From d0bc450d25e7534c8b73ac3dc7cb9972107e4afd Mon Sep 17 00:00:00 2001 From: Eric Wagoner Date: Sat, 3 Dec 2022 18:05:29 -0500 Subject: [PATCH] Solutions for day 3 --- 03/code.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 03/code.js diff --git a/03/code.js b/03/code.js new file mode 100644 index 0000000..fc279ce --- /dev/null +++ b/03/code.js @@ -0,0 +1,59 @@ +const fs = require('fs'); + +const inputArray = fs.readFileSync('input.txt').toString().split("\n"); + +// Part One +let totalPriority = 0; + +for (i in inputArray) { + const contents = (inputArray[i]); + const intersection = getIntersection(contents); + const priority = getPriority(intersection); + totalPriority += priority; +} + +console.log(totalPriority); + + +// Part Two +totalPriority = 0; +let group = []; + +for (i in inputArray) { + const contents = (inputArray[i]); + group.push(contents.split("")); + if (group.length === 3) { + const badge = getBadge(group); + const priority = getPriority(badge); + totalPriority += priority; + group = []; + } +} + +console.log(totalPriority); + +// functions + +function getBadge(arrs) { + let badge = arrs[0]; + for(let i = 1; i < arrs.length; i++){ + badge = intersection(badge, arrs[i]); + }; + return badge[0]; +} + +function getIntersection(contents) { + const length = contents.length; + const first = contents.substring(0, length / 2).split(""); + const second = contents.substring(length / 2).split(""); + return intersection(first, second)[0]; +} + +function getPriority(char) { + const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + return characters.indexOf(char) + 1; +} + +function intersection(first, second) { + return first.filter(x => second.includes(x)); +};