my solutions to advent of code
aoc advent-of-code

i didnt think of this as in that wasnt me making having this idea but thats cool

aylac.top 71d4c03c 977052bd

verified
Changed files
+28 -30
2015
18
rust
src
+28 -30
2015/18/rust/src/main.rs
···
use std::mem::swap;
fn generations(times: u32, mut world: Vec<u8>, size: usize, stuck: bool) -> Vec<u8> {
-
#[inline]
-
fn pos(x: usize, y: usize, size: usize) -> usize {
-
y * (size + 2) + x
-
}
-
-
#[inline]
-
fn get_at(world: &Vec<u8>, size: usize, x: usize, y: usize) -> u8 {
-
// this is in known bounds
-
unsafe { *world.get_unchecked(pos(x, y, size)) }
-
}
+
let pos = |x, y| y * (size + 2) + x;
let sizep = size + 1;
let mut new_world = vec![0_u8; (size + 2).pow(2)];
-
if stuck {
-
world[pos(1, 1, size)] = 1;
-
world[pos(size, 1, size)] = 1;
-
world[pos(1, size, size)] = 1;
-
world[pos(size, size, size)] = 1;
+
unsafe {
+
if stuck {
+
*world.get_unchecked_mut(pos(1, 1)) = 1;
+
*world.get_unchecked_mut(pos(size, 1)) = 1;
+
*world.get_unchecked_mut(pos(1, size)) = 1;
+
*world.get_unchecked_mut(pos(size, size)) = 1;
+
}
}
for _ in 0..times {
···
let xm = xo - 1;
let xp = xo + 1;
-
let was = get_at(&world, size, xo, yo) == 1;
-
let neighbours = get_at(&world, size, xm, ym)
-
+ get_at(&world, size, xo, ym)
-
+ get_at(&world, size, xp, ym)
-
+ get_at(&world, size, xm, yo)
-
+ get_at(&world, size, xp, yo)
-
+ get_at(&world, size, xm, yp)
-
+ get_at(&world, size, xo, yp)
-
+ get_at(&world, size, xp, yp);
-
new_world[pos(xo, yo, size)] = (neighbours == 3 || (neighbours == 2 && was)) as u8;
+
unsafe {
+
let was = *world.get_unchecked(pos(xo, yo)) == 1_u8;
+
let neighbours = world.get_unchecked(pos(xm, ym))
+
+ world.get_unchecked(pos(xo, ym))
+
+ world.get_unchecked(pos(xp, ym))
+
+ world.get_unchecked(pos(xm, yo))
+
+ world.get_unchecked(pos(xp, yo))
+
+ world.get_unchecked(pos(xm, yp))
+
+ world.get_unchecked(pos(xo, yp))
+
+ world.get_unchecked(pos(xp, yp));
+
*new_world.get_unchecked_mut(pos(xo, yo)) =
+
(neighbours == 3 || (neighbours == 2 && was)) as u8;
+
}
}
}
swap(&mut world, &mut new_world);
// i hate the duplication here :(
-
if stuck {
-
world[pos(1, 1, size)] = 1;
-
world[pos(size, 1, size)] = 1;
-
world[pos(1, size, size)] = 1;
-
world[pos(size, size, size)] = 1;
+
unsafe {
+
if stuck {
+
*world.get_unchecked_mut(pos(1, 1)) = 1;
+
*world.get_unchecked_mut(pos(size, 1)) = 1;
+
*world.get_unchecked_mut(pos(1, size)) = 1;
+
*world.get_unchecked_mut(pos(size, size)) = 1;
+
}
}
}
world