day3 part 1

This commit is contained in:
JasterV 2021-12-03 14:01:52 +01:00
parent 1f3a5ac38e
commit 74a20bec4f
6 changed files with 1086 additions and 0 deletions

1
day3/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target/

7
day3/Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day3"
version = "0.1.0"

8
day3/Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "day3"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1000
day3/input.txt Normal file

File diff suppressed because it is too large Load diff

58
day3/src/main.rs Normal file
View file

@ -0,0 +1,58 @@
use std::{
fs::File,
io::{BufRead, BufReader, Lines, Result},
path::Path,
};
static INPUT_PATH: &str = "input.txt";
fn main() -> Result<()> {
let diagnostic_report = read_diagnostic_report(INPUT_PATH)?;
let [gamma_rate, epsilon_rate] = extract_report_rates(&diagnostic_report);
println!("First puzzle: {}", gamma_rate * epsilon_rate);
Ok(())
}
fn extract_report_rates(report: &[String]) -> [i32; 2] {
let sums: Vec<i32> = report.iter().fold(vec![], |sums, curr| {
curr.chars()
.enumerate()
.map(|(index, char)| {
let value = if char == '0' { -1 } else { 1 };
sums.get(index).map_or(value, |sum| sum + value)
})
.collect()
});
let gamma_rate: String = sums
.iter()
.map(|&sum| if sum > 0 { "1" } else { "0" })
.collect::<Vec<&str>>()
.join("");
let epsilon_rate: String = sums
.iter()
.map(|&sum| if sum > 0 { "0" } else { "1" })
.collect::<Vec<&str>>()
.join("");
[
binary_str_to_int(&gamma_rate),
binary_str_to_int(&epsilon_rate),
]
}
fn read_diagnostic_report(file_path: &str) -> Result<Vec<String>> {
read_lines(file_path).map(|lines| lines.filter_map(|line| line.ok()).collect())
}
fn binary_str_to_int(binary_str: &str) -> i32 {
i32::from_str_radix(binary_str, 2).unwrap()
}
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> Result<Lines<BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(BufReader::new(file).lines())
}

12
day3/test.txt Normal file
View file

@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010