[2020][ruby][17.x] refactor

pull/2/head
Alpha Chen 4 years ago
parent f668b8256d
commit 5949372ee0

@ -1,24 +1,28 @@
state = ARGF.read.split("\n").flat_map.with_index {|line,y| DIMENSIONS = 4
line.chars.map.with_index {|c,x| [[0,0,y,x], c == "#"] } state = ARGF.read.strip.split("\n").flat_map.with_index {|line,y|
line.chars.map.with_index {|c,x|
[[x,y].fill(0, 2, DIMENSIONS-2), c == "#"]
}
}.to_h }.to_h
NEIGHBORS = (0...3**4).map {|n| n.digits(3) }.map {|n| (0..3).map {|x| n.fetch(x, 0) - 1 }} - [[0,0,0,0]] NEIGHBORS = (0...3**DIMENSIONS)
.reject {|n| n == 3**DIMENSIONS / 2 }
.map {|n| n.digits(3) }
.map {|n| (0...DIMENSIONS).map {|x| n.fetch(x, 0) - 1 }}
def tick(state) def tick(state)
actives = state.select {|_,c| c }.keys actives = state.select {|_,c| c }.keys
ww, zz, yy, xx = actives.transpose.map(&:minmax).map {|min,max| [min-1, max+1] } minmaxes = actives
Range.new(*ww).flat_map {|w| .transpose.map(&:minmax)
Range.new(*zz).flat_map {|z| .map {|min,max| (min-1..max+1).to_a }
Range.new(*yy).flat_map {|y| coords = minmaxes.inject {|n,x|
Range.new(*xx).map {|x| n.flat_map {|nn| x.map {|xx| [nn, xx] }}
active_neighbors = NEIGHBORS.map {|dw,dz,dy,dx| state[[w+dw,z+dz,y+dy, x+dx]] }.count(&:itself) }.map(&:flatten)
wzyx = [w,z,y,x] coords.map {|coord|
[ wzyx, active_neighbors = NEIGHBORS.count {|delta| state[coord.zip(delta).map {|a,b| a + b }] }
state[wzyx] ? (2..3).cover?(active_neighbors) : active_neighbors == 3 [ coord,
] state[coord] ? (2..3).cover?(active_neighbors) : active_neighbors == 3
} ]
}
}
}.to_h }.to_h
end end

Loading…
Cancel
Save