From f15f6bcec0fe79b6884d74ee4288fd161ebfecb9 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Thu, 1 Dec 2016 16:12:34 -0800 Subject: [PATCH] [2016][rust][1.1] --- 2016/rust/src/main.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/2016/rust/src/main.rs b/2016/rust/src/main.rs index de5a945..07ea0d4 100644 --- a/2016/rust/src/main.rs +++ b/2016/rust/src/main.rs @@ -1,14 +1,16 @@ +use std::collections::HashSet; use std::io; use std::io::Read; use std::f32::consts::PI; fn solve(input: &str) -> String { let mut turtle = (-PI / 2.0, (0, 0)); + let mut visited: HashSet<(i32, i32)> = HashSet::new(); for step in input.split(", ") { let mut chars = step.chars(); let dir = chars.next().unwrap(); - let blocks = chars.collect::().parse::().unwrap(); + let blocks = chars.collect::().parse::().unwrap(); turtle.0 += match dir { 'R' => PI / 2.0, @@ -18,9 +20,17 @@ fn solve(input: &str) -> String { } }; - let movement = turtle.0.sin_cos(); - (turtle.1).0 += (blocks*movement.1) as i32; - (turtle.1).1 += (blocks*movement.0) as i32; + for _ in 0..blocks { + let movement = turtle.0.sin_cos(); + (turtle.1).0 += movement.1 as i32; + (turtle.1).1 += movement.0 as i32; + + if visited.contains(&turtle.1) { + return ((turtle.1).0.abs() + (turtle.1).1.abs()).to_string() + } else { + visited.insert(turtle.1); + } + } } ((turtle.1).0.abs() + (turtle.1).1.abs()).to_string() @@ -28,9 +38,10 @@ fn solve(input: &str) -> String { #[test] fn test_solve() { - assert_eq!(solve("R2, L3"), "5".to_string()); - assert_eq!(solve("R2, R2, R2"), "2".to_string()); - assert_eq!(solve("R5, L5, R5, R3"), "12".to_string()); + // assert_eq!(solve("R2, L3"), "5".to_string()); + // assert_eq!(solve("R2, R2, R2"), "2".to_string()); + // assert_eq!(solve("R5, L5, R5, R3"), "12".to_string()); + assert_eq!(solve("R8, R4, R4, R8"), "4".to_string()); } fn main() {