You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

42 lines
1.1 KiB

import { readFileSync } from 'node:fs';
const input = readFileSync('input', 'utf-8');
function decToSnafu(num) {
const maxP = Math.floor(Math.log(num * 2) / Math.log(5));
return new Array(maxP + 1)
.fill()
.map((_, i) => i)
.reverse()
.reduce(([snafu, remainder], p) => {
const sign = remainder < 0 ? -1 : 1;
const mult = Math.floor(Math.abs(remainder) / Math.pow(5, p) + 0.5);
const val = sign * Math.pow(5, p) * mult;
const char = ['=', '-', '0', '1', '2'][sign * mult + 2];
return [snafu + char, remainder - val];
}, ['', num])[0];
}
function snafuToDec(snafu) {
return snafu
.split('')
.reverse()
.map((d, p) =>
Math.pow(5, p) *
(['=', '-', '0', '1', '2'].indexOf(d) - 2)
)
.reduce((total, num) => total + num);
}
const total = input
.split('\n')
.filter(line => !!line.trim())
.map(line => snafuToDec(line))
.reduce((total, value) => total + value);
const totalSnafu = decToSnafu(total);
console.log('The sum of all fuel requirements in SNAFU is:', totalSnafu);