adventofcode2022/02/code.js

101 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-12-02 05:38:17 +00:00
const fs = require('fs');
const inputArray = fs.readFileSync('input.txt').toString().split("\n");
// Part One
let totalScore = 0;
for (i in inputArray) {
const value = (inputArray[i]);
const throws = value.split(" ");
const result = getResult(throws[0], throws[1]);
const score = getScore(result, throws[1]);
totalScore += score;
}
console.log(totalScore);
// Part Two
totalScore = 0;
for (i in inputArray) {
const value = (inputArray[i]);
const throws = value.split(" ");
const result = getThrownResult(throws[1]);
const thrownThrow = getThrownThrow(throws[0], throws[1]);
const score = result + thrownThrow;
totalScore += score;
}
console.log(totalScore);
// functions
function getResult(them, me) {
let result;
if (them === "A") {
if (me === "X") {
result = 1;
} else {
result = me === "Y" ? 2 : 0;
}
}
if (them === "B") {
if (me === "Y") {
result = 1;
} else {
result = me === "Z" ? 2 : 0;
}
}
if (them === "C") {
if (me === "Z") {
result = 1;
} else {
result = me === "X" ? 2 : 0;
}
}
return result * 3;
}
function getScore(result, me) {
const options = ["X", "Y", "Z"];
const value = options.indexOf(me) + 1;
return value + result;
}
function getThrownResult(thrown) {
const results = ["X", "Y", "Z"];
return results.indexOf(thrown) * 3;
}
function getThrownThrow(them, me) {
let result;
if (them === "A") {
if (me === "Y") {
result = 1;
} else {
result = me === "X" ? 3 : 2;
}
}
if (them === "B") {
if (me === "Y") {
result = 2;
} else {
result = me === "X" ? 1 : 3;
}
}
if (them === "C") {
if (me === "Y") {
result = 3;
} else {
result = me === "X" ? 2 : 1;
}
}
return result;
}