day01 and day03 part 2 solutions

This commit is contained in:
Russell Champoux committed 2016-12-08 12:57:39 -05:00
1 parent f38991e9e8
commit 116bb99b1a
2 files changed
+52 -17

No files matched your search

+23 -16
View File
@@ -20,6 +20,10 @@ fn step(state: &(i32, i32), pos: &(i32, i32), dist: i32) -> (i32, i32) {
(pos.0 + state.0 * dist, pos.1 + state.1 * dist)
}
fn tiny_step(state: &(i32, i32), pos: &(usize, usize)) -> (usize, usize) {
((pos.0 as i32 + state.0) as usize, (pos.1 as i32 + state.1) as usize)
}
fn part_1(input: &String) {
let mut state = (1, 0);
let mut pos = (0, 0);
@@ -37,26 +41,29 @@ fn part_1(input: &String) {
}
fn part_2(input: &String) {
let mut state = (1, 0);
let mut positions: Vec<(i32, i32)> = vec![(0, 0)];
const OFFSET: usize = 500; //we'll make a grid 1000x1000
let mut grid = [[false; 2*OFFSET]; 2*OFFSET];
for item in input.trim().split(", ") {
let mut state = (1, 0);
let mut pos = (OFFSET, OFFSET);
grid[OFFSET][OFFSET] = true; //we are already at the axis
'outer: for item in input.trim().split(", ") {
let (dir, dist) = item.split_at(1);
let dir: String = dir.to_string();
let dist: i32 = dist.parse::<i32>().unwrap();
let mut dist: i32 = dist.parse::<i32>().unwrap();
state = turn(&state, &dir);
let pos = step(&state, positions.last().unwrap(), dist);
print!("{}: {}{} -> ({}, {}), ", positions.len(), dist, dir, pos.0, pos.1);
match positions.iter().position(|&p| p == pos) {
Some(v) => {
println!("Part 2: Stopped twice at ({}, {}) on element {}, {} away from the start", pos.0, pos.1, v, pos.0.abs() + pos.1.abs());
break;
},
None => {
//println!("Did not match {} locations", positions.len());
positions.push(pos);
},
while dist > 0 { //take a step
pos = tiny_step(&state, &pos);
match grid[pos.0][pos.1] {
true => {
let real_pos = ((pos.0 as i32 - OFFSET as i32), (pos.1 as i32 - OFFSET as i32));
println!("Part 2: Returned to ({}, {}), {} away from the start", real_pos.0, real_pos.1, real_pos.0.abs() + real_pos.1.abs());
break 'outer;
},
false => { grid[pos.0][pos.1] = true; dist = dist - 1 },
}
}
}
}
@@ -66,6 +73,6 @@ fn main() {
let mut input = String::new();
file.read_to_string(&mut input).expect("could not read file");
//part_1(&input);
part_1(&input);
part_2(&input);
}