Flow Cadence: How to generate a random integer between two integer?

125 Views Asked by At

I tried unsafeRandom and this custom smart-contract without success: https://github.com/justjoolz/PRNG/blob/master/cadence/contracts/PRNG.cdc

1

There are 1 best solutions below

0
On

As mentioned by @j00lz, you can create a random between two integers (more specifically UInt256 types) by using the PRNG contract found here.

Essentially, you create a Generator resource based on a seed (or block height + integer), and call functions on that generator.

Here is a helpful example of how to use it (try it out here):

import PRNG from 0x93615d25d14fa337

pub fun main(min: UInt256, max: UInt256): UInt256 {
  // create the generator resource
  let generator <- PRNG.createFrom(blockHeight: getCurrentBlock().height, uuid: 100)

  // call the range function to give you an integer between min and max
  let answer: UInt256 = generator.range(min, max)

  // destroy the generator resource
  destroy generator

  // return your answer
  return answer
}