r/adventofcode • • Dec 05 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 05 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It


--- Day 05: Binary Boarding ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for 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:49, megathread unlocked!

57 Upvotes

1.3k comments sorted by

View all comments

1

u/SureYeaah Dec 05 '20

Here's a compact solution in haskell.

module Day5 where

import Data.List (sort)

solve = solve2

solve1 :: IO ()
solve1 = interact $ show . maximum . map (seatID . getSeat) . lines

seatID :: (Int, Int) -> Int
seatID (r, c) = r * 8 + c

getSeat :: String -> (Int, Int)
getSeat s = (partition 'F' 'B' 0 127 s, partition 'L' 'R' 0 7 s)

partition :: Char -> Char -> Int -> Int -> String -> Int
partition _ _ l _ [] = l
partition cl cr l r (c:cs)
  | c == cl = partition cl cr l ((l+r) `div` 2) cs
  | c == cr = partition cl cr ((l+r+1) `div` 2) r cs
  | otherwise = partition cl cr l r cs

solve2 :: IO ()
solve2 = interact $ show . findSeat . sort . map (seatID . getSeat) . lines

findSeat :: [Int] -> Int
findSeat (x:y:xs)
  | x + 2 == y = x + 1
  | otherwise = findSeat (y:xs)
findSeat _ = error "broken"

1

u/daggerdragon Dec 05 '20

Your code is hard to read on old.reddit. As per our posting guidelines, would you please edit it using old.reddit's four-spaces formatting instead of new.reddit's triple backticks?

Put four spaces before every code line. (If you're using new.reddit, click the button in the editor that says "Switch to Markdown" first.)

[space space space space]public static void main()
[space space space space][more spaces for indenting]/* more code here*/

turns into

public static void main()
    /* more code here */

Alternatively, stuff your code in /u/topaz2078's paste or an external repo instead and link to that instead.

1

u/[deleted] Dec 05 '20

Even more compact, you can combine seatID, getSeat, and partition:

seatID :: String -> Int
seatID = foldl (\a x -> 2 * x + fromEnum (x == 'B' || x == 'R')) 0

1

u/SureYeaah Dec 05 '20

I feel stupid there was no need for all that it's just simple binary encoding smh. Thanks.