This commit is contained in:
Gregory 2022-05-04 18:03:29 +03:00
parent b196009d5a
commit 3656193dfa
5 changed files with 109 additions and 0 deletions

65
d12/common.go Normal file
View file

@ -0,0 +1,65 @@
package d12
import (
"strings"
)
type caveMap map[string][]string
func getLines(in string) []string {
return strings.Split(strings.TrimSpace(in), "\n")
}
func getPairs(lines []string) [][]string {
pairs := [][]string{}
for _, line := range lines {
pairs = append(pairs, strings.Split(line, "-"))
}
return pairs
}
func createMap(paths [][]string) caveMap {
caveMap := make(map[string][]string)
for _, path := range paths {
left := path[0]
right := path[1]
caveMap[left] = append(caveMap[left], right)
caveMap[right] = append(caveMap[right], left)
}
return caveMap
}
func countPaths(caveMap caveMap, key string, visited map[string]int, duplicate bool) int {
count := 0
if key == "end" {
return 1
}
if visited[key] > 0 {
if key == "start" {
return 0
}
if strings.ToUpper(key) != key {
if duplicate {
return 0
} else {
duplicate = true
}
}
}
visited[key]++
for _, path := range caveMap[key] {
count += countPaths(caveMap, path, visited, duplicate)
}
visited[key]--
return count
}

31
d12/d12_test.go Normal file
View file

@ -0,0 +1,31 @@
package d12
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestP1(t *testing.T) {
in := `start-A
start-b
A-c
A-b
b-d
A-end
b-end`
assert.EqualValues(t, 10, P1(in))
}
func TestP2(t *testing.T) {
in := `start-A
start-b
A-c
A-b
b-d
A-end
b-end`
assert.EqualValues(t, 36, P2(in))
}

5
d12/p1.go Normal file
View file

@ -0,0 +1,5 @@
package d12
func P1(input string) int {
return countPaths(createMap(getPairs(getLines(input))), "start", make(map[string]int), true)
}

5
d12/p2.go Normal file
View file

@ -0,0 +1,5 @@
package d12
func P2(input string) int {
return countPaths(createMap(getPairs(getLines(input))), "start", make(map[string]int), false)
}

View file

@ -10,6 +10,7 @@ import (
"github.com/fotonmoton/aoc2021/d1"
"github.com/fotonmoton/aoc2021/d10"
"github.com/fotonmoton/aoc2021/d11"
"github.com/fotonmoton/aoc2021/d12"
"github.com/fotonmoton/aoc2021/d2"
"github.com/fotonmoton/aoc2021/d3"
"github.com/fotonmoton/aoc2021/d4"
@ -52,4 +53,6 @@ func main() {
fmt.Printf("day 10 part 2: %v\n", d10.P2(client.Day(10)))
fmt.Printf("day 11: %v\n", d11.P1(client.Day(11)))
fmt.Printf("day 11 part 2: %v\n", d11.P2(client.Day(11)))
fmt.Printf("day 12: %v\n", d12.P1(client.Day(12)))
fmt.Printf("day 12 part 2: %v\n", d12.P2(client.Day(12)))
}