for(i=0;i<10;i++) { console.log(i); } This code will output a sequence of 0-9.
Question. How to output this sequence (all) in a random order.
I want to see the cleanest and proper implementation
for(i=0;i<10;i++) { console.log(i); } This code will output a sequence of 0-9.
Question. How to output this sequence (all) in a random order.
I want to see the cleanest and proper implementation
Short, but unfortunately, an uneven distribution method:
let arr = []; for (let i = 0; i < 10; arr[i] = i++); arr.sort(() => Math.random() - 0.5); console.log(arr); Alternative, more correct option:
function shuffle(n) { let arr = []; for (let i = 0; i < n; arr[i] = i++); return arr.map(a => { return { val: a, rnd: Math.random() } }).sort((a, b) => a.rnd - b.rnd).map(a => a.val) } console.log(shuffle(10)); If it is clean , it is without a zhukveri and anderskor / loudash, then this is how it works correctly : =)
const range = 10; let used = {}; for (let i = 0; i < range; ++i) { let r = Math.floor(Math.random() * (range - i)); console.log((r in used) ? used[r] : r); let l = range - i - 1; used[r] = (l in used) ? used[l] : l; } With lodash will be shorter:
_.forEach(_.shuffle(_.range(0,10)), function(v) { console.log(v); }); <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script> option
"use strict" const range = 10; let used = Array(range); for (let i = 0; i < range; ++i) { let r = Math.floor(Math.random() * range); let l = used[i] !== void(0) ? used[i] : i; used[i] = used[r] !== void(0) ? used[r] : r; used[r] = l; } console.log(used); Source: https://ru.stackoverflow.com/questions/765762/
All Articles
Хочется увидеть самую чистую и правильную реализацию- and what are the criteria for purity and correctness? - Andrei NOP