diff --git a/2017/day01/day01.rs b/2017/day01/day01.rs new file mode 100644 index 0000000..98ab997 --- /dev/null +++ b/2017/day01/day01.rs @@ -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, + } +} diff --git a/2017/day01/helpers.rs b/2017/day01/helpers.rs new file mode 100644 index 0000000..bb4d915 --- /dev/null +++ b/2017/day01/helpers.rs @@ -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()); +} diff --git a/2017/day01/main.go b/2017/day01/main.go index 5b1df9b..6c7d829 100644 --- a/2017/day01/main.go +++ b/2017/day01/main.go @@ -18,7 +18,7 @@ func main() { func part1(inp string) { sum := 0 for k := range inp { - tstIdx := getCompareIndex(k, k+1, len(inp)) + tstIdx := getCompareIndex(k, 1, len(inp)) sum += getCompareResult(inp[k], inp[tstIdx]) } fmt.Println("Part 1:", sum)