-1
$rowCount = 40 ; 
for (var $j = 0; $j < $rowCount -1; $j++) {
    var currentNum = #something
}

I need to have a mechanism, where I can loop in a way that I will be applying the values to the currentNum in a random way.

Eg: At the end of the loop, the currentNum should have the value (0....39). But it shouldn't be applied starting from 0,1,2,3,4,5,6,7,8,.....39.

It should be applied in a random way like 39, 4, 5,17, 28 , 16 .... and it should cover all the numbers from 0-40. I figured this can be achieved using a HashMap in java, but how to implement in javascript?

beresfordt
  • 5,088
  • 10
  • 35
  • 43
Ciba Zag
  • 15
  • 2

2 Answers2

0
var numbers = Array(rowCount);
for(var i = 0; i < rowCount; i++) numbers[i] = i;

shuffle(numbers); // randomly shuffle array elements

for (var $j = 0; $j < $rowCount -1; $j++) {
    var currentNum = numbers[i];
}
Simon
  • 6,293
  • 2
  • 28
  • 34
0

You can try something like this:

var _data = [];
for (var i = 0; i < 40; i++) {
  _data.push(i);
}

var result = [];

_data.slice().forEach(function(){
 result.push(getRandomValue(_data))
});

function getRandomValue(arr,i) {
  var r = Math.floor(Math.random() * arr.length);
  var result = arr[r];
  arr.splice(r, 1);
  return result;
}

document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");
Rajesh
  • 24,354
  • 5
  • 48
  • 79