RosettaCodeData/Task/Percolation-Bond-percolation/FreeBASIC/percolation-bond-percolation.basic
2025-02-27 18:35:13 -05:00

98 lines
2.3 KiB
Text

Randomize Timer
Const RAND_MAX = 32767
Const FILL = 1
Const RWALL = 2
Const BWALL = 4
Dim Shared As Integer x = 10, y = 10
Dim Shared As Integer grid(x * (y + 2))
Dim Shared As Integer m, n
Dim Shared As Integer cells, endPos
Sub makeGrid(p As Double)
Dim As Integer i, j, thresh, r1, r2, r3
thresh = Int(p * RAND_MAX)
m = x
n = y
For i = 0 To Ubound(grid) : grid(i) = 0 : Next
For i = 0 To m-1: grid(i) = BWALL Or RWALL : Next
cells = m
endPos = m
For i = 0 To y-1
For j = x-1 To 1 Step -1
r1 = Int(Rnd * (RAND_MAX + 1))
r2 = Int(Rnd * (RAND_MAX + 1))
grid(endPos) = Iif(r1 < thresh, BWALL, 0) Or Iif(r2 < thresh, RWALL, 0)
endPos += 1
Next
r3 = Int(Rnd * (RAND_MAX + 1))
grid(endPos) = RWALL Or Iif(r3 < thresh, BWALL, 0)
endPos += 1
Next
End Sub
Sub showGrid()
Dim As Integer i, j
For j = 0 To m-1
Print "+--";
Next
Print "+"
For i = 0 To n
Print Iif(i = n, " ", "|");
For j = 0 To m-1
Print Iif((grid(i * m + j + cells) And FILL) <> 0, "[]", " ");
Print Iif((grid(i * m + j + cells) And RWALL) <> 0, "|", " ");
Next
Print
If i = n Then Exit Sub
For j = 0 To m-1
Print Iif((grid(i * m + j + cells) And BWALL) <> 0, "+--", "+ ");
Next
Print "+"
Next
End Sub
Function filled(p As Integer) As Boolean
If (grid(p) And FILL) <> 0 Then Return False
grid(p) = grid(p) Or FILL
If p >= endPos Then Return True
Return ((grid(p + 0) And BWALL) = 0 Andalso filled(p + m)) Orelse _
((grid(p + 0) And RWALL) = 0 Andalso filled(p + 1)) Orelse _
((grid(p - 1) And RWALL) = 0 Andalso filled(p - 1)) Orelse _
((grid(p - m) And BWALL) = 0 Andalso filled(p - m))
End Function
Function percolate() As Boolean
Dim i As Integer = 0
While i < m Andalso Not filled(cells + i)
i += 1
Wend
Return i < m
End Function
' Main program
makeGrid(0.5)
percolate()
showGrid()
Print !"\nRunning " & x & " x " & y & " grids 10,000 times for each p:"
For p As Integer = 1 To 9
Dim As Integer cnt = 0
Dim As Double pp = p / 10
For i As Integer = 0 To 9999
makeGrid(pp)
If percolate() Then cnt += 1
Next
Print Using "p = #.# : #.####"; pp; cnt / 10000
Next
Sleep