-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07p1.odin
54 lines (46 loc) · 1.29 KB
/
07p1.odin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import "core:fmt"
import "core:slice"
import "core:strconv"
import "core:strings"
D07P1 :: proc() {
input_string := #load("./inputs/07.txt", string)
lines := strings.split(input_string, "\n", context.temp_allocator)
least_fuel := least_fuel_crab_alignment(lines[0], false)
fmt.printfln("Least fuel required to align crabs: %v", least_fuel)
}
least_fuel_crab_alignment :: proc(input: string, increasing_fuel_cost: bool) -> int {
crabs := parse_crabs(input)
defer delete(crabs)
min := crabs[0]
max := crabs[len(crabs) - 1]
least_fuel := max * max * len(crabs) // arbitrary large number
current_fuel := 0
for i in min ..= max {
for crab in crabs {
if increasing_fuel_cost {
distance := abs(crab - i)
fuel_used := (distance * (distance + 1)) / 2
current_fuel += fuel_used
} else {
current_fuel += abs(crab - i)
}
}
if current_fuel < least_fuel {
least_fuel = current_fuel
} else {
break // fuel cost is increasing, so no need to continue
}
current_fuel = 0
}
return least_fuel
}
parse_crabs :: proc(input: string) -> (crabs: [dynamic]int) {
crabs_strs := strings.split(input, ",", context.temp_allocator)
for crab_str in crabs_strs {
current_crab := strconv.atoi(crab_str)
append(&crabs, current_crab)
}
slice.sort(crabs[:])
return
}