Generate random numbers without repeating a value: Difference between revisions
Content added Content deleted
(Added Algol 68) |
(→{{header|JavaScript}}: Added a version in JavaScript) |
||
Line 479: | Line 479: | ||
[19, 15, 10, 6, 17, 13, 14, 9, 2, 20, 3, 18, 8, 16, 7, 12, 1, 4, 5, 11] |
[19, 15, 10, 6, 17, 13, 14, 9, 2, 20, 3, 18, 8, 16, 7, 12, 1, 4, 5, 11] |
||
</pre> |
</pre> |
||
=={{header|JavaScript}}== |
|||
<lang javascript>(() => { |
|||
"use strict"; |
|||
// ---------- NON-REPEATING RANDOM NUMBERS ----------- |
|||
// main :: IO () |
|||
const main = () => |
|||
sortOn(Math.random)( |
|||
enumFromTo(1)(20) |
|||
); |
|||
// --------------------- GENERIC --------------------- |
|||
// comparing :: (a -> b) -> (a -> a -> Ordering) |
|||
const comparing = f => |
|||
// The ordering of f(x) and f(y) as a value |
|||
// drawn from {-1, 0, 1}, representing {LT, EQ, GT}. |
|||
x => y => { |
|||
const |
|||
a = f(x), |
|||
b = f(y); |
|||
return a < b ? -1 : (a > b ? 1 : 0); |
|||
}; |
|||
// enumFromTo :: Int -> Int -> [Int] |
|||
const enumFromTo = m => |
|||
n => Array.from({ |
|||
length: 1 + n - m |
|||
}, (_, i) => m + i); |
|||
// sortBy :: (a -> a -> Ordering) -> [a] -> [a] |
|||
const sortBy = f => |
|||
// A copy of xs sorted by the comparator function f. |
|||
xs => xs.slice() |
|||
.sort((a, b) => f(a)(b)); |
|||
// sortOn :: Ord b => (a -> b) -> [a] -> [a] |
|||
const sortOn = f => |
|||
// Equivalent to sortBy(comparing(f)), but with f(x) |
|||
// evaluated only once for each x in xs. |
|||
// ('Schwartzian' decorate-sort-undecorate). |
|||
xs => sortBy( |
|||
comparing(x => x[0]) |
|||
)( |
|||
xs.map(x => [f(x), x]) |
|||
) |
|||
.map(x => x[1]); |
|||
// MAIN --- |
|||
return JSON.stringify(main()); |
|||
})();</lang> |
|||
{{Out}} |
|||
For example: |
|||
<pre>[6,9,8,16,5,15,19,7,13,12,4,20,1,2,18,11,14,17,10,3]</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |