June 2018 Update

This commit is contained in:
Ingy döt Net 2018-06-22 20:57:24 +00:00
parent ba8067c3b7
commit 22f33d4004
5278 changed files with 84726 additions and 14379 deletions

View file

@ -0,0 +1,51 @@
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

View file

@ -0,0 +1,80 @@
// version 1.2.10
import java.util.Random
val rand = Random()
const val RAND_MAX = 32767
lateinit var map: IntArray
var w = 0
var ww = 0
const val ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const val ALEN = ALPHA.length - 3
fun makeMap(p: Double) {
val thresh = (p * RAND_MAX).toInt()
ww = w * w
var i = ww
map = IntArray(i)
while (i-- != 0) {
val r = rand.nextInt(RAND_MAX + 1)
if (r < thresh) map[i] = -1
}
}
fun showCluster() {
var k = 0
for (i in 0 until w) {
for (j in 0 until w) {
val s = map[k++]
val c = if (s < ALEN) ALPHA[1 + s] else '?'
print(" $c")
}
println()
}
}
fun recur(x: Int, v: Int) {
if ((x in 0 until ww) && map[x] == -1) {
map[x] = v
recur(x - w, v)
recur(x - 1, v)
recur(x + 1, v)
recur(x + w, v)
}
}
fun countClusters(): Int {
var cls = 0
for (i in 0 until ww) {
if (map[i] != -1) continue
recur(i, ++cls)
}
return cls
}
fun tests(n: Int, p: Double): Double {
var k = 0.0
for (i in 0 until n) {
makeMap(p)
k += countClusters().toDouble() / ww
}
return k / n
}
fun main(args: Array<String>) {
w = 15
makeMap(0.5)
val cls = countClusters()
println("width = 15, p = 0.5, $cls clusters:")
showCluster()
println("\np = 0.5, iter = 5:")
w = 1 shl 2
while (w <= 1 shl 13) {
val t = tests(5, 0.5)
println("%5d %9.6f".format(w, t))
w = w shl 1
}
}