Count repeated numbers in an array

1

I have an array that will randomly have between 500 and 1000 positions. And in each position a value is saved that will be between 1 and 50. To get this array I have created the following functions:

//Funcion numero aleatorio entre 1 y 50
function generaAleatorio(min,max)
{
        return Math.round(Math.random() * (max - min) + min)
}

//Funcion array de n posiciones(aleatoria) con valores entre 1 y 50 (aleatorias)

function generaNaleatorios(n,min,max)
{
   var arrayNaleatorios=new Array(n);
   var control=0;
   while(control<n)
   {
       arrayNaleatorios[control]=generaAleatorio(min,max);
       control++;
   }
   
    return arrayNaleatorios;
}

So far less well. Now I have to create another function that in position 0 of the array I have the number of repetitions of 0, in position 1 those of number 1, in position 2 the repetitions of 2 ... I mean the number of times that a same number in the array and save it in another. I do not know if I explain myself.  Any suggestions? Thanks.

    
asked by Carlos Rayón Álvarez 10.11.2017 в 03:28
source

1 answer

2

The following algorithm counts the occurrences of each number, this algorithm is well known for countSort (Ordering by accounts), which deals with:

in which the number of elements of each class is counted and then ordered. It can only be used therefore to order items that are countable

var x = [1, 2, 3, 4, 5, 6, 7, 3, 4, 4, 5, 5, 6];
var indices = new Array(8); // colocar en vez de 8 el max del array "x"
indices.fill(0);

for (var i = 0; i < indices.length; i++) {

  for (var j = 0; j < x.length; j++) {
    if (i == x[j]) {
      indices[i] = indices[i] + 1;
    }
  }
}
console.log(indices);
    
answered by 10.11.2017 / 04:24
source