Please write code in JavaScript that shuffles an array in a deterministic way using…
- User
Please write code in JavaScript that shuffles an array in a deterministic way using xorshift32 as the RNG.
Assistant
js/** * Deterministic Fisher–Yates shuffle powered by xorshift32. * @param {Array} arr The array to shuffle (copied, original untouched). * @param {number} seed 32-bit unsigned integer seed. * @returns {Array} New shuffled array. */ function shuffleWithXorShift32(arr, seed) { if (!Number.isInteger(seed) || seed < 0 || seed > 0xFFFFFFFF) throw new RangeError('seed must be a 32-bit unsigned integer'); const out = arr.slice(); // don’t mutate caller’s array let x = seed >>> 0; // xorshift32 state // xorshift32 generator const rng = () => { x ^= x << 13; x ^= x >>> 17; x ^= x << 5; return x >>> 0; // 32-bit unsigned value }; // Fisher–Yates shuffle for (let i = out.length - 1; i > 0; --i) { // uniform index in [0, i] const j = rng() % (i + 1); [out[i], out[j]] = [out[j], out[i]]; } return out; } /* ---------- demo ---------- */ const data = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; console.log(shuffleWithXorShift32(data, 123456789)); // deterministic console.log(shuffleWithXorShift32(data, 123456789)); // identical again- User
Let's do this again but instead of the Fisher-Yates algorithm, implement the shuffling by associating a randomly generated number with each element, and rearrange the elements by sorting the randomly generated numbers.
Assistant
js/** * Deterministic shuffle by sorting keys produced with xorshift32. * @param {Array} arr The array to shuffle (copied, original untouched). * @param {number} seed 32-bit unsigned integer seed. * @returns {Array} New shuffled array. */ function shuffleBySortingWithXorShift32(arr, seed) { if (!Number.isInteger(seed) || seed < 0 || seed > 0xFFFFFFFF) throw new RangeError('seed must be a 32-bit unsigned integer'); let x = seed >>> 0; // xorshift32 state // xorshift32 generator const rng = () => { x ^= x << 13; x ^= x >>> 17; x ^= x << 5; return x >>> 0; }; // pair each element with a deterministic random key const keyed = arr.map(el => ({ el, key: rng() })); // sort by the random keys keyed.sort((a, b) => a.key - b.key); // extract the re-ordered elements return keyed.map(pair => pair.el); } /* ---------- demo ---------- */ const data = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; console.log(shuffleBySortingWithXorShift32(data, 987654321)); console.log(shuffleBySortingWithXorShift32(data, 987654321)); // identical
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.