Skip to content

Instantly share code, notes, and snippets.

@Karamell
Created December 21, 2020 07:19
Show Gist options
  • Select an option

  • Save Karamell/c226d2396c00313b392841be6a1106c3 to your computer and use it in GitHub Desktop.

Select an option

Save Karamell/c226d2396c00313b392841be6a1106c3 to your computer and use it in GitHub Desktop.
Advent of Coed 2020 day 21 in F#
#time "on"
let lines = System.IO.File.ReadAllLines ( __SOURCE_DIRECTORY__ + "/input.txt")
let pars (l: string array) =
l
|> Array.map(fun line ->
let [|f; a|] = line.Split("(")
f.Trim().Split(" ") |> Array.toList, a.TrimEnd(')').Split(" ")
|> Array.map(fun s -> s.TrimEnd(',')) |> Array.tail |> Array.toList)
|> Array.toList
let menu = pars lines
let allergenes = menu |> List.collect snd |> List.distinct
let aMap =
allergenes |> List.map(fun allergene ->
allergene,
menu
|> List.filter (snd >> fun a -> a |> List.contains(allergene))
|> List.map (fst >> Set.ofList)
)
let hasAllergenes =
aMap
|> List.map(fun a -> a |> snd |> Set.intersectMany)
|> List.reduce (+)
let allIngrediences = menu |> List.collect fst |> Set.ofList
let noAllergs = allIngrediences - hasAllergenes
let count = menu |> List.collect fst |> List.filter (fun i -> Set.contains i noAllergs) |> List.length
printfn "part1: %d" count
//part 2
let hasAllergenes2 =
aMap
|> List.map(fun (a, i) -> a, i |> Set.intersectMany)
let rec find (foundI:Set<string>) HA Aout =
let HA' = HA |> List.map(fun (a, i ) -> a, i - foundI )
match HA' with
| [] -> Aout
| r ->
let (a, i) = r |> List.find(fun (_, i ) -> i |> Set.count = 1)
let foundI' = foundI + i
let Aout' = Aout |> Map.add a i
let HA'' = HA' |> List.filter(snd >> fun s -> s <> i)
find foundI' HA'' Aout'
let r = find Set.empty hasAllergenes2 Map.empty
let part2 = System.String.Join(",", r |> Map.toList |> List.map (snd >> fun s -> (Set.toList s |> List.head)))
printfn "part2: %s" part2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment