| 1 | package graph |
| 2 | |
| 3 | import ( |
| 4 | "math/rand" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | func TestComponents(t *testing.T) { |
| 9 | g := New(0) |
| 10 | if mess, diff := diff(Components(g), [][]int{}); diff { |
| 11 | t.Errorf("Components %s", mess) |
| 12 | } |
| 13 | if mess, diff := diff(Connected(g), false); diff { |
| 14 | t.Errorf("Connected %s", mess) |
| 15 | } |
| 16 | |
| 17 | g = New(1) |
| 18 | if mess, diff := diff(Components(g), [][]int{{0}}); diff { |
| 19 | t.Errorf("Components %s", mess) |
| 20 | } |
| 21 | if mess, diff := diff(Connected(g), true); diff { |
| 22 | t.Errorf("Connected %s", mess) |
| 23 | } |
| 24 | |
| 25 | g.Add(0, 0) |
| 26 | if mess, diff := diff(Components(g), [][]int{{0}}); diff { |
| 27 | t.Errorf("Components %s", mess) |
| 28 | } |
| 29 | if mess, diff := diff(Connected(g), true); diff { |
| 30 | t.Errorf("Connected %s", mess) |
| 31 | } |
| 32 | |
| 33 | g = New(4) |
| 34 | g.Add(0, 1) |
| 35 | g.Add(2, 1) |
| 36 | if mess, diff := diff(Components(g), [][]int{{0, 1, 2}, {3}}); diff { |
| 37 | t.Errorf("Components %s", mess) |
| 38 | } |
| 39 | if mess, diff := diff(Connected(g), false); diff { |
| 40 | t.Errorf("Connected %s", mess) |
| 41 | } |
| 42 | |
| 43 | g.AddBoth(0, 1) |
| 44 | g.AddBoth(1, 2) |
| 45 | g.AddBoth(2, 3) |
| 46 | g.AddBoth(0, 3) |
| 47 | if mess, diff := diff(Components(g), [][]int{{0, 1, 2, 3}}); diff { |
| 48 | t.Errorf("Components %s", mess) |
| 49 | } |
| 50 | if mess, diff := diff(Connected(g), true); diff { |
| 51 | t.Errorf("Connected %s", mess) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | func BenchmarkConnected(b *testing.B) { |
| 56 | n := 1000 |
| 57 | b.StopTimer() |
| 58 | g := New(n) |
| 59 | for i := 0; i < n; i++ { |
| 60 | g.AddBoth(rand.Intn(n), rand.Intn(n)) |
| 61 | } |
| 62 | b.StartTimer() |
| 63 | for i := 0; i < b.N; i++ { |
| 64 | _ = Connected(g) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | func BenchmarkComponents(b *testing.B) { |
| 69 | n := 1000 |
| 70 | b.StopTimer() |
| 71 | g := New(n) |
| 72 | for i := 0; i < n; i++ { |
| 73 | g.AddBoth(rand.Intn(n), rand.Intn(n)) |
| 74 | } |
| 75 | b.StartTimer() |
| 76 | for i := 0; i < b.N; i++ { |
| 77 | _ = Components(g) |
| 78 | } |
| 79 | } |