2017 Day 01 Complete in Rust

This commit is contained in:
2017-12-01 08:04:46 -06:00
parent 36e2202023
commit 09b1c9740d
3 changed files with 68 additions and 1 deletions

47
2017/day01/day01.rs Normal file
View File

@@ -0,0 +1,47 @@
mod helpers;
fn main() {
let input = helpers::read_std_in();
part1(input.clone());
part2(input.clone());
}
fn part1(input: String) {
let max = input.chars().count()-1;
let mut total = 0i32;
for (i, c) in input.chars().enumerate() {
let tst_idx = get_compare_idx(i, 1, max);
total += get_compare_result(c, input.chars().nth(tst_idx).unwrap());
}
println!("Part 1: {}", total);
}
fn part2(input: String) {
let max = input.chars().count()-1;
let mut total = 0i32;
for (i, c) in input.chars().enumerate() {
let tst_idx = get_compare_idx(i, (input.chars().count() / 2), max);
total += get_compare_result(c, input.chars().nth(tst_idx).unwrap());
}
println!("Part 2: {}", total);
}
fn get_compare_idx(curr: usize, add: usize, max: usize) -> usize {
let mut ret = curr + add;
if ret > max {
ret -= max+1;
}
return ret;
}
fn get_compare_result(c1: char, c2: char) -> i32 {
if c1 != c2 {
return 0;
}
match c1.to_digit(10) {
Some(v) => {
return v as i32;
},
None => 0,
}
}