Skip to content

Instantly share code, notes, and snippets.

@fay59
Created May 24, 2018 06:41
Show Gist options
  • Save fay59/0b3c623fdfe7098612cb05b2a8726d92 to your computer and use it in GitHub Desktop.
Save fay59/0b3c623fdfe7098612cb05b2a8726d92 to your computer and use it in GitHub Desktop.
use std::cmp;
fn spiral_distance(num: u32) -> u32 {
let ring = (((num as f64).sqrt() - 1.) / 2.).ceil() as u32;
let root = (num as f64 - 1.).sqrt() as u32;
let offset_to_mid = root / 2;
let ring_min = root * root + 1 + offset_to_mid;
let ring_max = (root + 1) * (root + 1) - offset_to_mid;
return ring + cmp::min(
(num as i32 - ring_min as i32).abs(),
(num as i32 - ring_max as i32).abs()) as u32;
}
fn main() {
let mut digits_string = String::new();
std::io::stdin().read_line(&mut digits_string).expect("wtf?");
let num = digits_string.trim().parse::<u32>().unwrap();
println!("{}", spiral_distance(num));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment