Created
April 9, 2021 12:12
-
-
Save timvisee/5745af2336d667bedcd2441749a0404c to your computer and use it in GitHub Desktop.
My Advent of Code solution for day 5 part 1, with explanation added. https://github.com/timvisee/advent-of-code-2020 / https://github.com/timvisee/advent-of-code-2020/blob/master/day05a/src/main.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn main() { | |
println!( | |
"{}", | |
// Read puzzle input | |
include_bytes!("../input.txt") | |
// For each line (each 10 character sequence, and a newline) | |
.chunks(11) | |
// Process the 10 character sequence, ignore the newline | |
.map(|b| b[..10] | |
.iter() | |
// Transform 10 character sequence in binary representation matching the value the | |
// sequence represents. | |
// | |
// You can transform the character sequence directly into binary with these rules: | |
// B, R = 1 | |
// F, L = 0 | |
// | |
// For example: | |
// FBFBBFFRLR = 0101100101 = 357 = 44 * 8 + 5 | |
// | |
// The B/R/F/L characters are represented as binary value in value, see ASCII, | |
// that's what I'm using here. I'm just processing each as 8-bit number. | |
// | |
// B/R and F/L have a common bit at the 3rd position (from the right). For B/R | |
// the 3rd bit is 0, for F/L the the third bit is 1. | |
// | |
// I invert the binary representation (using `!b`, where `b` is the current | |
// character) so B/R gets a 1-bit as 3rd character, F/L gets a 0-bit. | |
// I extract this bit and shift it to the first position to convert B/R to 1, and | |
// F/L to 0, which is what `(!b & 4) >> 2` is for. | |
// | |
// With `fold` I loop through the chararacters in the sequence one by one, and | |
// collect the result in `id`, after which it is returned. The `(id << 1)` | |
// expression shifts the value one position to the left to make space at the first | |
// position for the next character. | |
// | |
// We end up with a 10-bit number, representing our final value. | |
.fold(0, |id, b| (id << 1) | (!b & 4) as usize >> 2)) | |
// The puzzle asks for the highest seat ID, so we take just the highest number here. | |
.max() | |
.unwrap(), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment