Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior with random array generation [duplicate]

I was trying to generate an array of random numbers between 10 and 1000 in descending ordered.

This is the code I wrote:

function GenerateRandomArray(){
  var array = [];

  for (var i = 0; i < 10; i++) {
    array[i] = Math.round(Math.random() * (1000 - 10 + 1) + 10);
  }
  return array.sort().reverse();
}

When run in the terminal, here are the results I get:

new GenerateRandomArray() => [ 924, 804, 79, 788, 585, 451, 267, 217, 153, 135 ]

new GenerateRandomArray() => [ 869, 697, 647, 59, 458, 30, 291, 157, 112, 111 ]

new GenerateRandomArray() => [ 999, 98, 872, 823, 705, 418, 404, 306, 259, 20 ]

new GenerateRandomArray() => [ 688, 666, 664, 615, 580, 565, 336, 304, 250, 246 ]

new GenerateRandomArray() => [ 912, 906, 759, 690, 673, 481, 429, 355, 19, 103 ]

Why some arrays are in the right format and some others have a non ordered number in the middle of it ?

I tested:

  • converting numbers to strings
  • accessing the unordered element in the array (it gives the same number - obviously)
  • doing it with a function instead of a constructor

This doesn't change the weird result.

Am I missing something like a JS coercive property or something ?

Thanks :)

like image 655
Stan Amsellem Avatar asked Apr 20 '16 13:04

Stan Amsellem


2 Answers

By default the sort function sorts in alphanumeric/alphabetical order (i.e., "string sort"). As strings go, "aaa" comes before "b", and similarly "111" comes before "2".

To instead sort by numeric value, you can provide your own compare function.

array.sort(function(a, b) { 
    return a - b;
});
like image 167
Thomas Avatar answered Oct 06 '22 00:10

Thomas


function GenerateRandomArray(){
  var arr = [];

  for (var i = 0; i < 10; i++) {
    arr.push(Math.round(Math.random() * 1000));
  }
  arr.sort(function compareNumbers(a, b) {
    return a - b;
  });
  return arr;
}
like image 28
Hamik Hambardzumyan Avatar answered Oct 05 '22 23:10

Hamik Hambardzumyan