DEV Community

loading...
Cover image for Advent of code - Day 21

Advent of code - Day 21

qmenoret profile image Quentin Ménoret ・2 min read

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.


Thank you for the break after Day #20 horrors 🙏
This one was clear, easy to work with and just challenging enough for a Monday!

Part 2 was actually free if you anticipated a little bit while doing the first part, so after reading the subject, it only took me 30 seconds to adapt the return value (since I already knew which allergens and ingredients were linked).

Anyway, here is my solution for day #21:

const lines = input.split('\n').map((line) => {
    const [_ingredients, _allergens] = line.split(' (')
    return {
      ingredients: _ingredients.split(' '),
      allergens: _allergens.slice(9, -1).split(', '),
    }
  })

  const allAllergens = Array.from(new Set(lines.reduce((acc, line) => [...acc, ...line.allergens], [])))
  const allIngredients = Array.from(new Set(lines.reduce((acc, line) => [...acc, ...line.ingredients], [])))

  const struct = allAllergens.reduce((acc, allergen) => {
    acc[allergen] = [...allIngredients]
    return acc
  }, {})

  lines.map((line) => {
    allAllergens.map((allergen) => {
      if (line.allergens.includes(allergen)) {
        struct[allergen] = struct[allergen].filter((ingredient) => line.ingredients.includes(ingredient))
      }
    })
  })

  while (true) {
    let found = false

    allAllergens.map((foundAllergen) => {
      if (struct[foundAllergen].length === 1) {
        const foundIngredient = struct[foundAllergen][0]
        allAllergens.map((allergen) => {
          if (allergen === foundAllergen) return
          if (struct[allergen].includes(foundIngredient)) {
            found = true
            const index = struct[allergen].indexOf(foundIngredient)
            struct[allergen].splice(index, 1)
          }
        })
      }
    })

    if (!found) break
  }

  console.log(
    allAllergens
      .sort()
      .map((allergen) => struct[allergen][0])
      .join(),
  )
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash

Discussion (0)

pic
Editor guide