Jump to content

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


iwato

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

Link to comment
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
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...