-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.js
51 lines (38 loc) · 1.41 KB
/
2.js
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
import input from "./input.js";
class AlignSubmarineCrabs {
crabsXPositions = []
minimumFuelRequired = null
constructor (crabsXPositions) {
this.crabsXPositions = crabsXPositions
for (let currentXPosition = 0; currentXPosition < this.crabsXPositions.length; currentXPosition++) {
const fuelAtPosition = this.getFuelAtPosition(currentXPosition)
if (false === fuelAtPosition) {
continue
}
if (null === this.minimumFuelRequired || fuelAtPosition < this.minimumFuelRequired) {
this.minimumFuelRequired = fuelAtPosition
}
}
}
getFuelAtPosition = (currentXPosition) => {
let fuelAtPosition = 0
this.crabsXPositions.forEach(crabXPosition => {
fuelAtPosition += (1 + Math.abs(currentXPosition - crabXPosition)) * Math.abs(currentXPosition - crabXPosition) / 2
if (null !== this.minimumFuelRequired && fuelAtPosition > this.minimumFuelRequired) {
return false
}
})
return fuelAtPosition
}
getResult = () => {
return this.minimumFuelRequired
}
}
const output = new AlignSubmarineCrabs(input).getResult()
console.log({
title: 'The Treachery of Whales [7.2]',
url: 'https://adventofcode.com/2021/day/7#part2',
inputPreview: input.slice(0, 10),
inputLength: input.length,
output,
})