Welcome to the SRP Forum! Please refer to the SRP Forum FAQ post if you have any questions regarding how the forum works.

How to randomly shuffle an array

Is there a way to randomly shuffle the elements of an array?

Comments

  • DA = "ONE":@FM:"TWO":@FM:"THREE":@FM:"FOUR":@FM:"FIVE" N = DCOUNT(DA, @FM) FOR I = N TO 2 STEP -1 J = INT(RND(I)) + 1 TEMP = FIELD(DA, @FM, I) DA = FIELDSTORE(DA, @FM, I, 1, FIELD(DA, @FM, J)) DA = FIELDSTORE(DA, @FM, J, 1, TEMP) NEXT I $debug
  • How large of an array? I'm interested in both the number of elements and the length of the data in these elements.
  • edited 1:48PM
    The array length varies quite a bit, but I don't expect it to ever exceed 10K items. So it can have anywhere from 1 to 10,000 items.

    The items themselves are integers representing record IDs. The IDs are sequential, so they may be 3 digits today, but they could be 4 digits in a month.
  • If you follow Barry's pattern, which isn't bad on its own, you might consider adapting it to use a Dim array instead of a dynamic array. A dynamic array of a sufficient size (which ~10K easily exceeds this) will result in a lot of memory management when you use FieldStore. This is because dynamic arrays are just delimited strings, so a lot of shuffling is happening and memory is being reallocated for each operation. I think you'll notice performance degradation as your array size gets bigger. Use MatParse and MatUnparse to convert at the beginning and at the end of your randomizing.
  • Wow, that is fast.

    DIM DA(10000)
    DAx =''
    for x = 1 to 10000
    Dax =x
    Next x

    matparse DAx into DA
    N = DCOUNT(DAx, @FM)

    FOR I = N TO 2 STEP -1
    J = INT(RND(I)) + 1

    TEMP = DA(I)
    DA(I) = DA(J)
    DA(J) = TEMP
    NEXT I

    DAx = matunparse(DA)
Sign In or Register to comment.