Skip to content

Commit

Permalink
Cleanup day 10 solution (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomdewildt authored Dec 21, 2020
1 parent a0cd259 commit ede63cb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 18 deletions.
30 changes: 15 additions & 15 deletions internal/day10/day10.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,52 +32,52 @@ func AddCommandTo(cmd *cobra.Command) {
})
}

// Solve is used to find the solution to the problem. This function takes an stream
// Solve is used to find the solution to the problem. This function takes a stream
// of type io.Reader as input. It returns two integers and nil or 0, 0 and an error
// if one occurred.
func Solve(stream io.Reader) (int, int, error) {
input, err := input.ToIntSlice(stream)
adapters, err := input.ToIntSlice(stream)
if err != nil {
return 0, 0, err
}
sort.Ints(input)
sort.Ints(adapters)

diff1 := 0
diff3 := 1
prev := 0
for _, value := range input {
delta := value - prev
for _, adapter := range adapters {
delta := adapter - prev
if delta == 3 {
diff3++
} else if delta == 1 {
diff1++
}

prev = value
prev = adapter
}

input = append([]int{0}, input...)
permutations := permute(input, map[int]int{})
adapters = append([]int{0}, adapters...)
permutations := permute(adapters, map[int]int{})

return diff1 * diff3, permutations, nil
}

func permute(input []int, lookup map[int]int) int {
if len(input) == 1 {
func permute(adapters []int, lookup map[int]int) int {
if len(adapters) == 1 {
return 1
}

if count, ok := lookup[input[0]]; ok {
if count, ok := lookup[adapters[0]]; ok {
return count
}

count := 0
for i := 1; i < len(input); i++ {
if input[i]-input[0] <= 3 {
count += permute(input[i:], lookup)
for i := 1; i < len(adapters); i++ {
if adapters[i]-adapters[0] <= 3 {
count += permute(adapters[i:], lookup)
}
}
lookup[input[0]] = count
lookup[adapters[0]] = count

return count
}
6 changes: 3 additions & 3 deletions internal/day10/day10_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (
"github.com/tomdewildt/advent-of-code-2020/pkg/input"
)

func TestSolveInvalidStream(t *testing.T) {
stream := input.FromLiteral("abc\n20\n30\n40\n50\n")
func TestSolveInvalidAdapter(t *testing.T) {
stream := input.FromLiteral("abc")

solution1, solution2, err := Solve(stream)

Expand All @@ -19,7 +19,7 @@ func TestSolveInvalidStream(t *testing.T) {
}

func TestSolve(t *testing.T) {
stream := input.FromLiteral("16\n10\n15\n5\n1\n11\n7\n19\n6\n12\n4\n")
stream := input.FromLiteral("16\n10\n15\n5\n1\n11\n7\n19\n6\n12\n4")

solution1, solution2, err := Solve(stream)

Expand Down

0 comments on commit ede63cb

Please sign in to comment.