Skip to content

Instantly share code, notes, and snippets.

@r2p2
Created December 9, 2017 22:17
Show Gist options
  • Save r2p2/434df5e3914875b80bf59b4ca58e390f to your computer and use it in GitHub Desktop.
Save r2p2/434df5e3914875b80bf59b4ca58e390f to your computer and use it in GitHub Desktop.
Advent Of Code Day 6
struct Mem {
mem : Vec<i32>
}
impl Mem {
pub fn new(mem : &Vec<i32>) -> Mem {
Mem {
mem : mem.clone()
}
}
pub fn mem(&self) -> &Vec<i32> {
&self.mem
}
pub fn highest_bank(&self) -> usize {
let mut index = 0;
let mut max = 0;
for (i, &bank) in self.mem.iter().enumerate().rev() {
if bank >= max {
max = bank;
index = i;
}
}
index
}
pub fn redistribute(&mut self) {
let mut idx = self.highest_bank();
let mut val = self.mem[idx];
self.mem[idx] = 0;
while val > 0 {
val -= 1;
idx = (idx + 1) % self.mem.len();
self.mem[idx] += 1;
}
}
pub fn show(&self) {
println!("{:?}", self.mem);
}
}
fn main() {
let test_data = vec![0, 2, 7, 0];
let prod_data = vec![10, 3, 15, 10, 5, 15, 5, 15, 9, 2, 5, 8, 5, 2, 3, 6];
let mut mem = Mem::new(&prod_data);
mem.show();
let mut cycle = 0;
let mut banks = Vec::<Vec<i32>>::new();
loop {
cycle += 1;
mem.redistribute();
mem.show();
let curr_mem = mem.mem();
if banks.contains(&curr_mem) {
break;
}
banks.push(curr_mem.clone());
}
let mut cycle_2 = 0;
let first = mem.mem().clone();
loop {
cycle_2 += 1;
mem.redistribute();
mem.show();
if &first == mem.mem() {
break;
}
}
println!("cycles : {}", cycle);
println!("cycles 2: {}", cycle_2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment