diff --git a/2017/day15/main.go b/2017/day15/main.go new file mode 100644 index 0000000..23b5bb7 --- /dev/null +++ b/2017/day15/main.go @@ -0,0 +1,79 @@ +package main + +import ( + "flag" + "fmt" + "strings" + + "github.com/alexchao26/advent-of-code-go/mathutil" + "github.com/alexchao26/advent-of-code-go/util" +) + +func main() { + var part int + flag.IntVar(&part, "part", 1, "part 1 or 2") + flag.Parse() + fmt.Println("Running part", part) + + ans := duelingGenerators(util.ReadFile("./input.txt"), part) + fmt.Println("Output:", ans) +} + +func duelingGenerators(input string, part int) int { + values := parseInput(input) + + factors := []int{16807, 48271} + divisor := 2147483647 + + // set criteria for passing a value to judge, and rounds based on part num + criteria := []int{1, 1} + rounds := 40000000 + if part == 2 { + rounds = 5000000 + criteria = []int{4, 8} + } + + var judgeCount int + for i := 0; i < rounds; i++ { + for i, v := range values { + values[i] = getNextValue(v, factors[i], divisor, criteria[i]) + } + + // do the back 16 line up ? + // XOR them together, the last 16 should not have bits because they should + // should be zero'ed out. + // (XOR result) % (2^16) will be zero (i.e. no remainder) if back 16 match + compareVal := values[0] ^ values[1] + twoPow16 := 1 << 16 + if (compareVal % twoPow16) == 0 { + judgeCount++ + } + } + + return judgeCount +} + +// iterate until a value that can be passed to the judge is reached +// for part 1 the criteria will be 1, so only one iteration is made +// for part 2 it will be 4 or 8, so the loop will run until a good value is reached +func getNextValue(value, factor, divisor, criteria int) int { + // run at least once + value *= factor + value %= divisor + + for value%criteria != 0 { + value *= factor + value %= divisor + } + + return value +} + +func parseInput(input string) (ans []int) { + lines := strings.Split(input, "\n") + for _, l := range lines { + split := strings.Split(l, " starts with ") + ans = append(ans, mathutil.StrToInt(split[1])) + } + return ans +} diff --git a/2017/day15/main_test.go b/2017/day15/main_test.go new file mode 100644 index 0000000..ff8d4c2 --- /dev/null +++ b/2017/day15/main_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "testing" + + "github.com/alexchao26/advent-of-code-go/util" +) + +var example = `Generator A starts with 65 +Generator B starts with 8921` + +func Test_duelingGenerators(t *testing.T) { + tests := []struct { + name string + input string + part int + want int + }{ + {"example_part1", example, 1, 588}, + {"actual_part1", util.ReadFile("input.txt"), 1, 592}, + {"example_part2", example, 2, 309}, + {"actual_part2", util.ReadFile("input.txt"), 2, 320}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := duelingGenerators(tt.input, tt.part); got != tt.want { + t.Errorf("duelingGenerators() = %v, want %v", got, tt.want) + } + }) + } +}