diff options
author | 2020-12-24 12:54:45 +0100 | |
---|---|---|
committer | 2020-12-24 12:54:45 +0100 | |
commit | da3b7eacf125f1569fa5c5b50b60941a65d5067f (patch) | |
tree | 1c17197062bd6dcb61b8f8a3a8f63d37569c68f0 /day21/day21-2.js | |
parent | 50fd0627cc74b72b48775e78271a11ab1bcd50dd (diff) | |
download | advent_of_code_2020-da3b7eacf125f1569fa5c5b50b60941a65d5067f.tar.gz advent_of_code_2020-da3b7eacf125f1569fa5c5b50b60941a65d5067f.tar.bz2 advent_of_code_2020-da3b7eacf125f1569fa5c5b50b60941a65d5067f.zip |
day21
Diffstat (limited to 'day21/day21-2.js')
-rw-r--r-- | day21/day21-2.js | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/day21/day21-2.js b/day21/day21-2.js new file mode 100644 index 0000000..a5c697f --- /dev/null +++ b/day21/day21-2.js @@ -0,0 +1,46 @@ +const data = require('./data') +let arr = data + .split(/\n/g).filter(Boolean) + .map(l => l.replace(')','').split(' (contains ')) + .map(l => [l[0].split(' '), l[1].split(', ')]) + +const ingredients = {} +const allergens = {} + +for (let i=0; i<arr.length; i++) { + for (let j=0; j<arr[i][0].length; j++) { + let ingredient = arr[i][0][j] + if (!ingredients[ingredient]) { ingredients[ingredient] = [] } + ingredients[ingredient].push(i) + } + for (let k=0; k<arr[i][1].length; k++) { + let allergen = arr[i][1][k] + if (!allergens[allergen]) { allergens[allergen] = [] } + allergens[allergen].push(i) + } +} + +const variants = {} + Object.values(allergens).forEach((allergen, i) => { + const iv = Object.entries(ingredients).filter(i => allergen.every(a => i[1].includes(a))) + if (iv) { variants[Object.keys(allergens)[i]] = iv } +}) + +while (Object.values(variants).some(iv => iv.length > 1)) { + Object.entries(variants).forEach(iv => { + if (iv[1].length === 1) { + Object.keys(variants).forEach(ik => { + if (ik !== iv[0]) { + variants[ik] = variants[ik].filter(x => x[0] != iv[1][0][0]) + } + }) + } + }) +} + +const result = Object.entries(variants) + .sort((a, b) => a[0].localeCompare(b[0])) + .map(r => r[1][0][0]) + .join(',') + +console.log('Answer: ', result) |