jeudi 13 février 2020

Fill an array with random non-consecutive numbers

I want to create an array (indexes) that should be filled with random numbers from 0 to length - 1.

So if length = 3; then the indexes should extend from 0 to 2, for instance it could be something like: [0, 2, 1].

And there is one condition that we should follow: (God, how can I describe this in English:)

The condition: We don't accept consecutive numbers.

So we shouldn't return :

[0, 1, 2]       => Because 0 and 1 and 2 are consecutive.

[2, 0, 1]       => Because 0 and 1 are consecutive.

[2, 3, 1, 0]    => Because 2 and 3 are consecutive.

Ok, I know there may be an exception, the last element may be consecutive because we have no choice at that point!

I wrote a code but unfortunately, it crashes the browser because of high CPU usage!

Please help, my laptop and I are so much confused!

// generate number from 0 to max (max could include in the result)
function getRandom(max) {
    return Math.floor(Math.random() * (max + 1));
};

// our array to be filled with unordered numbers
let indexes = [];

// we will fill the above array with 0, 1 ,2 ,3 I mean 0 to (length - 1) 
let length = 4;

// loop through indexes so that it is filled with 4 elements
while( indexes.length <= length){

      // get a number randomally from 0 to 3
      let result = getRandom(length - 1);
       // we don't want any repeated number so..
       if(!indexes.includes(result)){     
          // finally here is our condition, we should   
          if( result !== indexes[indexes.length - 1] + 1 ){
              indexes.push(result);
          } else if(indexes.length == length){
            // push the last element to the array despite the condition
            indexes.push(result);
          }
       }

};

console.log(indexes);



Aucun commentaire:

Enregistrer un commentaire