Shuffling an array randomly

I have an array of CDTs say questions with question structured as:

{

id: 1,

statement: "Text string of question",

options: {List of Options}

}

Like multiple values like the above.

I would like to shuffle this array of questions randomly so that every time I print this array the questions are in no particular order and are different from last time. Example if I pick the array first time it had an order:

1, 4, 2, 5, 3

But next time I pick same array it should be ordered randomly like:

3, 5, 1, 4, 2

Also is there any possible way to implement Rand() ordering in the query like we do in SQL?

  Discussion posts and replies are publicly visible

Parents Reply Children
  • 0
    Certified Lead Developer
    in reply to normanc

    I like it - though it should be noted that this could occasionally (probably very rarely) return only 4 results if none of the 50 "coin flips" come up for one of the 5 numbers.  I assume if you push the "random array length" value high enough you'll eventually get zero failures, though i'm not sure what that'll do to the efficiency of the rule.

    I just tested and this happened 3 out of 10,000 times (though on some other runs of the same code it happened 0 times):

    a!flatten(
      a!forEach(
        enumerate(10000), /* number of times to test */
      
        a!localVariables(
          local!length: 5,
          local!array: floor(rand(local!length*10) * local!length) + 1,
          if(
            length(union(local!array, local!array)) < local!length,
            "flag",
            {}
          )
        )
      )
    )