Percolation/Mean cluster density: Difference between revisions

Added Julia language
m (→‎{{header|Perl 6}}: square matrix only)
(Added Julia language)
Line 622:
16 16 16 0 17 17 17 0 0 15 0 15 0 0 0
16 16 16 0 0 0 17 17 0 15 15 0 0 18 0</lang>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{trans|Python}}
 
<lang julia>using Distributions
 
newgrid(p::Float64, r::Int, c::Int=r) = rand(Bernoulli(p), r, c)
 
function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int)
NOT_CLUSTERED = 1 # const
N, M = size(grid)
dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
# fill cell
grid[r, c] = indx
# check for each direction
for d in dirs
rr, cc = (r, c) .+ d
if checkbounds(Bool, grid, rr, cc) && grid[rr, cc] == NOT_CLUSTERED
walkmaze!(grid, rr, cc, indx)
end
end
end
 
function clustercount!(grid::Matrix{Int})
NOT_CLUSTERED = 1 # const
walkind = 1
for r in 1:size(grid, 1), c in 1:size(grid, 2)
if grid[r, c] == NOT_CLUSTERED
walkind += 1
walkmaze!(grid, r, c, walkind)
end
end
return walkind - 1
end
clusterdensity(p::Float64, n::Int) = clustercount!(newgrid(p, n)) / n ^ 2
 
function printgrid(G::Matrix{Int})
LETTERS = vcat(' ', '#', 'A':'Z', 'a':'z')
for r in 1:size(G, 1)
println(r % 10, ") ", join(LETTERS[G[r, :] .+ 1], ' '))
end
end
 
G = newgrid(0.5, 15)
@printf("Found %i clusters in this %i×%i grid\n\n", clustercount!(G), size(G, 1), size(G, 2))
printgrid(G)
println()
 
const nrange = 2 .^ (4:2:12)
const p = 0.5
const nrep = 5
for n in nrange
sim = mean(clusterdensity(p, n) for _ in 1:nrep)
@printf("nrep = %2i p = %.2f dim = %-13s sim = %.5f\n", nrep, p, "$n × $n", sim)
end</lang>
 
{{out}}
<pre>Found 20 clusters in this 15×15 grid
 
1) A B C C D D D
2) E F D D
3) G F D D D D D D
4) G G H F I D D D J
5) G G K L D J
6) G G G G M N N
7) G G G G G G O O O N
8) G G O N N N
9) P P P G G G N N
0) P P P P G Q Q Q N
1) P Q Q Q Q N N
2) P N N N N
3) P P P R S N
4) P R R R S S N N
5) R R R S T N
 
nrep = 5 p = 0.50 dim = 16 × 16 sim = 0.07500
nrep = 5 p = 0.50 dim = 64 × 64 sim = 0.07178
nrep = 5 p = 0.50 dim = 256 × 256 sim = 0.06690
nrep = 5 p = 0.50 dim = 1024 × 1024 sim = 0.06609
nrep = 5 p = 0.50 dim = 4096 × 4096 sim = 0.06588</pre>
 
=={{header|Perl 6}}==
Anonymous user