MbahAgis

Fisher-Yates Shuffle Algorithm

Jul 22nd, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.78 KB | None | 0 0
  1.  '------------------------------------------- Fisher-Yates Shuffle Algorithm ------------------------------------------------
  2.  ' https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
  3.  
  4.             'Modern Variant 1
  5.             '  -- To shuffle an array a of n elements (indices 0..n-1)
  6.             'For i from n−1 downto 1 do
  7.             '  j ← random Integer such that 0 ≤ j ≤ i
  8.             ' exchange a[j] And a[i]
  9.  
  10.             '  For i = _baseArr.Count - 1 To 1 Step -1
  11.             '     Dim j As Integer = r.Next(0, i + 1)
  12.             '     Dim temp As Integer = _baseArr(i)
  13.             '     _baseArr(i) = _baseArr(j)
  14.             '     _baseArr(j) = temp
  15.             ' Next
  16. '-----------------------------------------------------------------------------------------------------------------------------
  17.             'An equivalent version which shuffles the array in the opposite direction (from lowest index to highest) Is
  18.             'Modern Variant 2
  19.             '-- To shuffle an array a of n elements (indices 0..n-1)
  20.             'For i from 0 To n−2 Do
  21.             '   j ← random Integer such that i ≤ j < n
  22.             '  exchange a[i] And a[j]
  23.  
  24.  
  25.             'generate sequence number
  26.             'ex 3x3 or _maxlimit = 9
  27.             'output _baseArr() = {1,2,3,4,5,6,7,8,0}
  28.             Dim _baseArr() As Integer = Enumerable.Range(1, _maxLimit - 1).Concat(Enumerable.Repeat(0, 1)).ToArray()
  29.  
  30.             For i = 0 To _baseArr.Count - 2
  31.                 Dim j As Integer = r.Next(i + 1, _baseArr.Count)
  32.                 Dim temp As Integer = _baseArr(j)
  33.                 _baseArr(j) = _baseArr(i)
  34.                 _baseArr(i) = temp
  35.  
  36.             Next
  37.             '-----------------------------------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment