From 3b877bf4cc667eb8bcc787d145203600a4dba2d2 Mon Sep 17 00:00:00 2001 From: Prefetch Date: Sat, 25 Feb 2023 11:41:27 +0100 Subject: Initial commit --- d16/src/main.rs | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 d16/src/main.rs (limited to 'd16/src') diff --git a/d16/src/main.rs b/d16/src/main.rs new file mode 100644 index 0000000..06ba9e1 --- /dev/null +++ b/d16/src/main.rs @@ -0,0 +1,81 @@ +fn generate_data(input: &str, length: usize) -> String { + let mut a = String::from(input); + + while a.len() < length { + let mut b = String::new(); + + // Fill `b' with reversed and bit-flipped `a' + for c in a.chars().rev() { + b.push(if c == '0' { '1' } else { '0' }); + } + + a = format!("{}0{}", a, b); + } + + a.truncate(length); + a +} + +fn get_checksum(data: &str) -> String { + let mut chars: Vec = data.chars().collect(); + + while chars.len() % 2 == 0 { + let mut next = Vec::new(); + + // For each pair of characters (length is even due to `while') + for i in 0..chars.len() / 2 { + // If both chars in this pair are equal + if chars[2 * i] == chars[2 * i + 1] { + next.push('1'); + } else { + next.push('0'); + } + } + + chars = next; + } + + chars.into_iter().collect() +} + +fn solve_puzzle(input: &str, length: usize) -> String { + let data = generate_data(input, length); + get_checksum(&data) +} + +fn main() { + // My personal puzzle input + let input = "11011110011011101"; + + // Part 1 gives 00000100100001100 for me + println!("Part 1 solution: {}", solve_puzzle(input, 272)); + + // Part 1 gives 00011010100010010 for me + println!("Part 2 solution: {}", solve_puzzle(input, 35651584)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_data() { + assert_eq!(generate_data("1", 3), "100"); + assert_eq!(generate_data("0", 3), "001"); + assert_eq!(generate_data("11111", 11), "11111000000"); + assert_eq!( + generate_data("111100001010", 25), + "1111000010100101011110000" + ); + } + + #[test] + fn test_checksum() { + assert_eq!(get_checksum("110010110100"), "100"); + } + + #[test] + fn part1_example1() { + assert_eq!(solve_puzzle("10000", 20), "01100"); + } +} -- cgit v1.2.3