-4

How to create the random number to assign in java script array with following condition.

  • need to create random number with (1-28).
  • Number allowed to repeat 2 times. (EX: 1,3,5,4,5). .
VinothRaja
  • 1,405
  • 10
  • 21
  • How many random numbers you need to create in array? – VenkyDhana Jun 23 '17 at 06:47
  • Have you tried anything or you just want someone to write the code for you? Just hints: Step 1: Look up how you can generate a random number in a range: https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range; Step 2: Store previously generated numbers in an array and do a check for 2 occurrences before each adding. – Samuil Petrov Jun 23 '17 at 06:48
  • I need to create 28 random numbers in array – VinothRaja Jun 23 '17 at 06:54

3 Answers3

0

Simple solution for adding a number to an array based on your criteria:

function addNumberToArray(arr){
    const minValue = 1;
    const maxValue = 28;
    if(arr.length==maxValue*2){ //no possible numbers left 
        return;
    }
    function getRandomArbitrary(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }
    function isValueInArrayLessThenTwoTimes(value, arr){
        var occurrences = 0;
        for(var i=0; i<arr.length; i++){
            if(arr[i]===value){
                occurrences++;
            }
        }
        return occurrences<2;
    }
    var newValue;
    do {
        newValue = getRandomArbitrary(minValue,maxValue);
    } while(!isValueInArrayLessThenTwoTimes(newValue, arr));
    arr.push(newValue);
}
Paweł Janik
  • 121
  • 1
  • 6
0
var array = [];

for (var i = 0; i < 28; i++) {
    var randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
    while (getCount(array, randomNumberBetween1and28) > 2) {
        randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
    }
    array.push(randomNumberBetween1and28);
}

function getCount(arr, value) {
    var count = 1;
    for (var i = 0; i < arr.length; i++) {
        if (value == arr[i]) count++;
    }
    return count;
}
VenkyDhana
  • 905
  • 5
  • 16
  • It's fine. But it's allowed repeated values in more than 2 time. (EX:6,11,7,6,22,19,25,1,3,13,19,26,27,18,7,24,6,25,5,23,27,24,2,1,2,2,23,17). This Example "6" has been return in three times but i need only two times. – VinothRaja Jun 23 '17 at 07:22
  • @R.vinoth I have modified. Can you try now? – VenkyDhana Jun 23 '17 at 07:32
  • @R.vinoth Mark this as answer. SO this will helpful for future reference – VenkyDhana Jun 23 '17 at 08:44
0

A shorter and faster solution:

min=1;
max=28;
nums= new Array();
for(i=1;nums.length<28;i++){
  a = Math.round(Math.random()*(max-min+1)+min);
  if(nums.indexOf(a)==-1 || nums.indexOf(a)==nums.length-nums.reverse().indexOf(a)-1){
    if(nums.indexOf(a)>-1){
      nums.reverse();
    }
    nums.push(a);
  }
}
console.log(nums);

https://jsfiddle.net/znge41fn/1/

zuluk
  • 1,557
  • 8
  • 29
  • 49