#![feature(iter_advance_by)]
use std::collections::HashMap;
use std::env;
struct ElfGame {
history: HashMap<usize, usize>,
last: usize,
len: usize,
}
impl ElfGame {
fn new() -> Self {
ElfGame {
history: HashMap::new(),
last: 0,
len: 0,
}
}
fn push(&mut self, num: usize) {
self.history.insert(self.last, self.len);
self.len += 1;
self.last = num;
}
}
impl Iterator for ElfGame {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
let nxt = self
.history
.get(&self.last)
.map_or_else(|| 0, |p| self.len - p);
self.push(nxt);
Some(nxt)
}
}
fn main() {
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
let mut eg = ElfGame::new();
let args: Vec<_> = env::args().collect();
let file = BufReader::new(File::open(<String as AsRef<Path>>::as_ref(&args[2])).unwrap());
for strnum in file.split(b',') {
match <usize as FromStr>::from_str(
String::from_utf8(strnum.unwrap_or(vec![]))
.unwrap_or("".to_string())
.trim(),
) {
Ok(num) => {
eg.push(num);
}
Err(_) => (),
}
}
match eg.advance_by(<usize as FromStr>::from_str(args[1].as_ref()).unwrap() - eg.len - 1) {
Ok(_) => println!("{}", eg.next().unwrap()),
Err(err) => eprintln!("{:?}", err),
}
}