import { readFileSync } from 'fs'; import { join } from 'path'; function findNDupes(inputArrays): string { var countMap = {}; for (const inputArray of inputArrays) { const s = new Set(inputArray); s.forEach(function(val){ if (val in countMap) { countMap[val] += 1; } else { countMap[val] = 1; } }); } for (const key in countMap) { if (countMap[key] == inputArrays.length) { return key; } } } const fileString = readFileSync(join(__dirname, "inp"), 'utf-8'); const rucksacks = fileString.split("\n"); var sum: number = 0; for (const rucksack of rucksacks) { if (rucksack.length == 0) { continue; } const items = rucksack.split(''); const firstHalf = items.slice(0, items.length/2); const secondHalf = items.slice(items.length/2, items.length); const ndup = findNDupes([firstHalf, secondHalf]) const s = new Set(ndup); s.forEach(function(val){ const charNum = val.charCodeAt(0); if (charNum > 96) { sum += charNum - 96; } else { sum += charNum - 38; } }); } console.log(sum); sum = 0; for (var i = 0; i < rucksacks.length; i += 3) { if (i + 1 >= rucksacks.length) { continue; } const r1 = rucksacks[i].split(''); const r2 = rucksacks[i+1].split(''); const r3 = rucksacks[i+2].split(''); const ndup = findNDupes([r1, r2, r3]) const s = new Set(ndup); s.forEach(function(val){ const charNum = val.charCodeAt(0); if (charNum > 96) { sum += charNum - 96; } else { sum += charNum - 38; } }); } console.log(sum);