DEV Community

Melisa Wong
Melisa Wong

Posted on

Same input, different output: I audited my own generator — and here's the whole app on one page

I have a generator that turns one input — your name — into a Chinese name, a past life, a guardian beast, a set of real places, and a fortune for the day. Last week I asked it a question I should have asked in month one:

If two devices, same input, same day, each run this thing, do they get the same answer?

I was confident the answer was yes. I even have a function named hashNameDate. Then I grepped my own source and wrote a 200,000-trial test against my own code, and found three places where the answer is no. What follows is what the product is (in one page, so any feedback has something to bite on), the three findings with the measurements, the twenty lines that fix them, and three questions I genuinely can't answer from the inside.

The whole thing, on one page

You type your name. You get a Chinese name drawn from real history, in one of six styles: poetic, bold, rooted in the five elements, drawn from nature, a transliteration of how your name sounds, or rustic folk. It's rendered twice — as brush calligraphy, and in seal script, the ancient script that looks close to oracle-bone carving, the kind of writing people say they'd get inked. The name then opens into a past life from one of China's dynasties, the real cities, landscapes and historic sites that life touched, a guardian beast from Chinese mythology that watches over you, and a daily fortune for the day ahead. It runs in ten languages.

That's the entire product. There is no second page. Now the part that broke.

Finding 1: .sort(() => Math.random() - 0.5) is not a shuffle

My folk-name picker, in full:

function pickFolkNames(surname, gender, count) {
  const pool = gender === 'male' ? folkMaleNames : folkFemaleNames;
  const shuffled = [...pool].sort(() => Math.random() - 0.5);
  const result = [];
  const usedChars = new Set();
  for (const name of shuffled) {
    const chars = name.split('');
    if (chars.some(c => usedChars.has(c))) continue;  // skip names that share a character
    chars.forEach(c => usedChars.add(c));
    result.push(surname + name);
    if (result.length >= count) break;
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

The comparator contract says: given a and b, return a consistent sign. Math.random() - 0.5 returns -1, 0 or 1 with probabilities 0.25 / 0.5 / 0.25, and it returns a different answer for the same pair on the next call. A sort doesn't compare every pair — it compares the ones it needs, in an order that depends on the answers it already got. So the permutation isn't uniform, and what you get depends on the engine's sort implementation and on array length.

I measured it. Six-element array, 200,000 shuffles, tallying how often each element lands in each of the six positions. Uniform would be 16.67% everywhere.

shuffle min max spread χ² (df = 25)
sort(() => Math.random() - 0.5) 5.31% 28.38% 23.07 pt 103,597
Fisher–Yates 16.55% 16.85% 0.30 pt 19.4

χ² at df = 25 is 52.6 at p = 0.001. 103,597 is not a small skew, it's a different distribution. One element is first 28.38% of the time; another, 10.79%. That's 1.7× versus 0.65× the fair rate.

Why it bites here specifically: the loop takes the first survivors of the character-dedup pass. A name pushed toward the front is a name that gets picked. So the symptom isn't "the order looks random" — it's that part of the pool is over-represented at 1.7× and part of it is starved to 0.65×, and which part depends on the engine. I ship a web build, an Android WebView and an iOS WKWebView: three engines, three biases, one product.

The fix is four lines, and the second row of the table is what it buys:

function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}
Enter fullscreen mode Exit fullscreen mode

Note what this fix does not do: it makes the shuffle uniform, not reproducible. Which is Finding 2.

Finding 2: the hash stops halfway

function hashNameDate(name, dateStr) {
  let s = name + '|' + dateStr;
  let h = 0;
  for (let i = 0; i < s.length; i++) { h = ((h << 5) - h) + s.charCodeAt(i); h |= 0; }
  return Math.abs(h);
}

function getFortuneFor(name, shakeNo = 1) {
  const h = hashNameDate(name, localDateKey());
  const r = Math.random();                    // ← the level is re-rolled right here
  let cum = 0, idx = 0;
  for (let i = 0; i < weights.length; i++) { cum += weights[i]; if (r <= cum) { idx = i; break; } }
  const f = fortunes[idx];
  const poemIdx = (h % f.poems.length + shakeNo - 1) % f.poems.length;
  return { ...f, poem: f.poems[poemIdx] };
}
Enter fullscreen mode Exit fullscreen mode

The hash exists. The function is named after it. But all it decides is which poem inside the level; the level itself comes from a fresh Math.random(). Measured: 1,000 calls with a fixed input produced 5 distinct levels out of 5 possible, and exactly 1 distinct poem index. The half I made deterministic is deterministic. The half the user reads is not.

Then there's localDateKey(), which is device wall-clock:

function localDateKey(d = new Date()) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}
Enter fullscreen mode Exit fullscreen mode

