|
| 1 | +import * as t from "https://deno.land/std/testing/asserts.ts"; |
| 2 | +import { shuffle } from "../shuffle.js"; |
| 3 | +import { rnd } from "../rnd.js"; |
| 4 | + |
| 5 | +// 偏りあり |
| 6 | +const shuffle0 = (array) => { |
| 7 | + for (let i = 0; i < array.length; i++) { |
| 8 | + const n = rnd(array.length); |
| 9 | + const tmp = array[i]; |
| 10 | + array[i] = array[n]; |
| 11 | + array[n] = tmp; |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +const make = n => { |
| 16 | + const res = new Array(n); |
| 17 | + for (let i = 0; i < n; i++) res[i] = i; |
| 18 | + return res; |
| 19 | +}; |
| 20 | + |
| 21 | +/* |
| 22 | +const chk = (a) => { |
| 23 | + return a.reduce((pre, n, idx) => n == idx ? pre + 1 : pre, 0); |
| 24 | +}; |
| 25 | +
|
| 26 | +const chk1000 = (func) => { |
| 27 | + let cnt = 0; |
| 28 | + const n = 1000; |
| 29 | + for (let i = 0; i < n; i++) { |
| 30 | + const a = make(100); |
| 31 | + func(a); |
| 32 | + cnt += chk(a); |
| 33 | + } |
| 34 | + return cnt / n; |
| 35 | +}; |
| 36 | +*/ |
| 37 | + |
| 38 | +const chk2 = (test, func) => { |
| 39 | + const count = {}; |
| 40 | + const trials = 600000; |
| 41 | + const arr = [0, 1, 2]; |
| 42 | + |
| 43 | + for (let i = 0; i < trials; i++) { |
| 44 | + const a = [...arr]; |
| 45 | + func(a); |
| 46 | + const key = a.join(''); |
| 47 | + count[key] = (count[key] || 0) + 1; |
| 48 | + } |
| 49 | + |
| 50 | + console.log("output:", test); |
| 51 | + let min = 100000; |
| 52 | + let max = 0; |
| 53 | + Object.keys(count).sort().forEach(key => { |
| 54 | + const v = count[key]; |
| 55 | + if (v < min) min = v; |
| 56 | + if (v > max) max = v; |
| 57 | + console.log(`${key}: ${v}`); |
| 58 | + }); |
| 59 | + const w = max - min; |
| 60 | + console.log("width", w); |
| 61 | + return w; |
| 62 | +}; |
| 63 | + |
| 64 | +Deno.test("simple", () => { |
| 65 | + //console.log(chk1000(shuffle)); |
| 66 | + //console.log(chk1000(shuffle0)); |
| 67 | + t.assert(chk2("new", shuffle) < 2000); // 偏り少ない |
| 68 | + t.assert(chk2("old", shuffle0) > 2000); // 偏り大きい |
| 69 | +}); |
0 commit comments