Skip to content

Commit

Permalink
day23p2
Browse files Browse the repository at this point in the history
  • Loading branch information
gamersi committed Dec 23, 2024
1 parent 8a1c5ba commit 1acf410
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 0 deletions.
74 changes: 74 additions & 0 deletions day23p2/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package day23p2

import (
"io"
"sort"
"strings"

"aoc/utils"
)

type Party map[string]bool

func Solve(r io.Reader) any {
lines := utils.ReadLines(r)

network := make(map[string]map[string]bool)

for _, line := range lines {
parts := strings.Split(line, "-")
a, b := parts[0], parts[1]
if _, ok := network[a]; !ok {
network[a] = make(map[string]bool)
}
network[a][b] = true
if _, ok := network[b]; !ok {
network[b] = make(map[string]bool)
}
network[b][a] = true
}

var largestParty Party

for c1 := range network {
party := dfs(network, c1, make(Party))
if len(party) > len(largestParty) {
largestParty = party
}
}
largestPartyPW := make([]string, 0, len(largestParty))
for k := range largestParty {
largestPartyPW = append(largestPartyPW, k)
}
sort.Strings(largestPartyPW)

return strings.Join(largestPartyPW, ",")
}

func dfs(network map[string]map[string]bool, c string, visited Party) Party {
visited[c] = true
var largestParty Party
NextParty:
for c2 := range network[c] {
if visited[c2] {
continue
}
for prev := range visited {
if !network[c2][prev] {
continue NextParty
}
}
party := dfs(network, c2, visited)
if len(party) > len(largestParty) {
largestParty = party
}
}
if len(largestParty) == 0 {
// deep clone visited
largestParty = make(Party)
for k, v := range visited {
largestParty[k] = v
}
}
return visited
}
64 changes: 64 additions & 0 deletions day23p2/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package day23p2

import (
"strings"
"testing"

"aoc/utils"
)

var testInput = `kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn`

func TestSolve(t *testing.T) {
tests := []struct {
input string
answer string
}{
{testInput, "co,de,ka,ta"},
}

if testing.Verbose() {
utils.Verbose = true
}

for _, test := range tests {
r := strings.NewReader(test.input)

result := Solve(r).(string)

if result != test.answer {
t.Errorf("Expected %s, got %s", test.answer, result)
}
}
}

0 comments on commit 1acf410

Please sign in to comment.