Take a single instant, 2026-11-28T23:30Z. A phone in Shanghai reads 2026-11-29 07:30. A phone in Los Angeles reads 2026-11-28 15:30. For about sixteen hours of every day, two devices disagree about what day it is — so they disagree about today's fortune, and the card one of them shared doesn't match what the other one sees.

Finding 3: ids from Date.now()

id: `name_${Date.now()}_${i}`,
Enter fullscreen mode Exit fullscreen mode

Generate the same name twice, get two different ids. Every use I have for an id breaks at once: React keys (the result card remounts and replays its entry animation), the saved list (dedupe by id stops noticing the duplicate), the share-card cache (new id, guaranteed miss), and any "have I generated this before?" check. All four are content-identity questions, and all four were being answered with a clock.

The rule I extracted

Randomness belongs to the interaction. Determinism belongs to the artifact.

Shaking for another fortune is a deliberate act with a counter. That counter goes into the seed — not into the draw. Everything else — the name, the beast, the places, the calligraphy, the poem — should come out identical on any device, in any engine, in any language, forever.

So: one seed for the whole recipe, built only from canonical inputs.

const fnv1a = (s) => {
  let h = 0x811c9dc5;
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); }
  return h >>> 0;
};

function mulberry32(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6D2B79F5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const seed = fnv1a([userId, styleId, beastId, utcDateKey(), shakeNo].join('|'));
const rnd  = mulberry32(seed);
Enter fullscreen mode Exit fullscreen mode

seededPick('melisa|folk|2026-11-28', 6) returns 1 ten times out of ten. seededShuffle(pool, 'same-input') returns the same order on both runs; a different seed returns a different order. Zero dependencies, thirty lines, and it's the whole fix.

Two details I'd hand to anyone shipping generated content in more than one language:

Hash ids, never display strings. If the seed is built from the text the user reads, the same person gets a different beast in Arabic than in English — because the strings differ. The seed has to be built from stable ids, and the display string looked up afterwards. My fortune hash happens to be keyed on the Chinese name, which is byte-identical in every locale; that accident is the only reason translation didn't quietly split my results into ten different universes.

Compute the date once, in UTC, and store it. Recomputing "today" at render time reopens Finding 2 with extra steps, and it means a user who flies to another timezone gets a different answer to a question they already asked.

And a footnote I keep re-learning: plain .sort() is stable and code-unit ordered, but localeCompare is not — it depends on the ICU version and the locale. Any sort that feeds a generator has to use a plain comparator, or your "deterministic" pipeline inherits the user's system.

What I'm actually asking

I can measure whether my generator is reproducible. I can't measure whether the thing is worth opening a second time — I wrote every word of it, so it reads fine to me, which is exactly the problem.

The app is live, one person built it, and v1.2 is not started. Three questions:

  1. If you opened this as a user, what would make you close it in the first ten seconds?
  2. Is a generated past life the reason to stay, or too much to take in at once?
  3. If this were yours, what's the one thing you'd add to v1.2 — or the one thing you'd cut?

I'm collecting answers and I'll build what makes sense. Hard answers are more useful than kind ones.

I build NameSoul, a Chinese naming app. The test harness in the tables above is about forty lines of Node with no dependencies; if you have a generator of your own, it takes a minute to point it at yours.

Top comments (0)