DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 5: Binary Boarding

Collapse
 
scgrk profile image
Stephen Gerkin • Edited

Python in 2 lines

seats = [(int("".join(map(lambda x: "1" if x in "BR" else "0", s.rstrip())), 2)) for s in open("day5.txt")]
print(f"Highest: {max(seats)}\tYour seat: {next(filter(lambda x: x not in seats, range(min(seats), max(seats))))}")
Enter fullscreen mode Exit fullscreen mode

And a much more legible Kotlin

import java.io.File
import java.lang.Exception

const val filepath = "day5.txt"

fun main() {
    val seats = File(filepath)
        .readLines()
        .map { line -> line
            .map { ch -> if (ch in "BR") "1" else "0" }
            .joinToString("")
            .toInt(2) }

    val min = seats.minOrNull() 
        ?: throw Exception("Min not found")
    val max = seats.maxOrNull()
        ?: throw Exception("Max not found")

    val yourSeat = IntRange(min, max).firstOrNull { it !in seats } 
        ?: throw Exception("Seat not found")

    println("Highest seat number: $max\nYour seat number: $yourSeat")
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
scgrk profile image
Stephen Gerkin

I was curious to know if Python would let you execute a lambda immediately by wrapping it with parens and giving it the input, such as (lambda)(input) and ... sure enough you can. As such, I present this monstrosity in 1 line:

(lambda seats: print(f"Highest: {max(seats)}\nYour seat: {next(filter(lambda x: x not in seats, range(min(seats), max(seats))))}"))([(int("".join(map(lambda x: "1" if x in "BR" else "0", s.rstrip())), 2)) for s in open("day5.txt")])
Enter fullscreen mode Exit fullscreen mode