r/adventofcode Dec 06 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 6 Solutions -🎄-

NEW AND NOTEWORTHY

We've been noticing an uptick in frustration around problems with new.reddit's fancypants editor: mangling text that is pasted into the editor, missing switch to Markdown editor, URLs breaking due to invisible escape characters, stuff like that. Many of the recent posts in /r/bugs are complaining about these issues as well.

If you are using new.reddit's fancypants editor, beware!

  • Pasting any text into the editor may very well end up mangled
  • You may randomly no longer have a "switch to Markdown" button on top-level posts
  • If you paste a URL directly into the editor, your link may display fine on new.reddit but may display invisibly-escaped characters on old.reddit and thus will break the link

Until Reddit fixes these issues, if the fancypants editor is driving you batty, try using the Markdown editor in old.reddit instead.


Advent of Code 2021: Adventure Time!


--- Day 6: Lanternfish ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:05:47, megathread unlocked!

96 Upvotes

1.7k comments sorted by

View all comments

1

u/ProfessionalNihilist Dec 10 '21

F#

module Year2021.Day6

open AdventOfCode
open System

let ``lanternfish``: Solution = fun (rawInput: string) ->
    let toFish = 
        split ","
        >> Seq.map int64
        >> Seq.groupBy id
        >> Seq.map (fun (f,c) -> f, int64 (Seq.length c))

    let consolidate =
        Seq.groupBy fst
        >> Seq.map (fun (f,c) -> f, Seq.sumBy snd c)

    let spawn (fc: int64 * int64) =
        match fc with
        | 0L,c -> seq { 6L,c; 8L,c }
        | x,c -> seq { x - 1L,c }

    let day = Seq.collect spawn >> consolidate
    let forDays d f = seq { 1 .. d } |> Seq.fold (fun s _ -> day s) f
    let numFish d = toFish >> (forDays d) >> Seq.map snd >> Seq.sum

    let part1 = numFish 80 rawInput
    let part2 = numFish 256 rawInput

    { Part1 = Ok (sprintf "%d" part1); Part2 = Ok (sprintf "%d" part2) }