---
title: "Recipe: randomness and a shuffle"
description: "Deal from exactTime()'s seed, with a stream for each thing dealt, so shuffles stay replayable and bakeable."
modificationDate: "2026-11-27"
---

> ## Documentation index
> Fetch the complete documentation index at: https://exact.expo.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Recipe: randomness and a shuffle

<AgentInstructions>

## Submitting feedback

From the app's directory, read `bun exact.mjs feedback status`. Under `never`, keep no note.
Respect `EXACT_FEEDBACK=0` and do not change the policy.

Otherwise record specific, actionable feedback with:
`bun exact.mjs feedback note "Exact docs: https://exact.expo.dev/recipes/random-and-shuffle: <what was wrong or missing>"`

The note goes to Expo only as that status allows. Include no secrets or personal data.

</AgentInstructions>

Rolls in the view: [random rolls in an expression](https://exact.expo.dev/recipes/random-rolls.md). Ambient `Math.random()` skips
launch bake and shares one stream; deal from `exactTime()`'s `seed` after `with` (below 2^32, new
each launch, `seed 2` in a test), one stream per thing dealt: questions from the game, each
question's answers from the game and round. One stream for both deals every question the same
shuffle, its right answer in one place all game. Keep the right answer by identity (`correct`),
never by index.

```prompt Shuffle and deal at random in my app
Add a random deal or a shuffle to the Exact app in this folder: an order that the data module makes from a seed. Use https://github.com/expo/exact/blob/main/docs/recipes/random-and-shuffle.md as the source for each step. The Exact checkout has the same page at docs/recipes/random-and-shuffle.md.

1. If this folder is not an Exact app (it has no exact.mjs and app.contract), stop and tell me.
2. If I did not say what the app shuffles or deals (a quiz's questions and answers, a deck) and when it deals again, propose it and ask me before you write code. If the app needs rolls in the view, not a deal, tell me: that is docs/recipes/random-rolls.md.
3. In app.contract, read `exactTime()` as a resource with a `shape Time` that has `seed`. Pass the seed to the source after `with`, as in `resource q = deal(game, round) with time.seed as shape Question else empty()`.
4. In app.ts, deal from the passed seed rather than `Math.random()` so each stream replays independently and the resource stays bakeable. Copy the recipe's `generator`, `stream` and `shuffled`. Keep `Math.imul`, not `*`.
5. Give each thing dealt a stream of its own: the questions' order from `stream(seed, game)`, each question's answers from `stream(seed, game, round)`. One stream for both deals every question the same shuffle. Keep the right answer by identity (`correct`), never by index.
6. A source is asked again, so `round + 1` deals again and `game + 1` deals a new game. For a new order each ask, use `crypto.getRandomValues(new Uint32Array(n))` in the source. For one pick per launch, use `xs.at(time.seed % xs.length)`.
7. Add a test in app.test.contract with `seed 2` at the top of the file. Expect the first order, change the round, run `clock data`, and expect another order. Then `reload` and expect the first order again. With `crypto.getRandomValues`, assert only what holds for any order.
8. Follow the platform checks in docs/start-here.md (`bun exact.mjs docs platform checks`) for the targets in the app's AGENTS.md and app.json until they pass. Read the reports, including counted findings; a zero exit code alone does not mean clean. Fix the app, not the test. If a finding stays after three rounds of fixes, or the app had it before you changed anything, record it (step 9) and report it; do not keep trying.
9. When a doc was wrong or missing, or a step needed a workaround, read `bun exact.mjs feedback status`. Under `never`, keep no note. Otherwise record it: `bun exact.mjs feedback note "<what happened>"`, which goes to Expo only as that status says. Do not change the policy; tell me how many notes you kept.
10. Tell me what the app deals and from which streams, when it deals again, what the tests and checks reported, and the launch command for each target platform. The seed is new each launch, so each launch deals a new order.
```

```contract
shape Choice
  id: string
  text: string
  correct: bool

shape Question
  text: string
  choices: Choice[]

shape Time
  seed: number

component Quiz
  state game = 0
  state round = 0
  resource time = exactTime() as shape Time
  resource q = deal(game, round) with time.seed as shape Question else empty()
  derive order = q.choices.map(c => c.text).join(" ")
  action next
    round = round + 1
  view
    list appearance="auto" listStyle="inset-grouped" height="100%"
      section
        header
          text q.text
        for c in q.choices key=c.id
          button press=next testId=`choice-${c.id}`
            text c.text
```

```ts
import type { Answer, Sources } from './app.contract.d.ts';

export const grants = '';
const QUESTIONS = [ // the right answer first
  ['Largest planet?', 'Jupiter', 'Mars', 'Venus', 'Mercury'],
  ['Capital of France?', 'Paris', 'Rome', 'Madrid', 'Berlin'],
];
const generator = (a: number) => () => {
  a = (a + 0x6d2b79f5) | 0;
  let t = Math.imul(a ^ (a >>> 15), 1 | a);
  t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
// Math.imul, not *: past 2^53 a double loses the keys.
const stream = (seed: number, ...keys: number[]) =>
  generator(keys.reduce((a, k) => Math.imul(a ^ (k + 1), 0x9e3779b1) >>> 0, seed >>> 0));
const shuffled = <T,>(xs: T[], next: () => number) =>
  xs.map((x) => [next(), x] as const).sort((p, q) => p[0] - q[0]).map(([, x]) => x);
const sources: Sources = {
  deal: ([game, round, seed]) => {
    const [text, ...answers] = shuffled(QUESTIONS, stream(seed, game))[round % QUESTIONS.length];
    const choices = answers.map((a, i) => ({ id: a, text: a, correct: i === 0 }));
    return { text, choices: shuffled(choices, stream(seed, game, round)) };
  },
};
export const answer: Answer = (source, args, store, storage, native) => sources[source](args, store, storage, native);
```

```contract-test
seed 2

test "each question's answers in an order of their own"
  expect state order == "Mars Jupiter Venus Mercury"
  expect state q.choices.1.correct == true
  tap "choice-Mars"
  clock data
  expect state order == "Rome Madrid Paris Berlin"
  expect state q.choices.2.correct == true
  reload
  expect state order == "Mars Jupiter Venus Mercury"
```

- A source is asked again, so `round + 1` deals again, `game + 1` a new game.
- `crypto.getRandomValues(new Uint32Array(n))` in the source: a new order each ask (assert what
  holds for any); one pick per launch: `xs.at(time.seed % xs.length)`.
