Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Last active January 7, 2026 23:00
Show Gist options
  • Select an option

  • Save matthewjberger/b1078897e833f7d11fd393a5ad858ad9 to your computer and use it in GitHub Desktop.

Select an option

Save matthewjberger/b1078897e833f7d11fd393a5ad858ad9 to your computer and use it in GitHub Desktop.
Port of Game of Life APL life ← {⊃1 ⍵ ∨.∧ 3 4 = +/ +⌿ ¯1 0 1 ∘.⊖ ¯1 0 1 ⌽¨ ⊂⍵}
fn main() {
let mut grid = vec![
vec![0,0,0,0,0,0,0,0,0,0],
vec![0,0,1,0,0,0,0,0,0,0],
vec![0,0,0,1,0,0,0,0,0,0],
vec![0,1,1,1,0,0,0,0,0,0],
vec![0,0,0,0,0,0,0,0,0,0],
vec![0,0,0,0,0,0,0,0,0,0],
vec![0,0,0,0,0,0,0,0,0,0],
vec![0,0,0,0,0,0,0,0,0,0],
vec![0,0,0,0,0,0,0,0,0,0],
vec![0,0,0,0,0,0,0,0,0,0],
];
for step in 0..20 {
println!("Generation {}:", step);
display(&grid);
grid = life(&grid);
}
}
fn rotate_h(grid: &Vec<Vec<i32>>, n: i32) -> Vec<Vec<i32>> {
grid.iter().map(|row| {
let len = row.len() as i32;
let n = ((n % len) + len) % len;
row.iter().cycle().skip(n as usize).take(row.len()).cloned().collect()
}).collect()
}
fn rotate_v(grid: &Vec<Vec<i32>>, n: i32) -> Vec<Vec<i32>> {
let len = grid.len() as i32;
let n = ((n % len) + len) % len;
grid.iter().cycle().skip(n as usize).take(grid.len()).cloned().collect()
}
fn sum_grids(grids: &[Vec<Vec<i32>>]) -> Vec<Vec<i32>> {
let rows = grids[0].len();
let cols = grids[0][0].len();
(0..rows).map(|r| {
(0..cols).map(|c| {
grids.iter().map(|g| g[r][c]).sum()
}).collect()
}).collect()
}
fn life(w: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let h_rotated: Vec<_> = [-1, 0, 1].iter()
.map(|&n| rotate_h(w, n))
.collect();
let all_shifted: Vec<_> = [-1, 0, 1].iter()
.flat_map(|&v| h_rotated.iter().map(move |g| rotate_v(g, v)))
.collect();
let sums = sum_grids(&all_shifted);
let rows = w.len();
let cols = w[0].len();
(0..rows).map(|r| {
(0..cols).map(|c| {
let sum = sums[r][c];
let was_alive = w[r][c];
if sum == 3 || (sum == 4 && was_alive == 1) { 1 } else { 0 }
}).collect()
}).collect()
}
fn display(grid: &Vec<Vec<i32>>) {
for row in grid {
for &cell in row {
print!("{}", if cell == 1 { "#" } else { "." });
}
println!();
}
println!();
}
fn main() {
let mut g = [0i32; 100];
for i in [12usize, 23, 31, 32, 33] {
g[i] = 1
}
for _ in 0..20 {
for i in 0..100 {
print!("{}", b".O"[g[i] as usize] as char);
if i % 10 == 9 {
println!()
}
}
println!();
let o = g;
g = std::array::from_fn(|i| {
let s: i32 = (0..9usize)
.map(|j| o[((i / 10 + j / 3 + 9) % 10) * 10 + (i % 10 + j % 3 + 9) % 10])
.sum();
(s == 3 || s == 4 && o[i] == 1) as i32
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment