Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
46
Task/Knuth-shuffle/JavaScript/knuth-shuffle-2.js
Normal file
46
Task/Knuth-shuffle/JavaScript/knuth-shuffle-2.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
(() => {
|
||||
|
||||
// knuthShuffle :: [a] -> [a]
|
||||
const knuthShuffle = xs =>
|
||||
enumFromTo(0, xs.length - 1)
|
||||
.reduceRight((a, i) => {
|
||||
const
|
||||
iRand = randomRInt(0, i),
|
||||
tmp = a[iRand];
|
||||
return iRand !== i ? (
|
||||
a[iRand] = a[i],
|
||||
a[i] = tmp,
|
||||
a
|
||||
) : a;
|
||||
}, xs);
|
||||
|
||||
const test = () => knuthShuffle(
|
||||
(`alpha beta gamma delta epsilon zeta
|
||||
eta theta iota kappa lambda mu`)
|
||||
.split(/\s+/)
|
||||
);
|
||||
|
||||
// GENERIC FUNCTIONS ----------------------------------
|
||||
|
||||
// enumFromTo :: Int -> Int -> [Int]
|
||||
const enumFromTo = (m, n) =>
|
||||
n >= m ? (
|
||||
iterateUntil(x => x >= n, x => 1 + x, m)
|
||||
) : [];
|
||||
|
||||
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
|
||||
const iterateUntil = (p, f, x) => {
|
||||
let vs = [x],
|
||||
h = x;
|
||||
while (!p(h))(h = f(h), vs.push(h));
|
||||
return vs;
|
||||
};
|
||||
|
||||
// randomRInt :: Int -> Int -> Int
|
||||
const randomRInt = (low, high) =>
|
||||
low + Math.floor(
|
||||
(Math.random() * ((high - low) + 1))
|
||||
);
|
||||
|
||||
return test();
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue