Created
December 3, 2020 03:57
-
-
Save gacardinal/89a1694cf81d1bc52e319d7dfaa7a115 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 1 TypeScript
This file contains hidden or 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
import { readFileSync } from 'fs'; | |
const expenses = readFileSync('input.txt').toString('utf8').split('\n').map(n => parseInt(n)); | |
const threeNumberSumIndices = (numbers: number[], targetSum: number) : [number, number, number] | null=> { | |
let first, second, third; | |
for (let i = 0; i < numbers.length; i++) { | |
first = numbers[i]; | |
for (let j = i + 1; j < numbers.length; j++) { | |
second = numbers[j]; | |
for (let k = i + 1; k < numbers.length; k++) { | |
third = numbers[k]; | |
if (first + second + third === targetSum) { | |
return [i, j, k]; | |
} | |
} | |
} | |
} | |
return null; | |
} | |
/** | |
* Finds the indices of two numbers adding up to `targetSum` in a list of numbers. Returns `null` if | |
* no combination of two numbers is found | |
* @param numbers The list of numbers in which to find indices | |
* @param targetSum The sum to find two numbers adding up to | |
*/ | |
const twoNumberSumIndices = (numbers: number[], targetSum: number) : [number, number] | null=> { | |
let currentLHS, currentRHS; | |
for (let i = 0; i < numbers.length; i++) { | |
currentLHS = numbers[i]; | |
for (let j = i + 1; j < numbers.length; j++) { | |
currentRHS = numbers[j]; | |
if (currentLHS + currentRHS === targetSum) { | |
return [i, j]; | |
} | |
} | |
} | |
return null; | |
} | |
const twoIndices = twoNumberSumIndices(expenses, 2020); | |
if (twoIndices) { | |
const [lhs, rhs] = twoIndices; | |
console.log("Chapter 1", expenses[lhs] * expenses[rhs]); | |
} else { | |
throw new Error('No indices found'); | |
} | |
const threeIndices = threeNumberSumIndices(expenses, 2020); | |
if (threeIndices) { | |
const [first, second, third] = threeIndices; | |
console.log("Chapter 2", expenses[first] * expenses[second] * expenses[third]); | |
} else { | |
throw new Error('No indices found'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment