Skip to content

Instantly share code, notes, and snippets.

@burnsauce
Last active December 19, 2020 07:03
Show Gist options
  • Select an option

  • Save burnsauce/7aaea3c9833f23a8370df1c8ab0b317e to your computer and use it in GitHub Desktop.

Select an option

Save burnsauce/7aaea3c9833f23a8370df1c8ab0b317e to your computer and use it in GitHub Desktop.
AOC2020 Day 13
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn main() -> io::Result<()> {
let f = File::open("input.txt")?;
let reader = BufReader::new(f);
let mut r = reader.lines();
let _num: usize = r.next().unwrap()?.parse().unwrap();
let mut sched = Vec::<Option<usize>>::new();
for s in r.next().unwrap()?.as_str().split(',') {
match s {
"x" => sched.push(None),
s => sched.push(Some(s.parse().unwrap())),
}
}
let mut sched: Vec::<(usize, usize)> = sched.iter()
.enumerate()
.filter(|(_, x)| x.is_some())
.map(|(a, b)| (a, b.unwrap()))
.collect();
sched.sort_by(|(_, x), (_, y)| x.cmp(y));
let mut iter = sched.iter().rev();
let (i, first) = iter.next().unwrap();
let mut fac = *first;
print!("{} {}", *i, fac);
let mut range: Box<dyn Iterator<Item = usize>> =
Box::new(StepRange { val: *i, step: fac });
while let Some((i, s)) = iter.next() {
let i = *i % *s;
fac *= *s;
println!(" {} {}", i, *s);
let x = range.filter(|&num| num % *s == (*s + i) % *s).next().unwrap();
println!("");
print!("{} {}", x, fac);
range = Box::new(StepRange { val: x, step:fac });
}
println!("{}", fac);
println!("{}", range.next().unwrap());
Ok(())
}
struct StepRange {
val: usize,
step: usize,
}
impl Iterator for StepRange {
type Item = usize;
fn next(&mut self) -> Option<usize> {
let ret = self.val;
print!("{}\r", ret);
self.val += self.step;
Some(ret)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment