Skip to content

Instantly share code, notes, and snippets.

@gacardinal
Created December 3, 2020 03:57
Show Gist options
  • Save gacardinal/89a1694cf81d1bc52e319d7dfaa7a115 to your computer and use it in GitHub Desktop.
Save gacardinal/89a1694cf81d1bc52e319d7dfaa7a115 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 1 TypeScript
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