2017 Day 01 Complete in Rust

This commit is contained in:
Brian Buller 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,
}
}

20
2017/day01/helpers.rs Normal file
View File

@ -0,0 +1,20 @@
use std::io;
pub fn read_std_in() -> String {
let mut input = String::new();
let mut done = false;
while !done {
match io::stdin().read_line(&mut input) {
Ok(n) => {
if n == 0 {
done = true;
}
},
Err(error) => {
println!("error: {}", error);
done = true;
},
}
}
return String::from(input.trim());
}

View File

@ -18,7 +18,7 @@ func main() {
func part1(inp string) { func part1(inp string) {
sum := 0 sum := 0
for k := range inp { for k := range inp {
tstIdx := getCompareIndex(k, k+1, len(inp)) tstIdx := getCompareIndex(k, 1, len(inp))
sum += getCompareResult(inp[k], inp[tstIdx]) sum += getCompareResult(inp[k], inp[tstIdx])
} }
fmt.Println("Part 1:", sum) fmt.Println("Part 1:", sum)