Randomizer function NodeJS - best practise (I am looking to use for some gamification)

Randomize all the items in a collection is a function in the backend.

Before I go down the wrong rabbit hole - I’d like to understand the best practise approach to using this function.

I have two use cases I’d like to use this (or other to solve).

Determine a specific ‘value’ from a list of values. E.g.
Rank one, would have values 0 to 100.
Rank two would have values 101 to 200.
So first we determine is this user rank one, or two and then we determine what value they get from each range.

Theory - we query values 0 to 100, randomize and set value on array item [0].

We want to randomly award a prize.

First we want to determine if this action (API Call receive blockchain data) should win a ‘box’ that may contain a prize.

Ideally we can randomly pick a number from a range, and then have a condition that if that number == X then it’s a winner. If there are any better ideas here…

Second we want to determine if once opened, this box delivers a prize. There would be 6 items in the box, 2 would be no win, the other 4 would be ‘win’. So we want to randomize and return one value to confirm if / what the user has won.

Theory here - we could query the box prizes, and randomize and again just always pick entry [0]. But if there are better ways…

Thank you in advance for any help!

Is money involved? If yes, you need a cryptographically secure pseudorandom number generator (CSPRNG) function, don’t blindly assume Wappler’s built-in randomizer is cryptographically secure

Generate an integer between 0 and 100 called “randomInt”, select the array item [randomInt]

In this case, Probability = 1 / length of range

  1. You throw a dice (generate random int from 0 to 5)
  2. You check the upward face (array[randomInt])

Probability = 4 / 6 = 0.66 = 66%

My core answer consists on using a random integer generator and selecting the result(s) from the array, instead of randomizing the array and selecting the 1st element. Your solutions are equally valid, but if CSPRNG is a requirement then you’re probably better finding a way to generate cryptographically safe random integers instead of randomizing the array

Thank you Apple this level of detail is really appreciated. We don’t need crypto-secure but I’m going to look into that regardless for additional security.

Re: random integer generator - this sounds ideal and a simpler way to achieve the desired output, have I missed this in Wapplers existing functionality? If not I’ll dig around for a solution I can include. Thank you!

I’m not sure if Wappler has an integer generator, I think not. If you’re using the NodeJS target you can use the RunJS Wappler extension and use simple code to generate the numbers:

If you’re using PHP you might be able to come up with something similar :slight_smile:

1 Like