|
| 1 | +use std::fmt; |
| 2 | + |
| 3 | +fn convert_into_snafu(input: usize) -> String { |
| 4 | + let base: usize = 5; |
| 5 | + let mut result = String::new(); |
| 6 | + let mut current_base_exp = 0; |
| 7 | + |
| 8 | + while base.pow(current_base_exp) <= input + base.pow(current_base_exp) / 2 { |
| 9 | + let digit = ((input + base.pow(current_base_exp) / 2) % base.pow(current_base_exp + 1)) |
| 10 | + / base.pow(current_base_exp); |
| 11 | + result = format!("{}{}", convert_digit_to_snafu_digit(digit), result); |
| 12 | + current_base_exp += 1; |
| 13 | + } |
| 14 | + result |
| 15 | +} |
| 16 | + |
| 17 | +fn convert_digit_to_snafu_digit(input: usize) -> char { |
| 18 | + match input { |
| 19 | + 0 => '0', |
| 20 | + 1 => '1', |
| 21 | + 2 => '2', |
| 22 | + 3 => '=', |
| 23 | + 4 => '-', |
| 24 | + _ => unimplemented!(), |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +fn convert_from_snafu(input: &str) -> usize { |
| 29 | + let base: usize = 5; |
| 30 | + let mut result: isize = 0; |
| 31 | + |
| 32 | + for (current_exp, c) in input.trim().chars().rev().enumerate() { |
| 33 | + result += convert_snafu_digit_to_digit(c) * base.pow(current_exp as u32) as isize; |
| 34 | + } |
| 35 | + |
| 36 | + result as usize |
| 37 | +} |
| 38 | + |
| 39 | +fn convert_snafu_digit_to_digit(input: char) -> isize { |
| 40 | + match input { |
| 41 | + '0' => 0, |
| 42 | + '1' => 1, |
| 43 | + '2' => 2, |
| 44 | + '=' => -2, |
| 45 | + '-' => -1, |
| 46 | + _ => unimplemented!(), |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +pub fn part_one(_input: &str) -> Option<String> { |
| 51 | + let sum: usize = _input.lines().map(convert_from_snafu).sum(); |
| 52 | + println!("Result decimal: {}", sum); |
| 53 | + Some(convert_into_snafu(sum)) |
| 54 | +} |
| 55 | + |
| 56 | +pub fn part_two(_input: &str) -> Option<u32> { |
| 57 | + // Nothing to do, Yay! |
| 58 | + Some(0) |
| 59 | +} |
| 60 | + |
| 61 | +fn main() { |
| 62 | + let input = &advent_of_code::read_file("inputs", 25); |
| 63 | + advent_of_code::solve!(1, part_one, input); |
| 64 | + advent_of_code::solve!(2, part_two, input); |
| 65 | +} |
| 66 | + |
| 67 | +#[cfg(test)] |
| 68 | +mod tests { |
| 69 | + use super::*; |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_part_one() { |
| 73 | + let input = advent_of_code::read_file("examples", 25); |
| 74 | + assert_eq!(part_one(&input), Some("2=-1=0".to_string())); |
| 75 | + } |
| 76 | + |
| 77 | + #[test] |
| 78 | + fn test_part_two() { |
| 79 | + let input = advent_of_code::read_file("examples", 25); |
| 80 | + assert_eq!(part_two(&input), Some(0)); |
| 81 | + } |
| 82 | +} |
0 commit comments