rust day 7 part 1
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
blackbeard420 2021-12-08 18:12:40 -05:00
parent eb6ae5ba85
commit 59c8c6dc98
Signed by: blackbeard420
GPG Key ID: 88C719E09CDDA4A5
3 changed files with 79 additions and 0 deletions

7
rust/day7/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 = "day7"
version = "0.1.0"

8
rust/day7/Cargo.toml Normal file
View File

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

64
rust/day7/src/main.rs Normal file
View File

@ -0,0 +1,64 @@
use std::fs;
use std::io::BufRead;
static PATH: &'static str = "../../inputs/input-day7";
fn remove_whitespace(s: &str) -> String {
return s.split_whitespace().collect();
}
fn load_file() -> Result<Vec<i64>, std::io::Error> {
let file = fs::File::open(PATH)?;
let reader = std::io::BufReader::new(file);
let res: Vec<i64> = reader.split(b',').map(|p| {
let p = p.unwrap();
let v = String::from_utf8_lossy(&p);
return remove_whitespace(&v).parse::<i64>().unwrap();
}).collect();
return Ok(res);
}
fn calc_fuel_for_pos(v: &Vec<i64>, pos: i64) -> i64 {
let mut total = 0;
for x in v {
if x > &pos {
total += x - pos;
} else if x < &pos {
total += pos - x;
}
}
return total;
}
fn get_max(v: &Vec<i64>) -> i64 {
let mut max = 0;
for i in v {
if i > &max {
max = *i;
}
}
return max
}
fn main() {
let pos = load_file().unwrap();
let max = get_max(&pos);
let mut lowest = 0;
let mut lastpos = 0;
for i in 0..max {
let fuel = calc_fuel_for_pos(&pos, i);
if i == 0 {
lowest = fuel;
}
if fuel < lowest {
lowest = fuel;
lastpos = i;
}
}
println!("lowest consumption is pos {} with {} fuel", lastpos, lowest);
}