Percolation/Site percolation: Difference between revisions

Added Julia language
(simplified and sped up haskell version)
(Added Julia language)
Line 982:
· · · · · · · · · · · ·
</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{trans|Python}}
 
<lang julia>using Distributions
 
newgrid(p::Float64, M::Int=15, N::Int=15) = rand(Bernoulli(p), M, N)
 
function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int)
NOT_VISITED = 1 # const
N, M = size(grid)
grid[r, c] = indx
 
rst = false
# down or bottom
if r < N && grid[r+1, c] == NOT_VISITED
rst = walkmaze!(grid, r + 1, c, indx)
elseif r == N
rst = true
end
# left
if !rst && c > 1 && grid[r, c-1] == NOT_VISITED
rst = walkmaze!(grid, r, c - 1, indx)
end
# right
if !rst && c < M && grid[r, c+1] == NOT_VISITED
rst = walkmaze!(grid, r, c + 1, indx)
end
# up
if !rst && r > 1 && grid[r-1, c] == NOT_VISITED
rst = walkmaze!(grid, r - 1, c, indx)
end
return rst
end
 
function checkpath!(grid::Matrix{Int})
NOT_VISITED = 1 # const
N, M = size(grid)
walkind = 1
for m in 1:M
if grid[1, m] == NOT_VISITED
walkind += 1
if walkmaze!(grid, 1, m, walkind)
return true
end
end
end
return false
end
 
function printgrid(G::Matrix{Int})
NOT_VISITED = 1 # const
LETTERS = vcat(' ', '#', 'A':'Z')
for r in 1:size(G, 1)
println(r % 10, ") ", join(LETTERS[G[r, :] .+ 1], ' '))
end
if any(G[end, :] .> 1)
println("!) ", join((ifelse(c > 1, LETTERS[c+1], ' ') for c in G[end, :]), ' '))
end
end
 
const nrep = 1000 # const
sampleprinted = false
 
p = collect(0.0:0.1:1.0)
f = similar(p)
for i in linearindices(f)
c = 0
for _ in 1:nrep
G = newgrid(p[i])
perc = checkpath!(G)
if perc
c += 1
if !sampleprinted
@printf("Sample percolation, %i×%i grid, p = %.2f\n\n", size(G, 1), size(G, 2), p[i])
printgrid(G)
sampleprinted = true
end
end
end
f[i] = c / nrep
end
 
println("\nFrequencies for $nrep tries that percolate through\n")
for (pi, fi) in zip(p, f)
@printf("p = %.1f ⇛ f = %.2f\n", pi, fi)
end</lang>
 
{{out}}
<pre>Sample percolation, 15×15 grid, p = 0.40
 
1) A B B
2) # # A A A A A A A B
3) # # A A A B #
4) # # # # B B
5) # # # # B # # #
6) # # # # B #
7) # # # # # B # # #
8) # # # # # # B # # #
9) # # # # B #
0) # B B B # #
1) # # # # # B
2) # # # # # B B # # #
3) # # # # # B B B #
4) # # # # # # # B
5) # # # B #
!) B
 
Frequencies for 1000 tries that percolate through
 
p = 0.0 ⇛ f = 0.00
p = 0.1 ⇛ f = 0.00
p = 0.2 ⇛ f = 0.00
p = 0.3 ⇛ f = 0.00
p = 0.4 ⇛ f = 0.01
p = 0.5 ⇛ f = 0.09
p = 0.6 ⇛ f = 0.56
p = 0.7 ⇛ f = 0.96
p = 0.8 ⇛ f = 1.00
p = 0.9 ⇛ f = 1.00
p = 1.0 ⇛ f = 1.00</pre>
 
=={{header|Perl 6}}==
Anonymous user