RosettaCodeData/Task/Knuths-algorithm-S/FreeBASIC/knuths-algorithm-s.basic

99 lines
2.3 KiB
Plaintext

Type SampleState
sample(0 To 99) As Integer ' Array to store the sample (arbitrary maximum size)
sampleSize As Integer ' Current sample size
i As Integer ' Counter of processed elements
n As Integer ' Desired sample size
End Type
' Function to generate a random number between 0 and max-1
Function randInt(Byval max As Integer) As Integer
Return Int(Rnd() * max)
End Function
' Function to create a new sampler
Function createSampler(Byval n As Integer) As SampleState
Dim sampler As SampleState
sampler.sampleSize = 0
sampler.i = 0
sampler.n = n
Return sampler
End Function
' Function to process a new element and update the sample
Function sampleOfN(Byref sampler As SampleState, Byval item As Integer) As Integer Ptr
sampler.i += 1
If sampler.i <= sampler.n Then
sampler.sample(sampler.sampleSize) = item
sampler.sampleSize += 1
Else
If randInt(sampler.i) < sampler.n Then
sampler.sample(randInt(sampler.n)) = item
End If
End If
Return @sampler.sample(0)
End Function
Sub printArray(arr() As Integer, Byval size As Integer)
Print "["
For i As Integer = 0 To size-1
Print arr(i)
If i < size-1 Then Print ", "
Next
Print "]"
End Sub
Sub main()
Dim As Integer i, j
Dim As Integer frequency(0 To 9)
For i = 0 To 9
frequency(i) = 0
Next
Print "Single run samples for n = 3:"
Dim As SampleState sampler = createSampler(3)
Dim As Integer Ptr samplePtr
Dim As Integer sample(0 To 2)
For i = 0 To 9
samplePtr = sampleOfN(sampler, i)
For j = 0 To sampler.sampleSize-1
sample(j) = samplePtr[j]
Next
Print " Item: " & i & " -> sample: ";
Print "[ ";
For j = 0 To sampler.sampleSize-1
Print Chr(8) & sample(j);
If j < sampler.sampleSize-1 Then Print ", ";
Next
Print "]"
Next
For i = 0 To 99999
sampler = createSampler(3)
For j = 0 To 9
samplePtr = sampleOfN(sampler, j)
Next
For j = 0 To sampler.n-1
frequency(samplePtr[j]) += 1
Next
Next
Print !"\nTest item frequencies for 100000 runs:"
For i = 0 To 9
Print " " & i & ": " & frequency(i)
Next
End Sub
Randomize Timer
main()
Sleep