104 lines
2.5 KiB
JavaScript
104 lines
2.5 KiB
JavaScript
import { readFileSync, promises as fsPromises } from "fs";
|
|
|
|
async function asyncReadFile(filename) {
|
|
try {
|
|
const contents = await fsPromises.readFile(filename, "utf-8");
|
|
|
|
const arr = contents.split(/\r?\n/);
|
|
|
|
// console.log(arr); // 👉️ ['One', 'Two', 'Three', 'Four']
|
|
|
|
return arr;
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
// dial 0-99
|
|
|
|
const DIAL_START = 50;
|
|
|
|
const Dial = (start = DIAL_START) => {
|
|
let countZero = 0,
|
|
current = start;
|
|
const getCountZero = () => countZero,
|
|
reset = () => {
|
|
countZero = 0;
|
|
current = start;
|
|
},
|
|
rotate = (initialVal = "") => {
|
|
const val = initialVal.trim(),
|
|
dir = val.length ? val.substring(0, 1).toUpperCase() : "",
|
|
originalAmount = val.length ? val.substring(1) * 1 : 0,
|
|
amount = originalAmount % 100,
|
|
hundreds = Math.floor(originalAmount / 100);
|
|
|
|
if (!dir) {
|
|
console.log(`${val} => invalid value!`);
|
|
}
|
|
|
|
const initial = current;
|
|
|
|
if (hundreds) {
|
|
countZero += hundreds;
|
|
console.log(`${val} => has hundreds: ${hundreds} x CountZero!`);
|
|
}
|
|
|
|
if (dir === "R") {
|
|
if (current + amount > 100) {
|
|
countZero++;
|
|
console.log(`${val} => passing 0: CountZero!`);
|
|
}
|
|
current = (current + amount) % 100;
|
|
} else if (dir === "L") {
|
|
if (current && current - amount < 0) {
|
|
countZero++;
|
|
console.log(`${val} => passing 0: CountZero!`);
|
|
}
|
|
current = (100 + current - amount) % 100;
|
|
}
|
|
console.log(
|
|
`${val} => rotating ${
|
|
dir === "R" ? "RIGHT" : "LEFT"
|
|
} ${amount} from ${initial} to ${current}`
|
|
);
|
|
|
|
if (current === 0) {
|
|
countZero++;
|
|
console.log("CountZero!");
|
|
}
|
|
};
|
|
|
|
return {
|
|
getCountZero,
|
|
reset,
|
|
rotate,
|
|
};
|
|
};
|
|
|
|
const dial = Dial();
|
|
|
|
// Test Data
|
|
/*
|
|
const dataToParse = [
|
|
"L68",
|
|
"L30",
|
|
"R48",
|
|
"L5",
|
|
"R60",
|
|
"L55",
|
|
"L1",
|
|
"L99",
|
|
"R14",
|
|
"L82",
|
|
];
|
|
*/
|
|
|
|
const dataToParse = await asyncReadFile("../input.txt");
|
|
|
|
dataToParse.forEach((val) => {
|
|
if (val.trim()) dial.rotate(val);
|
|
});
|
|
|
|
console.log(`Final countZero is ${dial.getCountZero()}`);
|