├── .gitignore ├── Cargo.toml ├── src ├── bin │ ├── day02b.rs │ ├── day01b.rs │ ├── day10b.rs │ ├── day05b.rs │ ├── day02.rs │ ├── day01.rs │ ├── day05.rs │ ├── day04.rs │ ├── day14.rs │ ├── day04b.rs │ ├── day09.rs │ ├── day15.rs │ ├── day10.rs │ ├── day15b.rs │ ├── day03.rs │ ├── day12.rs │ ├── day06.rs │ ├── day11.rs │ ├── day07.rs │ ├── day14b.rs │ ├── day03b.rs │ ├── day08.rs │ └── day13.rs └── lib.rs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "aoc2017" 3 | version = "0.1.0" 4 | authors = ["Adrian Perez de Castro "] 5 | 6 | [dependencies] 7 | bit-vec = "0.4" 8 | ego-tree = "0.1" 9 | failure = "0.1" 10 | num = "0.1" 11 | permutohedron = "0.2" 12 | 13 | [profile.release] 14 | lto = true 15 | -------------------------------------------------------------------------------- /src/bin/day02b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day02b.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use aoc2017::{ rows_of_digits, Permutations }; 10 | use std::io; 11 | 12 | 13 | fn main() 14 | { 15 | let stdin = io::stdin(); 16 | let mut sum = 0; 17 | for row in rows_of_digits(stdin.lock()) { 18 | for (a, b) in row.permutations() { 19 | if a != b && a % b == 0 { 20 | sum += a / b; 21 | break; 22 | } 23 | } 24 | } 25 | println!("{}", sum); 26 | } 27 | -------------------------------------------------------------------------------- /src/bin/day01b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day01b.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use std::io::{ self, Read }; 10 | use aoc2017::iter_digits; 11 | 12 | 13 | fn main() 14 | { 15 | let digits: Vec<_> = iter_digits(io::stdin().bytes()).collect(); 16 | 17 | let mut sum = 0; 18 | let step = digits.len() / 2; 19 | 20 | for (index, value) in digits.iter().enumerate() { 21 | if *value == digits[(index + step) % digits.len()] { 22 | sum += *value; 23 | } 24 | } 25 | 26 | println!("{}", sum); 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AOC2017 in Rust 2 | 3 | These are programs written in [Rust](https://rust-lang.org) which implement 4 | solutions for the [Advent of Code 2017](http://adventofcode.com/2017) (AoC). 5 | 6 | ## Code Structure 7 | 8 | This is a single `aoc2017` crate, which contains: 9 | 10 | - Some shared utility code in `src/lib.rs`. 11 | - Programs for each day's assignmens in `src/bin/*.rs`. 12 | 13 | ## Building 14 | 15 | The code needs a version of Rust that allows functions to return `impl Trait`. 16 | At the time of writing, this means using a nightly version of the compiler. 17 | Use Cargo normally for building: 18 | 19 | ```sh 20 | cargo build --release 21 | ``` 22 | -------------------------------------------------------------------------------- /src/bin/day10b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day10b.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use aoc2017::day10::KnotHash; 10 | use std::io; 11 | use std::io::prelude::*; 12 | 13 | 14 | fn trim<'a>(s: &'a [u8]) -> &'a [u8] { 15 | let mut l = 0; 16 | while l < s.len() && s[l].is_ascii_whitespace() { 17 | l += 1; 18 | } 19 | let mut r = s.len(); 20 | while r > l && s[r - 1].is_ascii_whitespace() { 21 | r -= 1; 22 | } 23 | return &s[l..r]; 24 | } 25 | 26 | 27 | fn main() 28 | { 29 | let mut input = Vec::new(); 30 | let stdin = io::stdin(); 31 | stdin.lock().read_to_end(&mut input).unwrap(); 32 | let mut kh = KnotHash::new(); 33 | kh.rounds(trim(&input)); 34 | println!("{:x}", kh); 35 | } 36 | -------------------------------------------------------------------------------- /src/bin/day05b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day05.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::io; 8 | use std::io::prelude::*; 9 | use std::str::FromStr; 10 | 11 | 12 | fn main() 13 | { 14 | let stdin = io::stdin(); 15 | let mut jumplist: Vec = stdin.lock() 16 | .lines() 17 | .filter_map(io::Result::ok) 18 | .map(|line| i32::from_str(&line)) 19 | .filter_map(Result::ok) 20 | .collect(); 21 | 22 | let mut pc: i32 = 0; 23 | let mut steps = 0; 24 | 25 | while pc >= 0 && (pc as usize) < jumplist.len() { 26 | steps += 1; 27 | let jump = jumplist[pc as usize]; 28 | jumplist[pc as usize] += if jump >= 3 { -1 } else { 1 }; 29 | pc += jump; 30 | } 31 | 32 | println!("steps: {}", steps); 33 | } 34 | -------------------------------------------------------------------------------- /src/bin/day02.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day02.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::io; 8 | use std::io::prelude::*; 9 | use std::str::FromStr; 10 | 11 | 12 | fn main() 13 | { 14 | let mut checksum = 0; 15 | 16 | let stdin = io::stdin(); 17 | for row in stdin.lock().lines().filter_map(io::Result::ok) { 18 | let mut rowmin = i32::max_value(); 19 | let mut rowmax = i32::min_value(); 20 | for value in row.split_whitespace().map(|s| i32::from_str(s).unwrap()) { 21 | if value < rowmin { 22 | rowmin = value; 23 | } 24 | if value > rowmax { 25 | rowmax = value; 26 | } 27 | } 28 | checksum += rowmax - rowmin; 29 | } 30 | 31 | println!("{}", checksum); 32 | } 33 | -------------------------------------------------------------------------------- /src/bin/day01.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day01.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use std::io::{ self, Read }; 10 | use aoc2017::iter_digits; 11 | 12 | 13 | fn main() 14 | { 15 | let mut digits = iter_digits(io::stdin().bytes()); 16 | let first = digits.next().unwrap(); 17 | let mut last = first; 18 | let mut sum = 0; 19 | 20 | loop { 21 | match digits.next() { 22 | None => break, 23 | Some(digit) => { 24 | if digit == last { 25 | sum += last; 26 | } 27 | last = digit; 28 | }, 29 | } 30 | } 31 | 32 | // Wrap around. 33 | if first == last { 34 | sum += last; 35 | } 36 | 37 | println!("{}", sum); 38 | } 39 | -------------------------------------------------------------------------------- /src/bin/day05.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day05.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::io; 8 | use std::io::prelude::*; 9 | use std::str::FromStr; 10 | 11 | 12 | fn main() 13 | { 14 | let stdin = io::stdin(); 15 | let mut jumplist: Vec = stdin.lock() 16 | .lines() 17 | .filter_map(io::Result::ok) 18 | .map(|line| i32::from_str(&line)) 19 | .filter_map(Result::ok) 20 | .collect(); 21 | 22 | let mut pc: i32 = 0; 23 | let mut steps = 0; 24 | 25 | while pc >= 0 && (pc as usize) < jumplist.len() { 26 | steps += 1; 27 | let jump = jumplist[pc as usize]; 28 | jumplist[pc as usize] += 1; // Increment jump. 29 | pc += jump; // Apply jump. 30 | } 31 | 32 | println!("steps: {}", steps); 33 | } 34 | -------------------------------------------------------------------------------- /src/bin/day04.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day04.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::collections::HashSet; 8 | use std::io; 9 | use std::io::prelude::*; 10 | 11 | 12 | fn main() 13 | { 14 | let stdin = io::stdin(); 15 | let mut valid = 0; 16 | let mut total = 0; 17 | for line in stdin.lock().lines().filter_map(io::Result::ok) { 18 | let mut seen_words = HashSet::new(); 19 | let mut is_valid = true; 20 | for word in line.split_whitespace() { 21 | if seen_words.contains(word) { 22 | is_valid = false; 23 | break; 24 | } 25 | seen_words.insert(word); 26 | } 27 | if is_valid { 28 | valid += 1; 29 | } 30 | total += 1; 31 | } 32 | println!("{}/{} valid", valid, total); 33 | } 34 | -------------------------------------------------------------------------------- /src/bin/day14.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day14.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use aoc2017::day14::{ make_row_hash, hex_char_to_u8 }; 10 | use std::io; 11 | use std::io::prelude::*; 12 | 13 | 14 | fn hex_string_bits(s: &str) -> u32 { 15 | let mut bits = 0; 16 | for c in s.chars() { 17 | let mut num = hex_char_to_u8(c); 18 | while num != 0 { 19 | if num & 0x1 == 0x1 { 20 | bits += 1; 21 | } 22 | num >>= 1; 23 | } 24 | } 25 | bits 26 | } 27 | 28 | 29 | fn main() 30 | { 31 | let stdin = io::stdin(); 32 | for line in stdin.lock().lines().filter_map(Result::ok) { 33 | let input_key = line.trim(); 34 | let mut used_bits = 0; 35 | for row in 0 .. 128 { 36 | let row_hash = make_row_hash(input_key, row); 37 | used_bits += hex_string_bits(&row_hash); 38 | } 39 | println!("Used cells: {}", used_bits); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/bin/day04b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day04b.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate permutohedron; 8 | 9 | use std::collections::HashSet; 10 | use std::io; 11 | use std::io::prelude::*; 12 | use permutohedron::Heap; 13 | 14 | 15 | fn main() 16 | { 17 | let stdin = io::stdin(); 18 | let mut valid = 0; 19 | let mut total = 0; 20 | for line in stdin.lock().lines().filter_map(io::Result::ok) { 21 | let mut seen_words = HashSet::new(); 22 | let mut is_valid = true; 23 | 'outer: for word in line.split_whitespace() { 24 | let mut word_chars: Vec = word.chars().collect(); 25 | let heap = Heap::new(&mut word_chars); 26 | for permutated_chars in heap { 27 | let permutation: String = permutated_chars.iter().collect(); 28 | if seen_words.contains(permutation.as_str()) { 29 | is_valid = false; 30 | break 'outer; 31 | } 32 | } 33 | seen_words.insert(word); 34 | } 35 | if is_valid { 36 | valid += 1; 37 | } 38 | total += 1; 39 | } 40 | println!("{}/{} valid", valid, total); 41 | } 42 | -------------------------------------------------------------------------------- /src/bin/day09.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day09.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::io::{ self, Read }; 8 | 9 | 10 | fn main() 11 | { 12 | let mut in_comment = false; 13 | let mut skip_next = false; 14 | let mut ngroups = 0; 15 | let mut nchars = 0; 16 | let mut score = 0; 17 | let mut score_stack = Vec::new(); 18 | score_stack.push(0); 19 | 20 | let stdin = io::stdin(); 21 | for ch in stdin.lock().bytes().filter_map(Result::ok) { 22 | if skip_next { 23 | skip_next = false; 24 | continue; 25 | } 26 | match ch { 27 | b'{' if !in_comment => { 28 | ngroups += 1; 29 | // Score for a group is "one more than the score of the 30 | // group that contains it". 31 | let current_score = score_stack.last().unwrap() + 1; 32 | score_stack.push(current_score); 33 | }, 34 | b'}' if !in_comment => { 35 | score += score_stack.pop().unwrap(); 36 | }, 37 | b'!' => skip_next = true, 38 | b'<' if !in_comment => in_comment = true, 39 | b'>' if in_comment => in_comment = false, 40 | _ if in_comment => nchars += 1, 41 | _ => (), // Do nothing. 42 | }; 43 | } 44 | println!("Groups: {}", ngroups); 45 | println!(" Score: {}", score); 46 | println!("NChars: {}", nchars); 47 | } 48 | -------------------------------------------------------------------------------- /src/bin/day15.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day15.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | #![feature(slice_patterns)] 8 | 9 | use std::io; 10 | use std::io::prelude::*; 11 | use std::str::FromStr; 12 | 13 | 14 | struct Generator 15 | { 16 | last: u64, 17 | factor: u64, 18 | } 19 | 20 | 21 | impl Generator 22 | { 23 | const DIVIDER: u64 = 2147483647; 24 | const FACTORA: u64 = 16807; 25 | const FACTORB: u64 = 48271; 26 | 27 | fn new(start: u64, factor: u64) -> Self { 28 | Self { last: start, factor: factor } 29 | } 30 | 31 | fn next(&mut self) -> u64 { 32 | self.last = (self.last * self.factor) % Self::DIVIDER; 33 | self.last 34 | } 35 | } 36 | 37 | 38 | const NPAIRS: usize = 40 * 1000 * 1000; 39 | 40 | 41 | fn main() 42 | { 43 | let stdin = io::stdin(); 44 | 45 | for line in stdin.lock().lines().filter_map(Result::ok) { 46 | let values: Vec<_> = line.split_whitespace() 47 | .map(u64::from_str).filter_map(Result::ok).collect(); 48 | assert_eq!(values.len(), 2); 49 | 50 | let mut a = Generator::new(values[0], Generator::FACTORA); 51 | let mut b = Generator::new(values[1], Generator::FACTORB); 52 | 53 | let mut matches = 0; 54 | for _ in 0 .. NPAIRS { 55 | if a.next() & 0xFFFF == b.next() & 0xFFFF { 56 | matches += 1; 57 | } 58 | } 59 | 60 | println!("{} matches", matches); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/bin/day10.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day10.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::io; 8 | use std::io::prelude::*; 9 | use std::str::FromStr; 10 | 11 | 12 | #[derive(Debug)] 13 | struct CircleString 14 | { 15 | list: Vec, 16 | pos: usize, 17 | skip: usize, 18 | } 19 | 20 | impl CircleString 21 | { 22 | fn new(size: usize) -> Self 23 | { 24 | assert!(size <= u32::max_value() as usize); 25 | let mut cs = CircleString { 26 | list: Vec::with_capacity(size), 27 | pos: 0, 28 | skip: 0, 29 | }; 30 | for value in 0..size { 31 | cs.list.push(value as u32); 32 | } 33 | cs 34 | } 35 | 36 | fn apply(&mut self, n: usize) 37 | { 38 | // 1. Reverse the order of elements pos..n 39 | let len = self.list.len(); 40 | let mut i = self.pos; 41 | let mut j = self.pos + n - 1; 42 | while i < j { 43 | self.list.swap(i % len, j % len); 44 | i += 1; 45 | j -= 1; 46 | } 47 | 48 | // 2. Increase position by n+skip 49 | self.pos = (self.pos + n + self.skip) % self.list.len(); 50 | 51 | // 3. Increase skip by one. 52 | self.skip += 1; 53 | } 54 | } 55 | 56 | 57 | fn main() 58 | { 59 | let stdin = io::stdin(); 60 | for line in stdin.lock().lines().filter_map(Result::ok) { 61 | let mut cs = CircleString::new(256); 62 | for length in line.split(',').map(usize::from_str).filter_map(Result::ok) { 63 | cs.apply(length); 64 | } 65 | println!("{}", cs.list[0] * cs.list[1]); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/bin/day15b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day15.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | #![feature(slice_patterns)] 8 | 9 | use std::io; 10 | use std::io::prelude::*; 11 | use std::str::FromStr; 12 | 13 | 14 | struct Generator 15 | { 16 | last: u64, 17 | factor: u64, 18 | multiplier: u64, 19 | } 20 | 21 | 22 | impl Generator 23 | { 24 | const DIVIDER: u64 = 2147483647; 25 | const FACTORA: u64 = 16807; 26 | const FACTORB: u64 = 48271; 27 | 28 | fn new(start: u64, factor: u64) -> Self { 29 | Self { 30 | last: start, 31 | factor: factor, 32 | multiplier: match factor { 33 | Self::FACTORA => 4, 34 | Self::FACTORB => 8, 35 | _ => 1, 36 | } 37 | } 38 | } 39 | 40 | fn next(&mut self) -> u64 { 41 | loop { 42 | self.last = (self.last * self.factor) % Self::DIVIDER; 43 | if self.last % self.multiplier == 0 { 44 | break; 45 | } 46 | } 47 | self.last 48 | } 49 | } 50 | 51 | 52 | const NPAIRS: usize = 5 * 1000 * 1000; 53 | 54 | 55 | fn main() 56 | { 57 | let stdin = io::stdin(); 58 | 59 | for line in stdin.lock().lines().filter_map(Result::ok) { 60 | let values: Vec<_> = line.split_whitespace() 61 | .map(u64::from_str).filter_map(Result::ok).collect(); 62 | assert_eq!(values.len(), 2); 63 | 64 | let mut a = Generator::new(values[0], Generator::FACTORA); 65 | let mut b = Generator::new(values[1], Generator::FACTORB); 66 | 67 | let mut matches = 0; 68 | for _ in 0 .. NPAIRS { 69 | if a.next() & 0xFFFF == b.next() & 0xFFFF { 70 | matches += 1; 71 | } 72 | } 73 | 74 | println!("{} matches", matches); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/bin/day03.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day03.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use aoc2017::day03::grid_size_for_cell; 10 | use std::io; 11 | use std::io::prelude::*; 12 | use std::str::FromStr; 13 | 14 | 15 | // For a memory grid, the center point is always "1", and the bottom-right 16 | // corner is "size * size = maxindex": 17 | // 18 | // 17 16 15 14 13 19 | // 18 5 4 3 12 20 | // 19 6 [1] 2 11 21 | // 20 7 8 [9] 10 22 | // 21 22 23 24 [25] = size * size 23 | // 24 | // The position we are searching for is always in the outer ring. We can 25 | // calculate the position by walking "backwards" in the spiral: The number 26 | // of steps is (size * size - cellindex). 27 | // 28 | fn manhattan_distance_for_cell(cellindex: u32) -> i64 29 | { 30 | let size = grid_size_for_cell(cellindex); 31 | 32 | // XXX: Probably this can be further simplified. 33 | let (x, y) = { 34 | let steps = size * size - cellindex; 35 | if steps < size { 36 | // Bottom row. 37 | (size - steps - 1, 0) 38 | } else { 39 | let steps = steps - (size - 1); 40 | if steps < size { 41 | // Left column. 42 | (0, steps) 43 | } else { 44 | let steps = steps - (size - 1); 45 | if steps < size { 46 | // Top column. 47 | (steps, size - 1) 48 | } else { 49 | let steps = steps - (size - 1); 50 | assert!(steps < size); 51 | // Right column. 52 | (size - 1, size - steps - 1) 53 | } 54 | } 55 | } 56 | }; 57 | 58 | let center = (size / 2) as i64; 59 | 60 | (center - x as i64).abs() + (center - y as i64).abs() 61 | } 62 | 63 | 64 | fn main() 65 | { 66 | let stdin = io::stdin(); 67 | for row in stdin.lock().lines().filter_map(io::Result::ok) { 68 | for cellindex in row.split_whitespace().map(|s| u32::from_str(s).unwrap()) { 69 | println!("{}", manhattan_distance_for_cell(cellindex)); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/bin/day12.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day12.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | #[macro_use] 8 | extern crate failure; 9 | 10 | use std::collections::{ HashMap, HashSet }; 11 | use std::io; 12 | use std::io::prelude::*; 13 | use std::str::FromStr; 14 | 15 | 16 | #[derive(Debug)] 17 | struct Pipe 18 | { 19 | from: u32, 20 | to: Vec, 21 | } 22 | 23 | impl FromStr for Pipe 24 | { 25 | type Err = ::failure::Error; 26 | 27 | fn from_str(s: &str) -> Result 28 | { 29 | if let Some(pos) = s.find("<->") { 30 | let (from_str, to_str) = s.split_at(pos); 31 | let mut to = Vec::new(); 32 | for num_str in to_str[3..].split(',').map(str::trim) { 33 | to.push(num_str.parse()?); 34 | } 35 | Ok(Pipe { from: from_str.trim().parse()?, to: to }) 36 | } else { 37 | bail!("Invalid pipe specification: '{}'", s) 38 | } 39 | } 40 | } 41 | 42 | 43 | fn add_connected_pipes(pipe_id: u32, 44 | pipes: &mut HashMap, 45 | connected_pipes: &mut HashSet) 46 | { 47 | // No more pipes to add. 48 | if pipes.is_empty() { 49 | return; 50 | } 51 | 52 | let pipe = if let Some(p) = pipes.remove(&pipe_id) { p } else { 53 | panic!("No pipe with id={} found", pipe_id); 54 | }; 55 | 56 | connected_pipes.insert(pipe.from); 57 | for pipe_id in pipe.to { 58 | if !connected_pipes.contains(&pipe_id) { 59 | add_connected_pipes(pipe_id, pipes, connected_pipes); 60 | } 61 | } 62 | } 63 | 64 | 65 | fn main() 66 | { 67 | let mut pipes = HashMap::new(); 68 | 69 | // Read all pipes. 70 | let stdin = io::stdin(); 71 | for line in stdin.lock().lines().filter_map(Result::ok) { 72 | let p: Pipe = line.parse().unwrap(); 73 | pipes.insert(p.from, p); 74 | } 75 | 76 | let mut connected_pipes = HashSet::new(); 77 | add_connected_pipes(0, &mut pipes, &mut connected_pipes); 78 | 79 | println!("Connected to 0: {}, disconnected: {}", 80 | connected_pipes.len(), pipes.len()); 81 | 82 | let mut ngroups = 1; // Count the group connected to 0. 83 | while !pipes.is_empty() { 84 | connected_pipes.clear(); // Start with an empty set. 85 | let &pipe_id = pipes.keys().next().unwrap(); 86 | add_connected_pipes(pipe_id, &mut pipes, &mut connected_pipes); 87 | ngroups += 1; 88 | } 89 | 90 | println!("Total groups: {}", ngroups); 91 | } 92 | -------------------------------------------------------------------------------- /src/bin/day06.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day06.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::collections::HashMap; 8 | use std::fmt; 9 | use std::io; 10 | use std::io::prelude::*; 11 | use std::str::FromStr; 12 | 13 | 14 | struct Memory 15 | { 16 | banks: Vec, 17 | } 18 | 19 | impl Memory 20 | { 21 | fn new(banks: Vec) -> Self { 22 | Self { banks: banks } 23 | } 24 | 25 | fn find_most_blocks(&self) -> (usize, u32) { 26 | let mut max_blocks = 0; 27 | let mut max_blocks_index = 0; 28 | for (index, blocks) in self.banks.iter().enumerate() { 29 | if *blocks > max_blocks { 30 | max_blocks_index = index; 31 | max_blocks = *blocks; 32 | } 33 | } 34 | (max_blocks_index, max_blocks) 35 | } 36 | 37 | fn reallocate(&mut self) { 38 | let (mut index, mut nblocks) = self.find_most_blocks(); 39 | 40 | // 1. Empty the bank 41 | self.banks[index] = 0; 42 | 43 | // 2. Redistribute among banks, starting with the next 44 | while nblocks > 0 { 45 | index = (index + 1) % self.banks.len(); // Move to next bank index 46 | self.banks[index] += 1; // Add one block to that bank 47 | nblocks -= 1; // One less block pending! 48 | } 49 | } 50 | 51 | fn id(&self) -> String { 52 | self.banks.iter().fold(None, |acc, &item| { 53 | if let Some(s) = acc { 54 | Some(format!("{},{}", s, item)) 55 | } else { 56 | Some(format!("{}", item)) 57 | } 58 | }).unwrap() 59 | } 60 | } 61 | 62 | impl fmt::Display for Memory 63 | { 64 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 65 | write!(f, "Mem<{}>{:?}", self.banks.len(), self.banks) 66 | } 67 | } 68 | 69 | 70 | fn main() 71 | { 72 | let stdin = io::stdin(); 73 | for row in stdin.lock().lines().filter_map(io::Result::ok) { 74 | let mut mem = Memory::new(row.split_whitespace() 75 | .map(u32::from_str) 76 | .filter_map(Result::ok) 77 | .collect()); 78 | let mut states = HashMap::new(); 79 | // states.insert(mem.id(), 0); 80 | 81 | for step in 1.. { 82 | mem.reallocate(); 83 | let id = mem.id(); 84 | if let Some(prev_step) = states.get(&id) { 85 | println!("steps: {}, cycle: {}, state: {}", 86 | step, step - prev_step, mem); 87 | break; 88 | } 89 | states.insert(id, step); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/bin/day11.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day11.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | // Awesome resource on hex grid tiling algorithms: 8 | // https://www.redblobgames.com/grids/hexagons/ 9 | 10 | #[macro_use] 11 | extern crate failure; 12 | 13 | use std::io; 14 | use std::io::prelude::*; 15 | use std::str::FromStr; 16 | 17 | 18 | #[derive(Debug)] 19 | pub enum Dir { 20 | N(u32), 21 | NE(u32), 22 | SE(u32), 23 | S(u32), 24 | SW(u32), 25 | NW(u32), 26 | } 27 | 28 | impl FromStr for Dir 29 | { 30 | type Err = ::failure::Error; 31 | 32 | fn from_str(s: &str) -> Result 33 | { 34 | Ok(match s { 35 | "n" => Dir::N(1), 36 | "ne" => Dir::NE(1), 37 | "se" => Dir::SE(1), 38 | "s" => Dir::S(1), 39 | "sw" => Dir::SW(1), 40 | "nw" => Dir::NW(1), 41 | _ => bail!("invalid direction: {}", s), 42 | }) 43 | } 44 | } 45 | 46 | 47 | mod coord { 48 | use super::Dir; 49 | 50 | #[derive(Default, Debug, Copy, Clone)] 51 | pub struct Axis { q: isize, r: isize } 52 | 53 | impl Axis { 54 | #[inline] 55 | pub fn new(q: isize, r: isize) -> Self { Axis { q: q, r: r } } 56 | 57 | #[inline] 58 | fn to_cube(&self) -> Cube { Cube::new(self.q, -self.q - self.r, self.r) } 59 | 60 | pub fn add(&self, d: Dir) -> Self { 61 | match d { 62 | Dir::N(s) => Axis::new(self.q, self.r - s as isize), 63 | Dir::NE(s) => Axis::new(self.q + s as isize, self.r - s as isize), 64 | Dir::SE(s) => Axis::new(self.q + s as isize, self.r), 65 | Dir::S(s) => Axis::new(self.q, self.r + s as isize), 66 | Dir::SW(s) => Axis::new(self.q - s as isize, self.r + s as isize), 67 | Dir::NW(s) => Axis::new(self.q - s as isize, self.r), 68 | } 69 | } 70 | 71 | pub fn distance_to(&self, other: &Axis) -> usize { 72 | self.to_cube().distance_to(&other.to_cube()) 73 | } 74 | } 75 | 76 | struct Cube { x: isize, y: isize, z: isize } 77 | 78 | impl Cube { 79 | #[inline] 80 | pub fn new(x: isize, y: isize, z: isize) -> Self { 81 | assert_eq!(0, x + y + z); 82 | Cube { x: x, y: y, z: z } 83 | } 84 | 85 | #[inline] 86 | pub fn distance_to(&self, other: &Cube) -> usize { 87 | ((self.x - other.x).abs() as usize + 88 | (self.y - other.y).abs() as usize + 89 | (self.z - other.z).abs() as usize) / 2 90 | } 91 | } 92 | } 93 | 94 | 95 | fn main() 96 | { 97 | let stdin = io::stdin(); 98 | let mut pos = coord::Axis::default(); 99 | let mut max_steps = 0; 100 | for s in stdin.lock().split(0x2C /* comma */) 101 | .filter_map(Result::ok) 102 | .map(String::from_utf8) 103 | .filter_map(Result::ok) 104 | { 105 | pos = pos.add(s.trim().parse::().unwrap()); 106 | let steps = pos.distance_to(&coord::Axis::default()); 107 | if steps > max_steps { 108 | max_steps = steps; 109 | } 110 | } 111 | println!("Steps: {}, max: {}", 112 | pos.distance_to(&coord::Axis::default()), 113 | max_steps); 114 | } 115 | -------------------------------------------------------------------------------- /src/bin/day07.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day07.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate ego_tree; 8 | 9 | #[macro_use] 10 | extern crate failure; 11 | 12 | use ego_tree::{ NodeMut, NodeRef, Tree }; 13 | use ego_tree::iter::Edge; 14 | use std::collections::HashMap; 15 | use std::io; 16 | use std::io::prelude::*; 17 | use std::str::FromStr; 18 | 19 | 20 | #[derive(Debug)] 21 | struct Tower 22 | { 23 | name: String, 24 | weight: u32, 25 | } 26 | 27 | 28 | impl FromStr for Tower 29 | { 30 | type Err = ::failure::Error; 31 | 32 | fn from_str(s: &str) -> Result 33 | { 34 | let pos = if let Some(p) = s.find(' ') { p } else { 35 | bail!("Input '{}' does not contain a space", s) 36 | }; 37 | 38 | let (name, weight_str) = s.split_at(pos); 39 | let weight = weight_str.trim() 40 | .trim_left_matches('(') 41 | .trim_right_matches(')') 42 | .parse()?; 43 | 44 | Ok(Tower { name: name.to_string(), weight: weight }) 45 | } 46 | } 47 | 48 | 49 | fn tree_node_fill(mut node: NodeMut, 50 | towers: &mut HashMap, 51 | parent: &HashMap) 52 | { 53 | let node_name = node.value().name.clone(); 54 | for (name, parent_name) in parent { 55 | if *parent_name == node_name { 56 | let mut child_node = node.append(towers.remove(name).unwrap()); 57 | tree_node_fill(child_node, towers, parent); 58 | } 59 | } 60 | } 61 | 62 | 63 | fn build_tree(mut towers: HashMap, 64 | parent: HashMap) -> Tree 65 | { 66 | let root_name = towers.keys() 67 | .filter(|&key| !parent.contains_key(key)) 68 | .next().unwrap().to_string(); 69 | 70 | let mut tree = Tree::new(towers.remove(&root_name).unwrap()); 71 | tree_node_fill(tree.root_mut(), &mut towers, &parent); 72 | tree 73 | } 74 | 75 | 76 | fn subtree_weight(node: NodeRef) -> u32 77 | { 78 | node.value().weight + node.children().fold(0, |sum, n| sum + subtree_weight(n)) 79 | } 80 | 81 | 82 | fn find_unbalanced_node(node: NodeRef) -> Option<(NodeRef, u32)> 83 | { 84 | if node.has_children() { 85 | let mut max_index = 0; 86 | let mut min_weight = u32::max_value(); 87 | let mut max_weight = u32::min_value(); 88 | 89 | for (index, weight) in node.children().map(subtree_weight).enumerate() { 90 | if weight > max_weight { 91 | max_weight = weight; 92 | max_index = index; 93 | } 94 | if weight < min_weight { 95 | min_weight = weight; 96 | } 97 | } 98 | 99 | if min_weight != max_weight { 100 | let node = node.children().nth(max_index).unwrap(); 101 | return Some((node, max_weight - min_weight)); 102 | } 103 | } 104 | 105 | None 106 | } 107 | 108 | 109 | fn main() 110 | { 111 | let mut parent = HashMap::new(); 112 | let mut towers = HashMap::new(); 113 | 114 | let stdin = io::stdin(); 115 | for line in stdin.lock().lines().filter_map(io::Result::ok) { 116 | // Each line of input is: () [-> child1[, child2, ...]] 117 | let (tower_str, child_str) = if let Some(arrow_pos) = line.find("->") { 118 | let (left, right) = line.split_at(arrow_pos); 119 | (left.trim(), right.trim_left_matches("->").trim()) 120 | } else { 121 | (line.as_str(), "") 122 | }; 123 | 124 | let tower = tower_str.parse::().unwrap(); 125 | 126 | if child_str.len() > 0 { 127 | for child in child_str.split(',') { 128 | parent.insert(child.trim().to_string(), tower.name.clone()); 129 | } 130 | } 131 | 132 | towers.insert(tower.name.clone(), tower); 133 | } 134 | 135 | let tree = build_tree(towers, parent); 136 | println!("Root: {}", tree.root().value().name); 137 | 138 | for node in tree.root().traverse().filter_map(|item| match item { 139 | Edge::Close(node) => Some(node), 140 | Edge::Open(_) => None 141 | }) { 142 | if let Some((n, weight_diff)) = find_unbalanced_node(node) { 143 | println!("Diff: {}: {} -> {}", 144 | n.value().name, n.value().weight, 145 | n.value().weight - weight_diff); 146 | break; 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/bin/day14b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day14b.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | extern crate bit_vec; 9 | extern crate num; 10 | 11 | use aoc2017::day14::{ make_row_hash, hex_char_to_u8 }; 12 | use bit_vec::BitVec; 13 | use num::Num; 14 | use std::io; 15 | use std::io::prelude::*; 16 | 17 | 18 | struct Bitmap 19 | { 20 | bits: BitVec, 21 | } 22 | 23 | 24 | impl Bitmap 25 | { 26 | const SIDE: usize = 128; 27 | 28 | fn new() -> Self { 29 | Self { 30 | bits: BitVec::from_elem(Self::SIDE * Self::SIDE, false) 31 | } 32 | } 33 | 34 | fn from_key(s: &str) -> Self { 35 | let mut bmap = Self::new(); 36 | for row in 0 .. Self::SIDE { 37 | let chars: Vec<_> = make_row_hash(s, row as u16).chars().map(hex_char_to_u8).collect(); 38 | let mut bytes = Vec::with_capacity(Self::SIDE / 2); 39 | for pair in chars.chunks(2) { 40 | bytes.push(pair[0] << 4 | pair[1]); 41 | } 42 | let row_bits = BitVec::from_bytes(&bytes); 43 | assert_eq!(row_bits.len(), Self::SIDE); 44 | for col in 0 .. Self::SIDE { 45 | bmap.set(col, row, row_bits.get(col).unwrap()); 46 | } 47 | } 48 | bmap 49 | } 50 | 51 | #[inline] 52 | fn set(&mut self, col: usize, row: usize, value: bool) { 53 | self.bits.set(row * Self::SIDE + col, value); 54 | } 55 | 56 | #[inline] 57 | fn get(&self, col: usize, row: usize) -> bool { 58 | if row >= Self::SIDE { 59 | panic!("Row index out of bounds: {}", row); 60 | } 61 | if col >= Self::SIDE { 62 | panic!("Column index out of bounds: {}", col); 63 | } 64 | self.bits.get(row * Self::SIDE + col).unwrap() 65 | } 66 | } 67 | 68 | 69 | struct BitmapLabels 70 | { 71 | bits: Vec, 72 | } 73 | 74 | 75 | impl BitmapLabels 76 | { 77 | const SIDE: usize = Bitmap::SIDE; 78 | 79 | fn new() -> Self { 80 | Self { bits: vec![T::zero(); Self::SIDE * Self::SIDE] } 81 | } 82 | 83 | #[inline] 84 | fn set(&mut self, col: usize, row: usize, value: T) { 85 | self.bits[row * Self::SIDE + col] = value; 86 | } 87 | 88 | #[inline] 89 | fn get(&self, col: usize, row: usize) -> T { 90 | self.bits[row * Self::SIDE + col].clone() 91 | } 92 | } 93 | 94 | 95 | fn main() 96 | { 97 | let stdin = io::stdin(); 98 | for line in stdin.lock().lines().filter_map(Result::ok) { 99 | let mut used = Bitmap::from_key(line.trim()); 100 | 101 | // How many bits are set? 102 | println!("Used bits: {}", used.bits.iter().filter(|&x| x).count()); 103 | 104 | // Label all the connected areas. 105 | let mut labels = BitmapLabels::new(); 106 | let mut queue = Vec::new(); 107 | let mut cur_label = 0; 108 | 109 | for row in 0 .. Bitmap::SIDE { 110 | for col in 0 .. Bitmap::SIDE { 111 | // Flood-fill unlabeled items with the current label. The 112 | // queue keeps a list of flooded items whose neighbours are 113 | // pending to be checked. 114 | if used.get(row, col) && labels.get(row, col) == 0 { 115 | cur_label += 1; 116 | labels.set(row, col, cur_label); 117 | queue.push((row, col)); 118 | while !queue.is_empty() { 119 | let (r, c) = queue.pop().unwrap(); 120 | // Up. 121 | if r > 0 && used.get(r - 1, c) && labels.get(r - 1, c) == 0 { 122 | labels.set(r - 1, c, cur_label); 123 | queue.push((r - 1, c)); 124 | } 125 | // Left. 126 | if c > 0 && used.get(r, c - 1) && labels.get(r, c - 1) == 0 { 127 | labels.set(r, c - 1, cur_label); 128 | queue.push((r, c - 1)); 129 | } 130 | // Right. 131 | if c + 1 < Bitmap::SIDE && used.get(r, c + 1) && labels.get(r, c + 1) == 0 { 132 | labels.set(r, c + 1, cur_label); 133 | queue.push((r, c + 1)); 134 | } 135 | // Bottom. 136 | if r + 1 < Bitmap::SIDE && used.get(r + 1, c) && labels.get(r + 1, c) == 0 { 137 | labels.set(r + 1, c, cur_label); 138 | queue.push((r + 1, c)); 139 | } 140 | } 141 | } 142 | } 143 | } 144 | 145 | println!("Total labels: {}", cur_label); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/bin/day03b.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day03b.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | extern crate aoc2017; 8 | 9 | use aoc2017::day03::grid_size_for_cell; 10 | use std::fmt; 11 | use std::io; 12 | use std::io::prelude::*; 13 | use std::ops::Add; 14 | use std::str::FromStr; 15 | 16 | 17 | struct SquareGrid 18 | { 19 | data: Vec, 20 | size: usize, 21 | } 22 | 23 | impl SquareGrid { 24 | fn new(size: usize, value: T) -> Self { 25 | SquareGrid { 26 | data: vec![value; size * size], 27 | size: size, 28 | } 29 | } 30 | 31 | #[inline] fn size(&self) -> usize { self.size } 32 | #[inline] fn center(&self) -> usize { self.size / 2 } 33 | 34 | fn get(&self, x: usize, y: usize) -> T { 35 | if x >= self.size { 36 | panic!("Index out of bounds: x={} >= {}", x, self.size); 37 | } 38 | if y >= self.size { 39 | panic!("Index out of bounds: y={} >= {}", y, self.size); 40 | } 41 | unsafe { self.data.get_unchecked(self.size * y + x) }.clone() 42 | } 43 | 44 | fn get_mut(&mut self, x: usize, y: usize) -> &mut T { 45 | if x >= self.size { 46 | panic!("Index out of bounds: x={} >= {}", x, self.size); 47 | } 48 | if y >= self.size { 49 | panic!("Index out of bounds: y={} >= {}", y, self.size); 50 | } 51 | unsafe { self.data.get_unchecked_mut(self.size * y + x) } 52 | } 53 | 54 | #[inline] 55 | fn set(&mut self, x: usize, y: usize, value: T) { 56 | *self.get_mut(x, y) = value; 57 | } 58 | 59 | #[inline] 60 | fn is_valid_index(&self, x: usize, y: usize) -> bool { 61 | x < self.size && y < self.size 62 | } 63 | } 64 | 65 | 66 | impl> SquareGrid { 67 | const COVER_STEPS: [(isize, isize); 8] = [ 68 | (-1, -1), (0, -1), (1, -1), 69 | (-1, 0), (1, 0), 70 | (-1, 1), (0, 1), (1, 1), 71 | ]; 72 | 73 | fn covered_sum(&self, x: usize, y: usize) -> T { 74 | let mut sum = self.get(x, y); // Center point. 75 | for &(dx, dy) in Self::COVER_STEPS.iter() { 76 | let (cx, cy) = ((x as isize + dx) as usize, 77 | (y as isize + dy) as usize); 78 | if self.is_valid_index(cx, cy) { 79 | sum = sum + self.get(cx, cy); 80 | } 81 | } 82 | sum 83 | } 84 | 85 | fn update_sum(&mut self, x: usize, y: usize) -> T { 86 | let sum = self.covered_sum(x, y); 87 | self.set(x, y, sum.clone()); 88 | sum 89 | } 90 | } 91 | 92 | 93 | impl fmt::Debug for SquareGrid { 94 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 95 | for row in 0..self.size() { 96 | for col in 0..self.size() { 97 | write!(f, "{:4}", self.get(col, self.size - row - 1))?; 98 | } 99 | write!(f, "\n")?; 100 | } 101 | Ok(()) 102 | } 103 | } 104 | 105 | 106 | #[derive(Debug, PartialEq, Copy, Clone)] 107 | enum Direction { 108 | EAST, 109 | NORTH, 110 | WEST, 111 | SOUTH, 112 | } 113 | 114 | impl Direction { 115 | fn left(&self) -> Self { 116 | match *self { 117 | Direction::EAST => Direction::NORTH, 118 | Direction::NORTH => Direction::WEST, 119 | Direction::WEST => Direction::SOUTH, 120 | Direction::SOUTH => Direction::EAST, 121 | } 122 | } 123 | 124 | fn ahead(&self, x: usize, y: usize) -> (usize, usize) { 125 | match *self { 126 | Direction::EAST => (x + 1, y), 127 | Direction::NORTH => (x, y + 1), 128 | Direction::WEST => (x - 1, y), 129 | Direction::SOUTH => (x, y - 1), 130 | } 131 | } 132 | } 133 | 134 | 135 | fn calculate(value: u32) -> u32 136 | { 137 | let size = grid_size_for_cell(value); 138 | let mut grid = SquareGrid::new(size as usize, 0); 139 | let mut x = grid.center(); 140 | let mut y = grid.center(); 141 | 142 | // Initial value. 143 | grid.set(x, y, 1); 144 | assert_eq!(1, grid.covered_sum(x, y)); 145 | 146 | // Move to the first position which must get filled. 147 | let mut d = Direction::EAST; 148 | let (sx, sy) = d.ahead(x, y); 149 | x = sx; 150 | y = sy; 151 | grid.update_sum(x, y); 152 | 153 | while grid.get(x, y) <= value { 154 | let left = d.left(); 155 | let (lx, ly) = left.ahead(x, y); 156 | if grid.get(lx, ly) == 0 { 157 | // Not filled: Can turn left. 158 | d = left; 159 | x = lx; 160 | y = ly; 161 | } else { 162 | // Already filled, just go ahead. 163 | let (ax, ay) = d.ahead(x, y); 164 | x = ax; 165 | y = ay; 166 | }; 167 | grid.update_sum(x, y); 168 | } 169 | 170 | grid.get(x, y) 171 | } 172 | 173 | 174 | fn main() 175 | { 176 | let stdin = io::stdin(); 177 | for row in stdin.lock().lines().filter_map(io::Result::ok) { 178 | for value in row.split_whitespace().map(|s| u32::from_str(s).unwrap()) { 179 | println!("{}", calculate(value)); 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // 2 | // lib.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::io::{ self, BufRead, Read }; 8 | use std::str::FromStr; 9 | 10 | 11 | #[inline] 12 | fn is_ascii_digit(byte: &u8) -> bool 13 | { 14 | *byte >= 0x30 && *byte <= 0x39 15 | } 16 | 17 | 18 | fn ascii_digit(byte: u8) -> u32 19 | { 20 | if is_ascii_digit(&byte) { 21 | byte as u32 - 0x30 22 | } else { 23 | panic!("Byte 0x{:02X} is not a number", byte) 24 | } 25 | } 26 | 27 | 28 | pub fn iter_digits(iter: io::Bytes) -> impl Iterator 29 | { 30 | iter.map(|item| item.unwrap()) 31 | .take_while(is_ascii_digit) 32 | .map(ascii_digit) 33 | } 34 | 35 | 36 | pub fn rows_of_digits(iter: BR) -> impl Iterator> 37 | { 38 | iter.lines() 39 | .filter_map(io::Result::ok) 40 | .map(|line| { 41 | line.split_whitespace() 42 | .map(|s| i32::from_str(s).unwrap()) 43 | .collect() 44 | }) 45 | } 46 | 47 | 48 | #[derive(Debug)] 49 | pub struct VecPermutations { 50 | v: Vec, 51 | i: usize, 52 | j: usize, 53 | } 54 | 55 | 56 | impl Iterator for VecPermutations 57 | where T: Clone 58 | { 59 | type Item = (T, T); 60 | 61 | fn size_hint(&self) -> (usize, Option) { 62 | let nitems = self.v.len() * self.v.len(); 63 | (nitems, Some(nitems)) 64 | } 65 | 66 | fn next(&mut self) -> Option { 67 | if self.i < self.v.len() && self.j < self.v.len() { 68 | let item = (self.v[self.i].clone(), self.v[self.j].clone()); 69 | self.i += 1; 70 | if self.i >= self.v.len() { 71 | self.i = 0; 72 | self.j += 1; 73 | } 74 | Some(item) 75 | } else { 76 | None 77 | } 78 | } 79 | } 80 | 81 | 82 | pub trait Permutations 83 | { 84 | type IteratorType; 85 | 86 | fn permutations(self) -> Self::IteratorType; 87 | } 88 | 89 | 90 | impl Permutations for Vec 91 | { 92 | type IteratorType = VecPermutations; 93 | 94 | fn permutations(self) -> Self::IteratorType 95 | { 96 | VecPermutations { v: self, i: 0, j: 0 } 97 | } 98 | } 99 | 100 | 101 | pub mod day03 { 102 | pub fn grid_size_for_cell(cellindex: u32) -> u32 103 | { 104 | let mut size = 1; 105 | while cellindex > size * size { 106 | size += 2; 107 | } 108 | return size; 109 | } 110 | } 111 | 112 | 113 | pub mod day10 114 | { 115 | use std::fmt; 116 | 117 | pub struct KnotHash 118 | { 119 | list: [u8; 256], 120 | pos: usize, 121 | skip: usize, 122 | } 123 | 124 | impl KnotHash 125 | { 126 | const ROUNDS: usize = 64; 127 | const XORITEMS: usize = 16; 128 | const XORGROUPS: usize = 256 / Self::XORITEMS; 129 | 130 | pub fn new() -> Self { 131 | let mut kh = KnotHash { list: [0u8; 256], pos: 0, skip: 0 }; 132 | for i in 0 .. kh.list.len() { 133 | kh.list[i] = i as u8; 134 | } 135 | kh 136 | } 137 | 138 | fn apply(&mut self, n: u8) { 139 | // 1. Reverse the order of elements pos..n 140 | let len = self.list.len(); 141 | let mut i = self.pos; 142 | let mut j = self.pos + (n as usize) - 1; 143 | while i < j { 144 | self.list.swap(i % len, j % len); 145 | i += 1; 146 | j -= 1; 147 | } 148 | 149 | // 2. Increase position by n+skip 150 | self.pos = (self.pos + (n as usize) + self.skip) % self.list.len(); 151 | 152 | // 3. Increase skip by one. 153 | self.skip += 1; 154 | } 155 | 156 | #[inline] 157 | pub fn rounds(&mut self, input: &[u8]) { 158 | for _ in 0..Self::ROUNDS { 159 | for &b in input { 160 | self.apply(b); 161 | } 162 | // Apply the standard tail lengths. 163 | for &b in &[17, 31, 73, 47, 23] { 164 | self.apply(b); 165 | } 166 | } 167 | } 168 | } 169 | 170 | impl fmt::LowerHex for KnotHash 171 | { 172 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 173 | for group in 0 .. Self::XORGROUPS { 174 | let startpos = group * Self::XORITEMS; 175 | let mut xor = 0; 176 | for x in &self.list[startpos .. startpos + Self::XORITEMS] { 177 | xor ^= x; 178 | } 179 | write!(f, "{:02x}", xor)?; 180 | } 181 | Ok(()) 182 | } 183 | } 184 | } 185 | 186 | 187 | pub mod day14 188 | { 189 | use super::day10::KnotHash; 190 | 191 | pub fn make_row_hash(key: &str, row: u16) -> String { 192 | let input = format!("{}-{}", key, row); 193 | let mut kh = KnotHash::new(); 194 | kh.rounds(input.as_bytes()); 195 | format!("{:x}", kh) 196 | } 197 | 198 | pub fn hex_char_to_u8(c: char) -> u8 { 199 | match c { 200 | '0' => 0x0, 201 | '1' => 0x1, 202 | '2' => 0x2, 203 | '3' => 0x3, 204 | '4' => 0x4, 205 | '5' => 0x5, 206 | '6' => 0x6, 207 | '7' => 0x7, 208 | '8' => 0x8, 209 | '9' => 0x9, 210 | 'a' | 'A' => 0xA, 211 | 'b' | 'B' => 0xB, 212 | 'c' | 'C' => 0xC, 213 | 'd' | 'D' => 0xD, 214 | 'e' | 'E' => 0xE, 215 | 'f' | 'F' => 0xF, 216 | _ => panic!("Non-hex character: '{}'", c), 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/bin/day08.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day08.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | #[macro_use] extern crate failure; 8 | 9 | use std::collections::HashMap; 10 | use std::fmt; 11 | use std::io; 12 | use std::io::prelude::*; 13 | use std::str::FromStr; 14 | 15 | 16 | #[derive(Debug)] 17 | enum Cond 18 | { 19 | EQ(String, i32), // == 20 | NE(String, i32), // != 21 | GT(String, i32), // > 22 | GE(String, i32), // >= 23 | LT(String, i32), // < 24 | LE(String, i32), // <= 25 | } 26 | 27 | impl FromStr for Cond 28 | { 29 | type Err = ::failure::Error; 30 | 31 | fn from_str(s: &str) -> Result 32 | { 33 | if let Some(pos) = s.find(" == ") { 34 | let (regname, value) = s.split_at(pos); 35 | Ok(Cond::EQ(regname.trim().to_string(), value[4..].trim().parse()?)) 36 | } else if let Some(pos) = s.find(" != ") { 37 | let (regname, value) = s.split_at(pos); 38 | Ok(Cond::NE(regname.trim().to_string(), value[4..].trim().parse()?)) 39 | } else if let Some(pos) = s.find(" >= ") { 40 | let (regname, value) = s.split_at(pos); 41 | Ok(Cond::GE(regname.trim().to_string(), value[4..].trim().parse()?)) 42 | } else if let Some(pos) = s.find(" <= ") { 43 | let (regname, value) = s.split_at(pos); 44 | Ok(Cond::LE(regname.trim().to_string(), value[4..].trim().parse()?)) 45 | } else if let Some(pos) = s.find(" > ") { 46 | let (regname, value) = s.split_at(pos); 47 | Ok(Cond::GT(regname.trim().to_string(), value[3..].trim().parse()?)) 48 | } else if let Some(pos) = s.find(" < ") { 49 | let (regname, value) = s.split_at(pos); 50 | Ok(Cond::LT(regname.trim().to_string(), value[3..].trim().parse()?)) 51 | } else { 52 | bail!("Condition '{}' has an invalid relational operator", s) 53 | } 54 | } 55 | } 56 | 57 | 58 | #[derive(Debug)] 59 | enum Op 60 | { 61 | Inc(String, i32), // inc 62 | Dec(String, i32), // dec 63 | } 64 | 65 | impl FromStr for Op 66 | { 67 | type Err = ::failure::Error; 68 | 69 | fn from_str(s: &str) -> Result 70 | { 71 | if let Some(pos) = s.find(" inc ") { 72 | let (regname, value) = s.split_at(pos); 73 | Ok(Op::Inc(regname.trim().to_string(), value[5..].trim().parse()?)) 74 | } else if let Some(pos) = s.find(" dec ") { 75 | let (regname, value) = s.split_at(pos); 76 | Ok(Op::Dec(regname.trim().to_string(), value[5..].trim().parse()?)) 77 | } else { 78 | bail!("Instruction '{}' contains invalid operation", s) 79 | } 80 | } 81 | } 82 | 83 | 84 | #[derive(Debug)] 85 | struct Instr 86 | { 87 | op: Op, 88 | cond: Cond, 89 | } 90 | 91 | impl FromStr for Instr 92 | { 93 | type Err = ::failure::Error; 94 | 95 | fn from_str(s: &str) -> Result 96 | { 97 | let if_pos = if let Some(pos) = s.find(" if ") { pos } else { 98 | bail!("Input '{}' does not contain 'if'", s); 99 | }; 100 | let (op_str, cond_str) = s.split_at(if_pos); 101 | Ok(Instr { 102 | op: op_str.trim().parse()?, 103 | cond: cond_str[4..].trim().parse()?, 104 | }) 105 | } 106 | } 107 | 108 | 109 | struct Machine 110 | { 111 | regs: HashMap, 112 | max_seen: i32, 113 | } 114 | 115 | 116 | impl Machine 117 | { 118 | fn new() -> Self { 119 | Machine { 120 | regs: HashMap::new(), 121 | max_seen: i32::min_value(), 122 | } 123 | } 124 | 125 | #[inline] 126 | fn get(&self, regname: &str) -> i32 { 127 | *self.regs.get(regname).unwrap_or(&0) 128 | } 129 | 130 | fn check_condition(&self, cond: &Cond) -> bool { 131 | match *cond { 132 | Cond::EQ(ref r, v) => self.get(r) == v, 133 | Cond::NE(ref r, v) => self.get(r) != v, 134 | Cond::GT(ref r, v) => self.get(r) > v, 135 | Cond::GE(ref r, v) => self.get(r) >= v, 136 | Cond::LT(ref r, v) => self.get(r) < v, 137 | Cond::LE(ref r, v) => self.get(r) <= v, 138 | } 139 | } 140 | 141 | fn execute(&mut self, ins: &Instr) { 142 | if self.check_condition(&ins.cond) { 143 | match ins.op { 144 | Op::Inc(ref r, v) => self.inc(r, v), 145 | Op::Dec(ref r, v) => self.dec(r, v), 146 | } 147 | } 148 | } 149 | 150 | #[inline] 151 | fn inc(&mut self, regname: &str, value: i32) { 152 | let reg = self.regs.entry(regname.to_string()).or_insert(0); 153 | *reg += value; 154 | if *reg > self.max_seen { 155 | self.max_seen = *reg; 156 | } 157 | } 158 | 159 | #[inline] 160 | fn dec(&mut self, regname: &str, value: i32) { 161 | let reg = self.regs.entry(regname.to_string()).or_insert(0); 162 | *reg -= value; 163 | if *reg > self.max_seen { 164 | self.max_seen = *reg; 165 | } 166 | } 167 | } 168 | 169 | impl fmt::Display for Machine 170 | { 171 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result 172 | { 173 | for (regname, value) in &self.regs { 174 | write!(f, "{}: {}\n", regname, value)?; 175 | } 176 | Ok(()) 177 | } 178 | } 179 | 180 | 181 | fn main() 182 | { 183 | let mut m = Machine::new(); 184 | 185 | let stdin = io::stdin(); 186 | for line in stdin.lock().lines().filter_map(io::Result::ok) { 187 | let instr = line.parse().unwrap(); 188 | m.execute(&instr); 189 | } 190 | 191 | let mut max_value = i32::min_value(); 192 | for (_regname, &value) in &m.regs { 193 | if value > max_value { 194 | max_value = value; 195 | } 196 | } 197 | println!("max reg value: {}", max_value); 198 | println!("max seen value: {}", m.max_seen); 199 | } 200 | -------------------------------------------------------------------------------- /src/bin/day13.rs: -------------------------------------------------------------------------------- 1 | // 2 | // day13.rs 3 | // Copyright (C) 2017 Adrian Perez 4 | // Distributed under terms of the MIT license. 5 | // 6 | 7 | use std::fmt; 8 | use std::io; 9 | use std::io::prelude::*; 10 | 11 | 12 | #[derive(Debug, Clone)] 13 | struct Layer 14 | { 15 | len: u32, 16 | pos: u32, 17 | fwd: bool, // Going down (forward) or up (backward). 18 | } 19 | 20 | impl Layer 21 | { 22 | fn new(range: u32) -> Self { 23 | Self { len: range, pos: 0, fwd: true } 24 | } 25 | 26 | #[inline] 27 | fn reset(&mut self) { 28 | self.pos = 0; 29 | self.fwd = true; 30 | } 31 | 32 | #[inline] 33 | fn range(&self) -> u32 { 34 | self.len 35 | } 36 | 37 | #[inline] 38 | fn tick(&mut self) { 39 | if self.len > 1 { 40 | if self.fwd { 41 | if self.pos == self.len - 1 { 42 | self.fwd = false; 43 | self.pos -= 1; 44 | } else { 45 | self.pos += 1; 46 | } 47 | } else { 48 | if self.pos == 0 { 49 | self.fwd = true; 50 | self.pos += 1; 51 | } else { 52 | self.pos -= 1; 53 | } 54 | } 55 | } 56 | } 57 | 58 | fn scanner_at_top(&self) -> bool { 59 | self.len > 0 && self.pos == 0 60 | } 61 | } 62 | 63 | 64 | struct Firewall 65 | { 66 | layers: Vec, 67 | pos: usize, 68 | initial: bool, 69 | collision: Option, 70 | } 71 | 72 | impl Clone for Firewall { 73 | fn clone(&self) -> Self { 74 | Self { 75 | layers: self.layers.iter().map(Layer::clone).collect(), 76 | pos: self.pos, 77 | initial: self.initial, 78 | collision: self.collision, 79 | } 80 | } 81 | } 82 | 83 | impl fmt::Debug for Firewall 84 | { 85 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 86 | let mut max_range = 0; 87 | for i in 0 .. self.layers.len() { 88 | write!(f, " {} ", i)?; 89 | if self.layers[i].range() > max_range { 90 | max_range = self.layers[i].range(); 91 | } 92 | } 93 | write!(f, "\n")?; 94 | for row in 0 .. max_range { 95 | for i in 0 .. self.layers.len() { 96 | if row == 0 && self.pos == i { 97 | let item = if self.layers[i].range() == 0 { "." } 98 | else if self.layers[i].pos == row { "S" } 99 | else { " " }; 100 | if self.initial { 101 | write!(f, "[{}] ", item)?; 102 | } else { 103 | write!(f, "({}) ", item)?; 104 | } 105 | } else if self.layers[i].range() <= row { 106 | write!(f, "... ")?; 107 | } else { 108 | write!(f, "[{}] ", if self.layers[i].pos == row { "S" } else { " " })?; 109 | } 110 | } 111 | write!(f, "\n")?; 112 | } 113 | Ok(()) 114 | } 115 | } 116 | 117 | impl Firewall 118 | { 119 | fn new() -> Self { 120 | Self { 121 | layers: Vec::new(), 122 | pos: 0, 123 | initial: true, 124 | collision: None, 125 | } 126 | } 127 | 128 | fn set(&mut self, depth: u32, layer: Layer) { 129 | let depth = depth as usize; 130 | for _ in 0 .. (depth - self.layers.len() + 1) { 131 | self.layers.push(Layer::new(0)); // Fill with empty layers. 132 | } 133 | assert!(depth < self.layers.len()); 134 | self.layers[depth] = layer; 135 | } 136 | 137 | #[inline] 138 | fn reset(&mut self) { 139 | self.layers.iter_mut().for_each(Layer::reset); 140 | self.reset_packet(); 141 | } 142 | 143 | #[inline] 144 | fn reset_packet(&mut self) { 145 | self.collision = None; 146 | self.initial = true; 147 | self.pos = 0; 148 | } 149 | 150 | #[inline] 151 | fn finished(&self) -> bool { 152 | self.pos >= self.layers.len() 153 | } 154 | 155 | #[inline] 156 | fn collided(&self) -> bool { 157 | !self.finished() && self.layers[self.pos].scanner_at_top() 158 | } 159 | 160 | #[inline] 161 | fn collision_severity(&self) -> Option { 162 | if self.collided() { 163 | Some(self.pos as u32 * self.layers[self.pos].range()) 164 | } else { 165 | None 166 | } 167 | } 168 | 169 | #[inline] 170 | fn tick(&mut self) { 171 | if !self.finished() { 172 | if self.initial { 173 | self.initial = false; 174 | } else { 175 | self.pos += 1; 176 | } 177 | self.collision = self.collision_severity(); 178 | self.layers.iter_mut().for_each(Layer::tick); 179 | } 180 | } 181 | 182 | fn trip_severity(&mut self) -> Option { 183 | let mut total_severity = 0; 184 | let mut caught = false; 185 | while !self.finished() { 186 | self.tick(); 187 | if let Some(severity) = self.collision { 188 | total_severity += severity; 189 | caught = true; 190 | } 191 | } 192 | if caught { 193 | Some(total_severity) 194 | } else { 195 | None 196 | } 197 | } 198 | } 199 | 200 | 201 | fn main() 202 | { 203 | let mut fw = Firewall::new(); 204 | 205 | let stdin = io::stdin(); 206 | for line in stdin.lock().lines().filter_map(Result::ok) { 207 | if let Some(pos) = line.find(':') { 208 | let (left, right) = line.split_at(pos); 209 | let depth = left.trim().parse().unwrap(); 210 | let range = right[1..].trim().parse().unwrap(); 211 | fw.set(depth, Layer::new(range)); 212 | } 213 | } 214 | 215 | fw.reset(); 216 | println!("Trip severity: {}", fw.trip_severity().unwrap_or(0)); 217 | 218 | fw.reset(); 219 | for delay in 0 .. { 220 | if delay % 100 == 0 { 221 | print!("\rDelay: {}", delay); 222 | io::stdout().flush().unwrap(); 223 | } 224 | 225 | // Check what the severity of the trip would be now. We use a clone 226 | // so we can continue using "fw" to calculate states after the delay. 227 | if fw.clone().trip_severity() == None { 228 | println!("\rDelay to not be caught: {} picosends", delay); 229 | break; 230 | } 231 | 232 | // Add one tick of delay, reset packet to initial position. 233 | fw.tick(); 234 | fw.reset_packet(); 235 | } 236 | } 237 | --------------------------------------------------------------------------------