From d94663d31037a91afe5d32784919d859d94d812e Mon Sep 17 00:00:00 2001 From: Ben Charlton Date: Tue, 12 Dec 2017 21:41:07 +0000 Subject: [PATCH] day 12 --- 12/12.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++ 12/12_test.go | 40 ++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 12/12.go create mode 100644 12/12_test.go diff --git a/12/12.go b/12/12.go new file mode 100644 index 0000000..f6c93c5 --- /dev/null +++ b/12/12.go @@ -0,0 +1,86 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strings" + "strconv" +) + +// cat input | go run 12.go + +type pipedata struct { + pipe int + linkedTo []int +} + +func main() { + + scanner := bufio.NewScanner(os.Stdin) + + var pd = []pipedata{} + + for scanner.Scan() { + + s := strings.Split(scanner.Text(), " <-> ") + pipe,_ := strconv.Atoi(s[0]) + + var linkedTo = []int{} + l := strings.Split(s[1], ", ") + for t := range l { + i, _ := strconv.Atoi(l[t]) + linkedTo = append(linkedTo, i) + } + + pd = append(pd, pipedata{pipe, linkedTo}) + } + + cp := CountPipes(pd) + seenGroups := make(map[int]int) + groups,_ := CountGroups(seenGroups, pd) + + fmt.Println(cp,groups) +} + + +func CountPipes(pipedata []pipedata) int { + seen := make(map[int]int) + seen = getChildren(seen, pipedata, 0) + fmt.Println(seen) + + count := 0 + for range seen { + count++ + } + + return count + +} + +func CountGroups(seen map[int]int, pipedata []pipedata) (int,map[int]int) { + count := 0 + for i := range pipedata { + if seen[i] > 0 { + continue + } else { + seen = getChildren(seen, pipedata, i) + count++ + } + } + return count,seen +} + +func getChildren(seen map[int]int, pipedata []pipedata, pipe int) map[int]int { + + p := pipedata[pipe] + for l := range p.linkedTo { + child := p.linkedTo[l] + if (seen[child] == 0) { + seen[child]++ + seen = getChildren(seen, pipedata, child) + } + } + + return seen +} \ No newline at end of file diff --git a/12/12_test.go b/12/12_test.go new file mode 100644 index 0000000..3ae766c --- /dev/null +++ b/12/12_test.go @@ -0,0 +1,40 @@ +package main + +import ( + "testing" +) + + + var tests = []pipedata{ + {0, []int{2}}, + {1, []int{1}}, + {2, []int{0, 3, 4}}, + {3, []int{2, 4}}, + {4, []int{2, 3, 6}}, + {5, []int{6}}, + {6, []int{4, 5}}, + } + +func TestCountPipes(t *testing.T) { + v := CountPipes(tests) + if v != 6 { + t.Error( + "For", tests, + "expected 6", + "got", v, + ) + } +} + + +func TestCountGroups(t *testing.T) { + seen := make(map[int]int) + v,_ := CountGroups(seen, tests) + if v != 2 { + t.Error( + "For", tests, + "expected 2", + "got", v, + ) + } +} \ No newline at end of file