When I want to get a unique random sequence ...
R
print(sample(1:10, 10))
Python
import random
l = list(range(1, 10 + 1))
print(random.sample(l, 10))
JavaScript
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomArray(min, max) {
let result = [];
for (i = min; i <= max; i++) {
while (true) {
let v = getRandomInt(min, max);
if (!result.includes(v)) {
result.push(v);
break;
}
}
}
return result;
}
console.log(getRandomArray(1, 10));
Top comments (8)
While I get that this is a joke, that
getRandomArray
-function is a bit verbose. This does the same thing:Edit: unique list:
Not really, since the intent of the original implementation is to generate a sequence of unique elements, and your implementation can yield duplicated values.
A better approach would be to just generate the sequence in order and shuffle it:
The
data.sort
trick doesn't produce a lot of variations, though. A better way is to generate the sorted array and pick elements from a random index and add them to a new array.At this point the implementation is equally verbose to the original, so ¯\_(ツ)_/¯. But it avoids unnecessary iterations when duplicated values are generated.
Nice catch, thanks! Didn't realise that the list had to be unique. Could you explain what you mean by
.sort()
not producing a lot of variations?[].sort(() => Math.random() - 0.5)
tends to not displace elements in the array a lot. An element might be moved a few positions forward or backward, but it will generally stay close to its original position. Therefore, when used to shuffle an array, the result will be more similar to the original array than with other algorithms.As an example, here's the output of three runs with
randSeq
and three runs withrandSeq2
:You can notice that with the
randSeq
the array is less shuffled than withrandSeq2
and the elements show a clear tendency to be larger the further back they are in the array.Makes sense. Thanks!
That's a weird reason for liking and not liking a language. 🤦♂️😂
That R implementation is too verbose as well, just
sample(10)
will do! 😛Import lodash and use their sample...
It gets pretty much as short as the python version