Random pick some elements from array in Typst?

114 views Asked by At

How to select some elements from array randomly?

 let array = ("one", "two", "three", "1", "2", "3", "4")  
 array.pick(10)
1

There are 1 answers

0
Martin On BEST ANSWER

The suiji package provides a pseudo-random number generator. With it, you can write a pick function that returns random elements from the array:

#import "@preview/suiji:0.1.0"

// This will pick the same but random items every time
#let pick(num, arr) = {
  // Generate the RNG with a random seed.
  // This could also use `datetime.today().day()` or something
  // similar to return a different number every day.
  // If consecutive invocations need to yield different values,
  // you can alternatively pass the seed as an argument.
  let rng = suiji.gen-rng(3585789)
  suiji.integers(rng, high: arr.len(), size: num)
    .at(1)
    .map(idx => arr.at(idx))
}

#let array = ("one", "two", "three", "1", "2", "3", "4") 
#pick(10, array)

Note that this function will do the following:

  • Return randomly distributed items from an array
  • Return the same picks every time for a given length

This is because there is no true source of randomness in Typst so that incremental recompilation works. You can factor out the seed argument and pass a different seed every time if you need to get different picks at each call site.