Commit 96a30f59
96a30f59f7fbMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 2 files · ~2 modified
Description
Rewrite life.rb with _1, times.map, Range#sum/count blocks
Idiomatic Ruby style using:
- (-1..1).sum { |iy| (-1..1).count { |ix| ... } } for neighbor counting
- SIZE.times.map { |i| ... } for grid generation
- SIZE.times.map { 0 } for initialization
- cells.count { _1 == 1 } for live cell counting
Also fix: cross-function type inference now traverses block bodies when scanning for nested function calls.
Spinel: <0.01s vs CRuby: 1.49s (>100x faster)
Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]
Details
- Commit
- 96a30f59f7fb
- Parent
- 6387a185907b
examples/life.rbmodifiedView file
@@ -17,50 +17,28 @@
1717
end1818
1919
def neighbors(cells, x, y)20-
count = 021-
iy = -122-
while iy <= 123-
ix = -124-
while ix <= 125-
if cell_get(cells, x + ix, y + iy) == 126-
count = count + 127-
end28-
ix = ix + 129-
end30-
iy = iy + 131-
end32-
count20+
(-1..1).sum { |iy|21+
(-1..1).count { |ix| cell_get(cells, x + ix, y + iy) == 1 }22+
}3323
end3424
3525
def next_gen(cells)36-
new_cells = Array.new37-
y = 038-
while y < H39-
x = 040-
while x < W41-
n = neighbors(cells, x, y)42-
alive = cells[y * W + x]43-
if n == 344-
new_cells.push(1)45-
elsif n == 4 && alive == 146-
new_cells.push(1)47-
else48-
new_cells.push(0)49-
end50-
x = x + 126+
SIZE.times.map { |i|27+
y = i / W28+
x = i % W29+
n = neighbors(cells, x, y)30+
if n == 331+
132+
elsif n == 4 && cells[i] == 133+
134+
else35+
05136
end52-
y = y + 153-
end54-
new_cells37+
}5538
end5639
5740
# Initialize with a deterministic pattern (glider + blinker)58-
cells = Array.new59-
i = 060-
while i < SIZE61-
cells.push(0)62-
i = i + 163-
end41+
cells = SIZE.times.map { 0 }6442
6543
# Glider at (1,1)6644
cells[1 * W + 2] = 1@@ -76,20 +54,11 @@
7654
7755
# Run7856
gen = 079-
live = 08057
while gen < GENERATIONS8158
cells = next_gen(cells)8259
gen = gen + 18360
end8461
8562
# Count final live cells86-
i = 087-
while i < SIZE88-
if cells[i] == 189-
live = live + 190-
end91-
i = i + 192-
end93-
94-
puts live63+
puts cells.count { _1 == 1 }9564
puts "done"src/type.cmodifiedView file
Loading diff…