Finished day 5
This commit is contained in:
5
AdventOfCode2018/5thDay/challenge1/index.js
Normal file
5
AdventOfCode2018/5thDay/challenge1/index.js
Normal file
@@ -0,0 +1,5 @@
|
||||
const day4 = require('./istolethisfromsomeone');
|
||||
const fs = require('fs');
|
||||
|
||||
console.log('Part 1: ' + day4.part1(fs.readFileSync('input.txt').toString()));
|
||||
console.log('Part 2: ' + day4.part2(fs.readFileSync('input.txt').toString()));
|
||||
File diff suppressed because one or more lines are too long
44
AdventOfCode2018/5thDay/challenge1/istolethisfromsomeone.js
Normal file
44
AdventOfCode2018/5thDay/challenge1/istolethisfromsomeone.js
Normal file
@@ -0,0 +1,44 @@
|
||||
function part1(data) {
|
||||
const polymer = data.split("");
|
||||
const removeChar = ""; // No removal
|
||||
const stack = collapsePloymer(polymer, removeChar);
|
||||
return stack.length;
|
||||
}
|
||||
|
||||
function collapsePloymer(ploymerChars, removeChar) {
|
||||
const stack = [];
|
||||
for (let i = 0; i < ploymerChars.length; i++) {
|
||||
const char = ploymerChars[i];
|
||||
if (char.toLowerCase() === removeChar.toLowerCase()) {
|
||||
continue;
|
||||
}
|
||||
const last = stack.pop();
|
||||
if (!last) {
|
||||
stack.push(char);
|
||||
continue;
|
||||
}
|
||||
if (last.toLowerCase() === char.toLowerCase() && last !== char) {
|
||||
continue;
|
||||
}
|
||||
stack.push(last);
|
||||
stack.push(char);
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
function part2(data) {
|
||||
const polymer = data.split("");
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
|
||||
const collapsedPolymers = alphabet.map(letter =>
|
||||
collapsePloymer(polymer, letter)
|
||||
);
|
||||
const shortestCollapse = collapsedPolymers.reduce((longest, curr) =>
|
||||
longest.length < curr.length ? longest : curr
|
||||
);
|
||||
return shortestCollapse.length;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
part1: part1,
|
||||
part2: part2
|
||||
};
|
||||
Reference in New Issue
Block a user