Skip to content

Instantly share code, notes, and snippets.

Created December 16, 2017 19:58
Show Gist options
  • Select an option

  • Save anonymous/d45479bdccefaa2c76c917e0359c2bcb to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/d45479bdccefaa2c76c917e0359c2bcb to your computer and use it in GitHub Desktop.
Rust code shared from the playground
const INPUT: isize = 289326;
#[derive(Clone, Copy, Debug)]
struct Vec2 {
x: isize,
y: isize,
}
fn main() {
let mut pos = Vec2 { x: 0, y: 0 };
let mut spiral_pos = 1;
let directions = [
Vec2 { x: 1, y: 0 },
Vec2 { x: 0, y: 1 },
Vec2 { x: -1, y: 0 },
Vec2 { x: 0, y: -1 },
].iter().cloned().cycle();
// 1, 1, 2, 2, 3, 3, 4, 4, ...
let step_sizes = (2..).map(|x| x / 2);
for (dir, step_size) in directions.zip(step_sizes) {
let dist_remaining = INPUT - spiral_pos;
if dist_remaining < step_size {
pos.x += dir.x * dist_remaining;
pos.y += dir.y * dist_remaining;
let origin_dist = pos.x.abs() + pos.y.abs();
println!("{}", origin_dist);
break;
}
pos.x += dir.x * step_size;
pos.y += dir.y * step_size;
spiral_pos += step_size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment