Created
December 21, 2022 20:46
-
-
Save greenido/12ab9ec1b6b935743d414fc63612220c to your computer and use it in GitHub Desktop.
The monkeys are back! You're worried they're going to try to steal your stuff again, but it seems like they're just holding their ground and making various monkey noises at you. Eventually, one of the elephants realizes you don't speak monkey and comes over to interpret. As it turns out, they overheard you talking about trying to find the grove;…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// https://adventofcode.com/2022/day/21 | |
// | |
// Author: @greenido | |
// Date: 21-Dec-2022 | |
// | |
const fs = require('fs') | |
const monkeys = new Map(); | |
// | |
// Get the number that the monkey will yell | |
// Go deeper if the current monkey is holding a dependecy on two other dudes. | |
// | |
function getNumber(monkeyName, monkeyOp) { | |
if (isNaN(monkeyOp)) { | |
// It depnds on two other monkeys | |
let num1 = getNumber(monkeyOp.name1, monkeys.get(monkeyOp.name1)); | |
let op = monkeyOp.op; | |
let num2 = getNumber(monkeyOp.name2, monkeys.get(monkeyOp.name2)); | |
let res = 0; | |
if (op == '+') { | |
res = num1 + num2; | |
} | |
else if (op == '-') { | |
res = num1 - num2; | |
} | |
else if (op == '/') { | |
res = num1 / num2; | |
} | |
else if (op == '*') { | |
res = num1 * num2; | |
} | |
console.log(monkeyName + " return: " + res); | |
return res; | |
} | |
else { | |
// The monkey just yell the number | |
console.log(monkeyName + " return num: " + monkeyOp); | |
return monkeyOp; | |
} | |
} | |
// | |
// Start the party 📃 | |
// | |
try { | |
// read contents of the file | |
const data = fs.readFileSync('/Applications/MAMP/htdocs/adventofcode/day_21/data21.txt', 'UTF-8'); | |
// unit test data | |
//const data = fs.readFileSync('/Applications/MAMP/htdocs/adventofcode/day_21/unit-test-data21.txt', 'UTF-8'); | |
// split the contents by new line | |
const lines = data.split(/\r?\n/); | |
let totalScore = 0; | |
lines.forEach(line => { | |
let curInput = line.split(' ').map(element => element.trim()); | |
let monkeyName = curInput[0].replace(":", ""); | |
if (!isNaN(curInput[1])) { | |
monkeys.set(monkeyName, parseInt(curInput[1])); | |
} | |
else { | |
let moneyAction = { | |
name1: curInput[1], | |
op: curInput[2], | |
name2: curInput[3] | |
} | |
monkeys.set(monkeyName, moneyAction); | |
} | |
}); | |
//console.log(monkeys); | |
totalScore = getNumber('root' , monkeys.get("root")); | |
console.log("🌅🌅🌅 Total : " + totalScore); | |
} | |
catch (err) { | |
console.error(err); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment