0

I'm using a very old version of VBA that can't return arrays.

I copied most of this from another post and modified it.

x = Array(679, 680, 683, 781, 790, 792, 800, 801, 809, 818, 822, 871, 897, 911, 913, 924, 927, 929, 930, 934, 936, 946, 951, 952, 956, 970, 971)

Dim i As Long
For i = UBound(x) To LBound(x) Step -1
    Dim t As Variant
    t = x(i)
    Dim j As Long
    j = CLng((25 - 0 + 1) * Rnd + 0)
    x(i) = x(j)
    x(j) = t
Next i

When I loop through the outcome and the old array it never overlaps numbers.

The J = CLng((Max - min + 1) * Rnd + Min) but I just moved it the way I had it.

Why does the randomness never overlap to create duplication? I looped the outcomes over 100k times.

5
  • I'm happy it works great but I have no clue why it works LOL Commented Jan 25, 2023 at 23:42
  • 1
    The function you provided is using a technique called Fisher-Yates shuffle algorithm. It is a way to randomly shuffle the elements of an array. The idea behind the algorithm is to iterate through the array backwards, and for each element, swap it with a randomly chosen element that comes after it. This way, each element in the array will have an equal probability of being in any position. Commented Jan 25, 2023 at 23:43
  • So no matter how many numbers are used in the array it'll never overlap? If I had a list of a million numbers they would always be shuffled perfectly? What kind of sorcery is this? LOL Commented Jan 25, 2023 at 23:54
  • Let me add an answer for a any number or items, your code is hardcoded to 27 items Commented Jan 25, 2023 at 23:59
  • Is this actually more like Durstenfeld's version? Since it looks like the array position is switched with the random number generator number. OOOOO I see now. This is really cool. Commented Jan 26, 2023 at 0:01

1 Answer 1

1

Notice the line I change to dynamically increase the chosen subindex according to array size.

Dim i As Long
For i = UBound(x) To LBound(x) Step -1
    Dim t As Variant
    t = x(i)
    Dim j As Long
    j = CLng(LBound(x) * Rnd )
    x(i) = x(j)
    x(j) = t
Next i
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.