56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { readLines } from "https://deno.land/std@0.177.1/io/read_lines.ts";
|
|
|
|
async function Part1() {
|
|
const file = await Deno.open("./Day7/input.txt");
|
|
const lines = readLines(file);
|
|
let line: string = (await lines.next()).value;
|
|
|
|
const positions = (line.split(","))
|
|
.map(x => +x)
|
|
.sort((a,b) => a - b)
|
|
.map(x => +x);
|
|
|
|
let optimalPosition = 0;
|
|
|
|
if (positions.length % 2 == 1) {
|
|
optimalPosition = positions[ (positions.length -1) / 2];
|
|
} else {
|
|
optimalPosition = positions[positions.length / 2];
|
|
}
|
|
|
|
const cost = positions
|
|
.map(x => Math.abs(x - optimalPosition))
|
|
.reduce((a,x) => a + x);
|
|
|
|
return cost;
|
|
}
|
|
|
|
async function Part2() {
|
|
const file = await Deno.open("./Day7/input.txt");
|
|
const lines = readLines(file);
|
|
let line: string = (await lines.next()).value;
|
|
|
|
const positions = (line.split(","))
|
|
.map(x => +x);
|
|
|
|
const mean = positions.reduce((a,x) => a + x) / positions.length;
|
|
const optimalFloor = Math.floor(mean);
|
|
const optimalCeil = Math.ceil(mean);
|
|
|
|
const fuel = (x : number) => x * (x + 1) / 2;
|
|
|
|
const FuelCostFloor = positions
|
|
.map(x => fuel(Math.abs(x-optimalFloor)))
|
|
.reduce((a,x) => a + x);
|
|
|
|
const FuelCostCeil = positions
|
|
.map(x => fuel(Math.abs(x-optimalCeil)))
|
|
.reduce((a,x) => a + x);
|
|
|
|
const cost = Math.min(FuelCostFloor,FuelCostCeil);
|
|
|
|
return cost;
|
|
}
|
|
|
|
console.log("Part1: " + await Part1());
|
|
console.log("Part1: " + await Part2()); |