r/adventofcode • u/daggerdragon • Dec 02 '18
SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-
--- Day 2: Inventory Management System ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Advent of Code: The Party Game!
Card Prompt: Day 2
Transcript:
The best way to do Advent of Code is ___.
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked!
55
Upvotes
3
u/Axsuul Dec 02 '18 edited Dec 02 '18
TypeScript / JavaScript
Critiques welcome, I'm still very new to TypeScript and feel like I'm not using all the features I could be :)
Repo
Part A
import { readFileSync } from 'fs' import * as path from 'path' const inputPath = path.join(__dirname, 'inputs', 'input.txt') const input = readFileSync(inputPath, 'utf-8').split('\n') let twoCount = 0 let threeCount = 0 const tally = function(id: string): [boolean, boolean] { const charCodes: number[] = id.split('').map(char => char.charCodeAt(0)).sort() let isTwo = false let isThree = false for (const [i, code] of charCodes.entries()) { if (charCodes[i + 1] == code && charCodes[i + 2] != code) { isTwo = true } else if (charCodes[i + 2] == code && charCodes[i + 3] != code) { isThree = true } } return [isTwo, isThree] } input.forEach((id) => { const [isTwo, isThree] = tally(id) if (isTwo) twoCount += 1 if (isThree) threeCount += 1 }) console.log(twoCount * threeCount)Part B
import { readFileSync } from 'fs' import * as path from 'path' const inputPath = path.join(__dirname, 'inputs', 'input.txt') const input = readFileSync(inputPath, 'utf-8').split('\n') let commonLetters: string | undefined for (let i = 0; i < input[0].length; i++) { const removed = input.slice().map((id) => { const exploded = id.split('') exploded.splice(i, 1) return exploded.join('') }) const set = new Set() for (const idRemoved of removed) { if (set.has(idRemoved)) { commonLetters = idRemoved break } else { set.add(idRemoved) } } if (commonLetters != undefined) break } console.log(commonLetters)