Browse Source

Not there yet

Piotr Czajkowski 2 weeks ago
parent
commit
56ebcf1116
1 changed files with 48 additions and 1 deletions
  1. 48 1
      13/code.go

+ 48 - 1
13/code.go

@@ -53,6 +53,53 @@ func readInput(file *os.File) []Machine {
 	return machines
 }
 
+func min(a, b int) int {
+	if a < b {
+		return a
+	}
+
+	return b
+}
+
+func calculate(machine Machine, button int) [2]int {
+	var results [2]int
+	otherButton := (button + 1) % 2
+
+	if machine.x%machine.buttons[button].x == 0 && machine.y%machine.buttons[button].y == 0 {
+		results[button] = machine.x / machine.buttons[button].x
+		results[otherButton] = 0
+		return results
+	}
+
+	start := min(machine.x/machine.buttons[button].x, machine.y/machine.buttons[button].y)
+	for start > 0 {
+		if (machine.x-start*machine.buttons[button].x)%machine.buttons[otherButton].x == 0 && (machine.y-start*machine.buttons[button].y)%machine.buttons[otherButton].y == 0 {
+			results[button] = start
+			results[otherButton] = (machine.x - start*machine.buttons[button].x) / machine.buttons[otherButton].x
+			return results
+		}
+
+		start--
+	}
+
+	return results
+}
+
+func checkMachine(machine Machine) int {
+	results := calculate(machine, 0)
+
+	return results[0]*3 + results[1]
+}
+
+func part1(machines []Machine) int {
+	var result int
+	for _, machine := range machines {
+		result += checkMachine(machine)
+	}
+
+	return result
+}
+
 func main() {
 	if len(os.Args) < 2 {
 		log.Fatal("You need to specify a file!")
@@ -65,5 +112,5 @@ func main() {
 	}
 
 	machines := readInput(file)
-	fmt.Println(machines)
+	fmt.Println("Part1:", part1(machines))
 }