Jump to content
iwato

Randomly Select a Pre-determined Number of Elments of an Array without Duplication

Recommended Posts

CONCERN:  The following function does what it is suppose to do -- namely, select at random and without duplication a given number of elements from an array of elements.  However, I fear that it is hopelessly awkward and would like your professional assessment of its construction.  You will likely not find another like it on the internet, but parts of it were obtained therefrom.

function selectCubes(gates) {
    function onlyUnique(value, index, self) { 
        return self.indexOf(value) === index;
    }
    var cubes = ['cube_one', 'cube_two', 'cube_three', 'cube_four', 'cube_five', 'cube_six', 'cube_seven'];
    var selectedCubes = [];
    var filteredCubes = [];
    var n = 0;
    while (n < gates) {
        selectedCube = cubes[Math.floor(Math.random()*cubes.length)];
        selectedCubes.push(selectedCube);
        if (filteredCubes.length < gates) {
            var filteredCubes = selectedCubes.filter(onlyUnique);
            n++;
        }
    }
    return filteredCubes;
}
console.log('selectCubes(3):' + selectCubes(3));

Please comment and have a great weekend!

Roddy

Share this post


Link to post
Share on other sites

You could replace that filter function with Array.splice.  Generate the random number, use splice to remove and return the removed element, and then push the element onto the other array.

function selectCubes(gates) {
    var cubes = ['cube_one', 'cube_two', 'cube_three', 'cube_four', 'cube_five', 'cube_six', 'cube_seven'];
    var selectedCubes = [];
    while (selectedCubes.length < gates) {
        selectedCubes.push(cubes.splice(Math.floor(Math.random()*cubes.length), 1)[0]);
    }
    return selectedCubes;
}

 

  • Thanks 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...