Why is my random shuffle always producing the same result when using Suiji?

I remember reading recently in an answer on the forum that using both get() and update() on a state in one context is not ideal. I tried searching for the post that I am vaguely remembering but didn’t find it.

I see in the state page of the documents that update() can be given a function that:

receives the previous state and has to return the new state.

After some trial-and-error I ended up with the following. It stores the most recent ordering of options in the state with rng (as an array).

#import "@preview/suiji:0.4.0": *

#let options = ("A", "B", "C", "D")
#let rng-and-options = state("rng", (gen-rng(1), options))

#let randomize(rng-and-options-local) = context {
  rng-and-options-local.update((current) => {
    let (rng-cur, options-cur) = current
    let (rng-new, options-new) = shuffle(rng-cur, options-cur)
  
    let new-state = (rng-new, options-new)
    return new-state
  })
  rng-and-options-local.get().at(1).join(", ")
}

#for _ in range(10) [
  #randomize(rng-and-options)
  #linebreak()
]

Because the state is a parameter of the function, you can create a second set of options (and state):

#let options2 = ("A", "B", "C", "D", "E")
#let rng-and-options2 = state("rng", (gen-rng(1), options2))

And call the randomize() function with either of the states.

1 Like