Created
December 5, 2017 16:04
-
-
Save archer884/d23845dedbf189cb2d5574f13b960c15 to your computer and use it in GitHub Desktop.
AOC/5 (Rust)b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(conservative_impl_trait)] | |
const INPUT: &str = include_str!("../input.txt"); | |
fn main() { | |
println!("{}", run_program(read_input(), |i| i + 1)); | |
println!("{}", run_program(read_input(), offset)); | |
} | |
fn offset(i: i32) -> i32 { | |
if i >= 3 { i - 1 } else { i + 1 } | |
} | |
fn run_program<I, F>(instructions: I, offset: F) -> usize | |
where | |
I: IntoIterator<Item = i32>, | |
F: Fn(i32) -> i32, | |
{ | |
let mut instructions: Vec<_> = instructions.into_iter().collect(); | |
let mut pointer = 0; | |
let mut counter = 0; | |
while pointer >= 0 && pointer < (instructions.len() as i32) { | |
let next_pointer = pointer + instructions[pointer as usize]; | |
instructions[pointer as usize] = offset(instructions[pointer as usize]); | |
pointer = next_pointer; | |
counter += 1; | |
} | |
counter | |
} | |
// Impl trait feature employed here. Ordinarily, the return of any item whose type | |
// signature includes a closure (a unique, unnameable type) would require boxing. | |
fn read_input() -> impl Iterator<Item = i32> { | |
INPUT.lines().filter_map(|n| n.parse().ok()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment