|
1 | 1 | const sum = (x, y) => x + y
|
2 | 2 |
|
3 |
| -const getFuel = (crabs, destination) => { |
4 |
| - return crabs.map((crab) => Math.abs(crab - destination)) |
5 |
| - .reduce(sum) |
| 3 | +const getFuel = (crabs, destination, exponential = false) => { |
| 4 | + const simpleCalc = (crab) => { |
| 5 | + const distance = Math.abs(crab - destination) |
| 6 | + return distance |
| 7 | + } |
| 8 | + |
| 9 | + const expoCalc = (crab) => { |
| 10 | + const distance = Math.abs(crab - destination) |
| 11 | + let fuel = 0 |
| 12 | + for (let x = 1; x <= distance; x++) { |
| 13 | + fuel += x |
| 14 | + } |
| 15 | + return fuel |
| 16 | + } |
| 17 | + |
| 18 | + if (exponential) { |
| 19 | + return crabs.map(expoCalc).reduce(sum) |
| 20 | + } |
| 21 | + return crabs.map(simpleCalc).reduce(sum) |
6 | 22 | }
|
7 | 23 |
|
8 |
| -const getLeastFuel = (crabs) => { |
9 |
| - const positions = crabs |
10 |
| - let fuel = crabs.length * crabs.length // assume a cluster of crabs super far away is the initial worst case |
11 |
| - positions.forEach((position) => { |
12 |
| - fuel = Math.min(fuel, getFuel(crabs, position)) |
13 |
| - }) |
| 24 | +const getLeastFuel = (crabs, exponential = false) => { |
| 25 | + const positions = JSON.parse(JSON.stringify(crabs)) // Deep copy to ensure we aren't mutating the original data |
| 26 | + let fuel = 100000000 // assume a stupid high fuel count to start |
| 27 | + const highest = positions.sort((a, b) => b - a)[0] // Find the largest position |
| 28 | + for (let x = 0; x <= highest; x++) { |
| 29 | + console.debug(`Checking position ${x}`) |
| 30 | + const proposed = getFuel(crabs, x, exponential) |
| 31 | + console.debug(`Needed fuel would be ${proposed}`) |
| 32 | + fuel = Math.min(fuel, proposed) |
| 33 | + } |
14 | 34 | return fuel
|
15 | 35 | }
|
16 | 36 |
|
|
0 commit comments