Skip to content

Commit

Permalink
complete day 8 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Lawrence Niu committed Sep 25, 2022
1 parent a8a9090 commit d70b13f
Showing 1 changed file with 22 additions and 36 deletions.
58 changes: 22 additions & 36 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,27 @@
use std::cmp;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::str;

fn process_lines(mut reader: impl BufRead) -> anyhow::Result<usize> {
let mut line = String::new();
reader.read_to_string(&mut line)?;
let initial_state = line
.trim()
.split(',')
.map(|token| token.trim().parse::<u32>())
.collect::<Result<Vec<u32>, _>>()?;
let pos_offset = *initial_state.iter().min().unwrap();
let pos_max = ((*initial_state.iter().max().unwrap()) - pos_offset) as usize;
let mut histogram = vec![0u32; pos_max + 1];
initial_state.into_iter().for_each(|i| {
histogram[(i - pos_offset) as usize] += 1;
});

(0..=pos_max)
.map(|pos| {
histogram
.iter()
.copied()
.enumerate()
.map(|(i, count)| {
// gas(n) = summa [i = 0 -> n]{n - i}
// = summa [i = 0 -> n]{i}
// = n*(n+1)/2
let distance = cmp::max(i, pos) - cmp::min(i, pos);
let individual_use = distance * (distance + 1) / 2;
(count as usize) * individual_use
})
.sum()
})
.min()
.ok_or_else(|| unreachable!())
fn process_lines(reader: impl BufRead) -> anyhow::Result<usize> {
let mut digit_count: HashMap<usize, usize> = HashMap::with_capacity(4);
digit_count.insert(2, 0);
digit_count.insert(3, 0);
digit_count.insert(4, 0);
digit_count.insert(7, 0);
for line_res in reader.lines() {
let line = line_res?;
line.split('|')
.next_back()
.map(|s| s.trim())
.expect("malformed input")
.split_whitespace()
.map(|digit| digit.chars().count())
.for_each(|count| {
digit_count.entry(count).and_modify(|v| *v += 1);
});
}
Ok(digit_count.into_values().sum())
}
fn main() {
const INPUT_PATH: &str = "data/input.txt";
Expand All @@ -45,8 +31,8 @@ fn main() {
Err(err) => {
eprintln!("Could not process file {}:\n {}", INPUT_PATH, err);
}
Ok(gas_use) => {
println!("min gas use: {}", gas_use);
Ok(digit_count) => {
println!("# special digits: {}", digit_count);
}
},
Err(err) => {
Expand Down

0 comments on commit d70b13f

Please sign in to comment.