Update all new Tasks
This commit is contained in:
parent
00a190b0a6
commit
91df62d461
5697 changed files with 93386 additions and 804 deletions
23
Task/Percolation-Bond-percolation/00DESCRIPTION
Normal file
23
Task/Percolation-Bond-percolation/00DESCRIPTION
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{{Percolation Simulation}}
|
||||
Given an <math>M \times N</math> rectangular array of cells numbered <math>\mathrm{cell}[0..M-1, 0..N-1]</math>assume <math>M</math> is horizontal and <math>N</math> is downwards. Each <math>\mathrm{cell}[m, n]</math> is bounded by (horizontal) walls <math>\mathrm{hwall}[m, n]</math> and <math>\mathrm{hwall}[m+1, n]</math>; (vertical) walls <math>\mathrm{vwall}[m, n]</math> and <math>\mathrm{vwall}[m, n+1]</math>
|
||||
|
||||
Assume that the probability of any wall being present is a constant <math>p</math> where
|
||||
: <math>0.0 \le p \le 1.0</math>
|
||||
Except for the outer horizontal walls at <math>m = 0</math> and <math>m = M</math> which are always present.
|
||||
|
||||
;The task:
|
||||
Simulate pouring a fluid onto the top surface (<math>n = 0</math>) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall.
|
||||
|
||||
The fluid does not move beyond the horizontal constraints of the grid.
|
||||
|
||||
The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point.
|
||||
|
||||
Given <math>p</math> repeat the percolation <math>t</math> times to estimate the proportion of times that the fluid can percolate to the bottom for any given <math>p</math>.
|
||||
|
||||
Show how the probability of percolating through the random grid changes with <math>p</math> going from <math>0.0</math> to <math>1.0</math> in <math>0.1</math> increments and with the number of repetitions to estimate the fraction at any given <math>p</math> as <math>t = 100</math>.
|
||||
|
||||
Use an <math>M=10, N=10</math> grid of cells for all cases.
|
||||
|
||||
Optionally depict fluid successfully percolating through a grid graphically.
|
||||
|
||||
Show all output on this page.
|
||||
2
Task/Percolation-Bond-percolation/00META.yaml
Normal file
2
Task/Percolation-Bond-percolation/00META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Percolation Simulations
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// cell states
|
||||
#define FILL 1
|
||||
#define RWALL 2 // right wall
|
||||
#define BWALL 4 // bottom wall
|
||||
|
||||
typedef unsigned int c_t;
|
||||
|
||||
c_t *cells, *start, *end;
|
||||
int m, n;
|
||||
|
||||
void make_grid(double p, int x, int y)
|
||||
{
|
||||
int i, j, thresh = RAND_MAX * p;
|
||||
m = x, n = y;
|
||||
|
||||
// Allocate two addition rows to avoid checking bounds.
|
||||
// Bottom row is also required by drippage
|
||||
start = realloc(start, m * (n + 2) * sizeof(c_t));
|
||||
cells = start + m;
|
||||
|
||||
for (i = 0; i < m; i++)
|
||||
start[i] = BWALL | RWALL;
|
||||
|
||||
for (i = 0, end = cells; i < y; i++) {
|
||||
for (j = x; --j; )
|
||||
*end++ = (rand() < thresh ? BWALL : 0)
|
||||
|(rand() < thresh ? RWALL : 0);
|
||||
*end++ = RWALL | (rand() < thresh ? BWALL: 0);
|
||||
}
|
||||
memset(end, 0, sizeof(c_t) * m);
|
||||
}
|
||||
|
||||
void show_grid(void)
|
||||
{
|
||||
int i, j;
|
||||
|
||||
for (j = 0; j < m; j++) printf("+--");
|
||||
puts("+");
|
||||
|
||||
for (i = 0; i <= n; i++) {
|
||||
putchar(i == n ? ' ' : '|');
|
||||
for (j = 0; j < m; j++) {
|
||||
printf((cells[i*m + j] & FILL) ? "[]" : " ");
|
||||
putchar((cells[i*m + j] & RWALL) ? '|' : ' ');
|
||||
}
|
||||
putchar('\n');
|
||||
|
||||
if (i == n) return;
|
||||
|
||||
for (j = 0; j < m; j++)
|
||||
printf((cells[i*m + j] & BWALL) ? "+--" : "+ ");
|
||||
puts("+");
|
||||
}
|
||||
}
|
||||
|
||||
int fill(c_t *p)
|
||||
{
|
||||
if ((*p & FILL)) return 0;
|
||||
*p |= FILL;
|
||||
if (p >= end) return 1; // success: reached bottom row
|
||||
|
||||
return ( !(p[ 0] & BWALL) && fill(p + m) ) ||
|
||||
( !(p[ 0] & RWALL) && fill(p + 1) ) ||
|
||||
( !(p[-1] & RWALL) && fill(p - 1) ) ||
|
||||
( !(p[-m] & BWALL) && fill(p - m) );
|
||||
}
|
||||
|
||||
int percolate(void)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < m && !fill(cells + i); i++);
|
||||
|
||||
return i < m;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
make_grid(.5, 10, 10);
|
||||
percolate();
|
||||
show_grid();
|
||||
|
||||
int cnt, i, p;
|
||||
|
||||
puts("\nrunning 10x10 grids 10000 times for each p:");
|
||||
for (p = 1; p < 10; p++) {
|
||||
for (cnt = i = 0; i < 10000; i++) {
|
||||
make_grid(p / 10., 10, 10);
|
||||
cnt += percolate();
|
||||
//show_grid(); // don't
|
||||
}
|
||||
printf("p = %3g: %.4f\n", p / 10., (double)cnt / i);
|
||||
}
|
||||
|
||||
free(start);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
import std.stdio, std.random, std.array, std.range, std.algorithm;
|
||||
|
||||
struct Grid {
|
||||
// Not enforced by runtime and type system:
|
||||
// a Cell must contain only the flags bits.
|
||||
alias Cell = uint;
|
||||
|
||||
enum : Cell { // Cell states (bit flags).
|
||||
empty = 0,
|
||||
filled = 1,
|
||||
rightWall = 2,
|
||||
bottomWall = 4
|
||||
}
|
||||
|
||||
const size_t nc, nr;
|
||||
Cell[] cells;
|
||||
|
||||
this(in size_t nRows, in size_t nCols) pure nothrow {
|
||||
nr = nRows;
|
||||
nc = nCols;
|
||||
|
||||
// Allocate two addition rows to avoid checking bounds.
|
||||
// Bottom row is also required by drippage.
|
||||
cells = new Cell[nc * (nr + 2)];
|
||||
}
|
||||
|
||||
void initialize(in double prob, ref Xorshift rng) {
|
||||
cells[0 .. nc] = bottomWall | rightWall; // First row.
|
||||
|
||||
uint pos = nc;
|
||||
foreach (immutable r; 1 .. nr + 1) {
|
||||
foreach (immutable c; 1 .. nc)
|
||||
cells[pos++] = (uniform01 < prob ?bottomWall : empty) |
|
||||
(uniform01 < prob ? rightWall : empty);
|
||||
cells[pos++] = rightWall |
|
||||
(uniform01 < prob ? bottomWall : empty);
|
||||
}
|
||||
|
||||
cells[$ - nc .. $] = empty; // Last row.
|
||||
}
|
||||
|
||||
bool percolate() pure nothrow @nogc {
|
||||
bool fill(in size_t i) pure nothrow @nogc {
|
||||
if (cells[i] & filled)
|
||||
return false;
|
||||
|
||||
cells[i] |= filled;
|
||||
|
||||
if (i >= cells.length - nc)
|
||||
return true; // Success: reached bottom row.
|
||||
|
||||
return (!(cells[i] & bottomWall) && fill(i + nc)) ||
|
||||
(!(cells[i] & rightWall) && fill(i + 1)) ||
|
||||
(!(cells[i - 1] & rightWall) && fill(i - 1)) ||
|
||||
(!(cells[i - nc] & bottomWall) && fill(i - nc));
|
||||
}
|
||||
|
||||
return iota(nc, nc + nc).any!fill;
|
||||
}
|
||||
|
||||
void show() const {
|
||||
writeln("+-".replicate(nc), '+');
|
||||
|
||||
foreach (immutable r; 1 .. nr + 2) {
|
||||
write(r == nr + 1 ? ' ' : '|');
|
||||
foreach (immutable c; 0 .. nc) {
|
||||
immutable cell = cells[r * nc + c];
|
||||
write((cell & filled) ? (r <= nr ? '#' : 'X') : ' ');
|
||||
write((cell & rightWall) ? '|' : ' ');
|
||||
}
|
||||
writeln;
|
||||
|
||||
if (r == nr + 1)
|
||||
return;
|
||||
|
||||
foreach (immutable c; 0 .. nc)
|
||||
write((cells[r * nc + c] & bottomWall) ? "+-" : "+ ");
|
||||
'+'.writeln;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
enum uint nr = 10, nc = 10; // N. rows and columns of the grid.
|
||||
enum uint nTries = 10_000; // N. simulations for each probability.
|
||||
enum uint nStepsProb = 10; // N. steps of probability.
|
||||
|
||||
auto rng = Xorshift(2);
|
||||
auto g = Grid(nr, nc);
|
||||
g.initialize(0.5, rng);
|
||||
g.percolate;
|
||||
g.show;
|
||||
|
||||
writefln("\nRunning %dx%d grids %d times for each p:",
|
||||
nr, nc, nTries);
|
||||
foreach (immutable p; 0 .. nStepsProb) {
|
||||
immutable probability = p / double(nStepsProb);
|
||||
uint nPercolated = 0;
|
||||
foreach (immutable i; 0 .. nTries) {
|
||||
g.initialize(probability, rng);
|
||||
nPercolated += g.percolate;
|
||||
}
|
||||
writefln("p = %0.2f: %.4f",
|
||||
probability, nPercolated / double(nTries));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
const (
|
||||
m, n = 10, 10
|
||||
t = 1000
|
||||
minp, maxp, Δp = 0.1, 0.99, 0.1
|
||||
)
|
||||
|
||||
// Purposely don't seed for a repeatable example grid:
|
||||
g := NewGrid(.5, m, n)
|
||||
g.Percolate()
|
||||
fmt.Println(g)
|
||||
|
||||
rand.Seed(time.Now().UnixNano()) // could pick a better seed
|
||||
for p := float64(minp); p < maxp; p += Δp {
|
||||
count := 0
|
||||
for i := 0; i < t; i++ {
|
||||
g := NewGrid(p, m, n)
|
||||
if g.Percolate() {
|
||||
count++
|
||||
}
|
||||
}
|
||||
fmt.Printf("p=%.2f, %.3f\n", p, float64(count)/t)
|
||||
}
|
||||
}
|
||||
|
||||
type cell struct {
|
||||
full bool
|
||||
right, down bool // true if open to the right (x+1) or down (y+1)
|
||||
}
|
||||
|
||||
type grid struct {
|
||||
cell [][]cell // row first, i.e. [y][x]
|
||||
}
|
||||
|
||||
func NewGrid(p float64, xsize, ysize int) *grid {
|
||||
g := &grid{cell: make([][]cell, ysize)}
|
||||
for y := range g.cell {
|
||||
g.cell[y] = make([]cell, xsize)
|
||||
for x := 0; x < xsize-1; x++ {
|
||||
if rand.Float64() > p {
|
||||
g.cell[y][x].right = true
|
||||
}
|
||||
if rand.Float64() > p {
|
||||
g.cell[y][x].down = true
|
||||
}
|
||||
}
|
||||
if rand.Float64() > p {
|
||||
g.cell[y][xsize-1].down = true
|
||||
}
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
var (
|
||||
full = map[bool]string{false: " ", true: "**"}
|
||||
hopen = map[bool]string{false: "--", true: " "}
|
||||
vopen = map[bool]string{false: "|", true: " "}
|
||||
)
|
||||
|
||||
func (g *grid) String() string {
|
||||
var buf bytes.Buffer
|
||||
// Don't really need to call Grow but it helps avoid multiple
|
||||
// reallocations if the size is large.
|
||||
buf.Grow((len(g.cell) + 1) * len(g.cell[0]) * 7)
|
||||
|
||||
for _ = range g.cell[0] {
|
||||
buf.WriteString("+")
|
||||
buf.WriteString(hopen[false])
|
||||
}
|
||||
buf.WriteString("+\n")
|
||||
for y := range g.cell {
|
||||
buf.WriteString(vopen[false])
|
||||
for x := range g.cell[y] {
|
||||
buf.WriteString(full[g.cell[y][x].full])
|
||||
buf.WriteString(vopen[g.cell[y][x].right])
|
||||
}
|
||||
buf.WriteByte('\n')
|
||||
for x := range g.cell[y] {
|
||||
buf.WriteString("+")
|
||||
buf.WriteString(hopen[g.cell[y][x].down])
|
||||
}
|
||||
buf.WriteString("+\n")
|
||||
}
|
||||
ly := len(g.cell) - 1
|
||||
for x := range g.cell[ly] {
|
||||
buf.WriteByte(' ')
|
||||
buf.WriteString(full[g.cell[ly][x].down && g.cell[ly][x].full])
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (g *grid) Percolate() bool {
|
||||
for x := range g.cell[0] {
|
||||
if g.fill(x, 0) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (g *grid) fill(x, y int) bool {
|
||||
if y >= len(g.cell) {
|
||||
return true // Out the bottom
|
||||
}
|
||||
if g.cell[y][x].full {
|
||||
return false // Allready filled
|
||||
}
|
||||
g.cell[y][x].full = true
|
||||
|
||||
if g.cell[y][x].down && g.fill(x, y+1) {
|
||||
return true
|
||||
}
|
||||
if g.cell[y][x].right && g.fill(x+1, y) {
|
||||
return true
|
||||
}
|
||||
if x > 0 && g.cell[y][x-1].right && g.fill(x-1, y) {
|
||||
return true
|
||||
}
|
||||
if y > 0 && g.cell[y-1][x].down && g.fill(x, y-1) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
from collections import namedtuple
|
||||
from random import random
|
||||
from pprint import pprint as pp
|
||||
|
||||
Grid = namedtuple('Grid', 'cell, hwall, vwall')
|
||||
|
||||
M, N, t = 10, 10, 100
|
||||
|
||||
class PercolatedException(Exception): pass
|
||||
|
||||
HVF = [(' .', ' _'), (':', '|'), (' ', '#')] # Horiz, vert, fill chars
|
||||
|
||||
def newgrid(p):
|
||||
hwall = [[int(random() < p) for m in range(M)]
|
||||
for n in range(N+1)]
|
||||
vwall = [[(1 if m in (0, M) else int(random() < p)) for m in range(M+1)]
|
||||
for n in range(N)]
|
||||
cell = [[0 for m in range(M)]
|
||||
for n in range(N)]
|
||||
return Grid(cell, hwall, vwall)
|
||||
|
||||
def pgrid(grid, percolated=None):
|
||||
cell, hwall, vwall = grid
|
||||
h, v, f = HVF
|
||||
for n in range(N):
|
||||
print(' ' + ''.join(h[hwall[n][m]] for m in range(M)))
|
||||
print('%i) ' % (n % 10) + ''.join(v[vwall[n][m]] + f[cell[n][m] if m < M else 0]
|
||||
for m in range(M+1))[:-1])
|
||||
n = N
|
||||
print(' ' + ''.join(h[hwall[n][m]] for m in range(M)))
|
||||
if percolated:
|
||||
where = percolated.args[0][0]
|
||||
print('!) ' + ' ' * where + ' ' + f[1])
|
||||
|
||||
def pour_on_top(grid):
|
||||
cell, hwall, vwall = grid
|
||||
n = 0
|
||||
try:
|
||||
for m in range(M):
|
||||
if not hwall[n][m]:
|
||||
flood_fill(m, n, cell, hwall, vwall)
|
||||
except PercolatedException as ex:
|
||||
return ex
|
||||
return None
|
||||
|
||||
|
||||
def flood_fill(m, n, cell, hwall, vwall):
|
||||
# fill cell
|
||||
cell[n][m] = 1
|
||||
# bottom
|
||||
if n < N - 1 and not hwall[n + 1][m] and not cell[n+1][m]:
|
||||
flood_fill(m, n+1, cell, hwall, vwall)
|
||||
# THE bottom
|
||||
elif n == N - 1 and not hwall[n + 1][m]:
|
||||
raise PercolatedException((m, n+1))
|
||||
# left
|
||||
if m and not vwall[n][m] and not cell[n][m - 1]:
|
||||
flood_fill(m-1, n, cell, hwall, vwall)
|
||||
# right
|
||||
if m < M - 1 and not vwall[n][m + 1] and not cell[n][m + 1]:
|
||||
flood_fill(m+1, n, cell, hwall, vwall)
|
||||
# top
|
||||
if n and not hwall[n][m] and not cell[n-1][m]:
|
||||
flood_fill(m, n-1, cell, hwall, vwall)
|
||||
|
||||
if __name__ == '__main__':
|
||||
sample_printed = False
|
||||
pcount = {}
|
||||
for p10 in range(11):
|
||||
p = (10 - p10) / 10.0 # count down so sample print is interesting
|
||||
pcount[p] = 0
|
||||
for tries in range(t):
|
||||
grid = newgrid(p)
|
||||
percolated = pour_on_top(grid)
|
||||
if percolated:
|
||||
pcount[p] += 1
|
||||
if not sample_printed:
|
||||
print('\nSample percolating %i x %i grid' % (M, N))
|
||||
pgrid(grid, percolated)
|
||||
sample_printed = True
|
||||
print('\n p: Fraction of %i tries that percolate through' % t )
|
||||
|
||||
pp({p:c/float(t) for p, c in pcount.items()})
|
||||
1
Task/Percolation-Bond-percolation/README
Normal file
1
Task/Percolation-Bond-percolation/README
Normal file
|
|
@ -0,0 +1 @@
|
|||
Data source: http://rosettacode.org/wiki/Percolation/Bond_percolation
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
#lang racket
|
||||
|
||||
(define has-left-wall? (lambda (x) (bitwise-bit-set? x 0)))
|
||||
(define has-right-wall? (lambda (x) (bitwise-bit-set? x 1)))
|
||||
(define has-top-wall? (lambda (x) (bitwise-bit-set? x 2)))
|
||||
(define has-bottom-wall? (lambda (x) (bitwise-bit-set? x 3)))
|
||||
(define has-fluid? (lambda (x) (bitwise-bit-set? x 4)))
|
||||
|
||||
(define (walls->cell l? r? t? b?)
|
||||
(+ (if l? 1 0) (if r? 2 0) (if t? 4 0) (if b? 8 0)))
|
||||
|
||||
(define (bonded-percol-grid M N p)
|
||||
(define rv (make-vector (* M N)))
|
||||
(for* ((idx (in-range (* M N))))
|
||||
(define left-wall?
|
||||
(or (zero? (modulo idx M))
|
||||
(has-right-wall? (vector-ref rv (sub1 idx)))))
|
||||
(define right-wall?
|
||||
(or (= (modulo idx M) (sub1 M))
|
||||
(< (random) p)))
|
||||
(define top-wall?
|
||||
(if (< idx M) (< (random) p)
|
||||
(has-bottom-wall? (vector-ref rv (- idx M)))))
|
||||
(define bottom-wall? (< (random) p))
|
||||
(define cell-value
|
||||
(walls->cell left-wall? right-wall? top-wall? bottom-wall?))
|
||||
(vector-set! rv idx cell-value))
|
||||
rv)
|
||||
|
||||
(define (display-percol-grid M . vs)
|
||||
(define N (/ (vector-length (car vs)) M))
|
||||
(define-syntax-rule (tab-eol m)
|
||||
(when (= m (sub1 M)) (printf "\t")))
|
||||
(for ((n N))
|
||||
(for* ((v vs) (m M))
|
||||
(when (zero? m) (printf "+"))
|
||||
(printf
|
||||
(match (vector-ref v (+ (* n M) m))
|
||||
((? has-top-wall?) "-+")
|
||||
((? has-fluid?) "#+")
|
||||
(else ".+")))
|
||||
(tab-eol m))
|
||||
(newline)
|
||||
(for* ((v vs) (m M))
|
||||
(when (zero? m) (printf "|"))
|
||||
(printf
|
||||
(match (vector-ref v (+ (* n M) m))
|
||||
((and (? has-fluid?) (? has-right-wall?)) "#|")
|
||||
((? has-right-wall?) ".|")
|
||||
((? has-fluid?) "##")
|
||||
(else "..")))
|
||||
(tab-eol m))
|
||||
(newline))
|
||||
(for* ((v vs) (m M))
|
||||
(when (zero? m) (printf "+"))
|
||||
(printf
|
||||
(match (vector-ref v (+ (* (sub1 M) M) m))
|
||||
((? has-bottom-wall?) "-+")
|
||||
((? has-fluid?) "#+")
|
||||
(else ".+")))
|
||||
(tab-eol m))
|
||||
(newline))
|
||||
|
||||
(define (find-bonded-grid-t/b-path M v)
|
||||
(define N (/ (vector-length v) M))
|
||||
|
||||
(define (flood-cell idx)
|
||||
(cond
|
||||
[(= (quotient idx M) N) #t] ; wootiments!
|
||||
[(has-fluid? (vector-ref v idx)) #f] ; been here
|
||||
[else (define cell (vector-ref v idx))
|
||||
(vector-set! v idx (bitwise-ior cell 16))
|
||||
(or (and (not (has-bottom-wall? cell)) (flood-cell (+ idx M)))
|
||||
(and (not (has-left-wall? cell)) (flood-cell (- idx 1)))
|
||||
(and (not (has-right-wall? cell)) (flood-cell (+ idx 1)))
|
||||
(and (not (has-top-wall? cell))
|
||||
(>= idx M) ; not top row
|
||||
(flood-cell (- idx M))))]))
|
||||
|
||||
(for/first ((m (in-range M))
|
||||
#:unless (has-top-wall? (vector-ref v m))
|
||||
#:when (flood-cell m)) #t))
|
||||
|
||||
(define t (make-parameter 1000))
|
||||
(define (experiment p)
|
||||
(/ (for*/sum ((sample (in-range (t)))
|
||||
(v (in-value (bonded-percol-grid 10 10 p)))
|
||||
#:when (find-bonded-grid-t/b-path 10 v)) 1)
|
||||
(t)))
|
||||
|
||||
(define (main)
|
||||
(for ((tenths (in-range 0 (add1 10))))
|
||||
(define p (/ tenths 10))
|
||||
(define e (experiment p))
|
||||
(printf "proportion of grids that percolate p=~a : ~a (~a)~%"
|
||||
p e (real->decimal-string e 5))))
|
||||
|
||||
(module+ test
|
||||
(define (make/display/flood/display-bonded-grid M N p attempts (atmpt 1))
|
||||
(define v (bonded-percol-grid M N p))
|
||||
(define v+ (vector-copy v))
|
||||
(cond [(or (find-bonded-grid-t/b-path M v+) (= attempts 0))
|
||||
(define v* (vector-copy v+))
|
||||
(define (flood-bonded-grid)
|
||||
(when (find-bonded-grid-t/b-path M v*)
|
||||
(flood-bonded-grid)))
|
||||
(flood-bonded-grid)
|
||||
(display-percol-grid M v v+ v*)
|
||||
(printf "After ~a attempt(s)~%~%" atmpt)]
|
||||
[else
|
||||
(make/display/flood/display-bonded-grid
|
||||
M N p (sub1 attempts) (add1 atmpt))]))
|
||||
|
||||
(make/display/flood/display-bonded-grid 10 10 0 20)
|
||||
(make/display/flood/display-bonded-grid 10 10 .25 20)
|
||||
(make/display/flood/display-bonded-grid 10 10 .50 20)
|
||||
(make/display/flood/display-bonded-grid 10 10 .75 20000))
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
package require Tcl 8.6
|
||||
|
||||
# Structure the bond percolation system as a class
|
||||
oo::class create BondPercolation {
|
||||
variable hwall vwall cells M N
|
||||
constructor {width height probability} {
|
||||
set M $height
|
||||
set N $width
|
||||
for {set i 0} {$i <= $height} {incr i} {
|
||||
for {set j 0;set walls {}} {$j < $width} {incr j} {
|
||||
lappend walls [expr {rand() < $probability}]
|
||||
}
|
||||
lappend hwall $walls
|
||||
}
|
||||
for {set i 0} {$i <= $height} {incr i} {
|
||||
for {set j 0;set walls {}} {$j <= $width} {incr j} {
|
||||
lappend walls [expr {$j==0 || $j==$width || rand() < $probability}]
|
||||
}
|
||||
lappend vwall $walls
|
||||
}
|
||||
set cells [lrepeat $height [lrepeat $width 0]]
|
||||
}
|
||||
|
||||
method print {{percolated ""}} {
|
||||
set nw [string length $M]
|
||||
set grid $cells
|
||||
if {$percolated ne ""} {
|
||||
lappend grid [lrepeat $N 0]
|
||||
lset grid end $percolated 1
|
||||
}
|
||||
foreach hws $hwall vws [lrange $vwall 0 end-1] r $grid {
|
||||
incr row
|
||||
puts -nonewline [string repeat " " [expr {$nw+2}]]
|
||||
foreach w $hws {
|
||||
puts -nonewline [if {$w} {subst "+-"} {subst "+ "}]
|
||||
}
|
||||
puts "+"
|
||||
puts -nonewline [format "%-*s" [expr {$nw+2}] [expr {
|
||||
$row>$M ? $percolated eq "" ? " " : ">" : "$row)"
|
||||
}]]
|
||||
foreach v $vws c $r {
|
||||
puts -nonewline [if {$v==1} {subst "|"} {subst " "}]
|
||||
puts -nonewline [if {$c==1} {subst "#"} {subst " "}]
|
||||
}
|
||||
puts ""
|
||||
}
|
||||
}
|
||||
|
||||
method percolate {} {
|
||||
try {
|
||||
for {set i 0} {$i < $N} {incr i} {
|
||||
if {![lindex $hwall 0 $i]} {
|
||||
my FloodFill $i 0
|
||||
}
|
||||
}
|
||||
return ""
|
||||
} trap PERCOLATED n {
|
||||
return $n
|
||||
}
|
||||
}
|
||||
method FloodFill {x y} {
|
||||
# fill cell
|
||||
lset cells $y $x 1
|
||||
# bottom
|
||||
if {![lindex $hwall [expr {$y+1}] $x]} {
|
||||
if {$y == $N-1} {
|
||||
# THE bottom
|
||||
throw PERCOLATED $x
|
||||
}
|
||||
if {$y < $N-1 && ![lindex $cells [expr {$y+1}] $x]} {
|
||||
my FloodFill $x [expr {$y+1}]
|
||||
}
|
||||
}
|
||||
# left
|
||||
if {![lindex $vwall $y $x] && ![lindex $cells $y [expr {$x-1}]]} {
|
||||
my FloodFill [expr {$x-1}] $y
|
||||
}
|
||||
# right
|
||||
if {![lindex $vwall $y [expr {$x+1}]] && ![lindex $cells $y [expr {$x+1}]]} {
|
||||
my FloodFill [expr {$x+1}] $y
|
||||
}
|
||||
# top
|
||||
if {$y>0 && ![lindex $hwall $y $x] && ![lindex $cells [expr {$y-1}] $x]} {
|
||||
my FloodFill $x [expr {$y-1}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Demonstrate one run
|
||||
puts "Sample percolation, 10x10 p=0.5"
|
||||
BondPercolation create bp 10 10 0.5
|
||||
bp print [bp percolate]
|
||||
bp destroy
|
||||
puts ""
|
||||
|
||||
# Collect some aggregate statistics
|
||||
apply {{} {
|
||||
puts "Percentage of tries that percolate, varying p"
|
||||
set tries 100
|
||||
for {set pint 0} {$pint <= 10} {incr pint} {
|
||||
set p [expr {$pint * 0.1}]
|
||||
set tot 0
|
||||
for {set i 0} {$i < $tries} {incr i} {
|
||||
set bp [BondPercolation new 10 10 $p]
|
||||
if {[$bp percolate] ne ""} {
|
||||
incr tot
|
||||
}
|
||||
$bp destroy
|
||||
}
|
||||
puts [format "p=%.2f: %2.1f%%" $p [expr {$tot*100./$tries}]]
|
||||
}
|
||||
}}
|
||||
Loading…
Add table
Add a link
Reference in a new issue