meintspan

AoC Day 6 Part 2

Dec 6th, 2021 (edited)
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export const calculateLantarns = (input, iterations) => {
  2.     if (!input) {
  3.         return []
  4.     }
  5.  
  6.     const reSpawnRate = 7;
  7.     const newSpawnRate = 9;
  8.     const fishes = input.split(',').map(num => parseInt(num));
  9.  
  10.     const knownFish = fishes.length; // start length
  11.  
  12.     // Create array with days from current
  13.     const dayBuffer = Array.from({length: iterations + 1}, () => 0)
  14.  
  15.     // Count how often a known fish is spawn and add to buffer
  16.     fishes.forEach((fish) => {
  17.  
  18.         // amount of spawns of all remaining days
  19.         const spawns = Math.floor((iterations - fish - 1) / reSpawnRate)
  20.         for (let i = 0; i <= spawns; i++) {
  21.             const spawnDay = fish + (reSpawnRate * i) + 1
  22.             dayBuffer[spawnDay]++;
  23.         }
  24.  
  25.     })
  26.  
  27.     // Increase the daily buffer with new fish
  28.     // see per day how many fish will be added in remaining days
  29.     for (let day = 0; day < iterations; day++) {
  30.         const newFishesToday = dayBuffer[day]
  31.  
  32.         if (dayBuffer[day] > 0) {
  33.  
  34.             const spawns = Math.floor((iterations - day - newSpawnRate) / reSpawnRate)
  35.  
  36.             for (let i = 0; i <= spawns; i++) {
  37.  
  38.                 const spawnDay = day + newSpawnRate + (reSpawnRate * i)
  39.                 dayBuffer[spawnDay] += newFishesToday;
  40.             }
  41.         }
  42.     }
  43.     // Sum of dayBuffer (amount of fish that are spawned each day)
  44.     const spawnedFish = dayBuffer.reduce((accumulative, current) => accumulative + current);
  45.     return knownFish + spawnedFish
  46. }
Advertisement
Add Comment
Please, Sign In to add comment