Create an array with random values

JavascriptArraysRandom

Javascript Problem Overview


How can I create an array with 40 elements, with random values from 0 to 39 ? Like

[4, 23, 7, 39, 19, 0, 9, 14, ...]

I tried using solutions from here:

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

but the array I get is very little randomized. It generates a lot of blocks of successive numbers...

Javascript Solutions


Solution 1 - Javascript

The shortest approach (ES6):

// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));

Solution 2 - Javascript

Here's a solution that shuffles a list of unique numbers (no repeats, ever).

for (var a=[],i=0;i<40;++i) a[i]=i;

// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}

a = shuffle(a);

If you want to allow repeated values (which is not what the OP wanted) then look elsewhere. :)

Solution 3 - Javascript

ES5:

function randomArray(length, max) {
    return Array.apply(null, Array(length)).map(function() {
        return Math.round(Math.random() * max);
    });
}

ES6:

randomArray = (length, max) => [...new Array(length)]
    .map(() => Math.round(Math.random() * max));

Solution 4 - Javascript

Even shorter ES6 approach:

Array(40).fill().map(() => Math.round(Math.random() * 40))

Also, you could have a function with arguments:

const randomArray = (length, max) => 
  Array(length).fill().map(() => Math.round(Math.random() * max))

Solution 5 - Javascript

Shortest:

[...Array(40)].map(e=>~~(Math.random()*40))

Solution 6 - Javascript

Math.random() will return a number between 0 and 1(exclusive). So, if you want 0-40, you can multiple it by 40, the highest the result can ever be is what you're multiplying by.

var arr = [];
for (var i=0, t=40; i<t; i++) {
    arr.push(Math.round(Math.random() * t))
}
document.write(arr);

http://jsfiddle.net/robert/tUW89/

Solution 7 - Javascript

> .. the array I get is very little randomized. It generates a lot of blocks of successive numbers...

Sequences of random items often contain blocks of successive numbers, see the Gambler's Fallacy. For example:

> .. we have just tossed four heads in a row .. Since the probability of > a run of five successive heads is only 1⁄32 .. a person subject to the > gambler's fallacy might believe that this next flip was less likely to > be heads than to be tails. > http://en.wikipedia.org/wiki/Gamblers_fallacy

Solution 8 - Javascript

let randomNumber = Array.from({length: 6}, () => Math.floor(Math.random() * 39));

limited the array to 6 values to make it easy to see.

Solution 9 - Javascript

Because * has higher precedence than |, it can be shorter by using |0 to replace Math.floor().

[...Array(40)].map(e=>Math.random()*40|0)

Solution 10 - Javascript

You can generate arrays with 10 random numbers just two lines of code.

let result = new Array(10)
result = result.fill(0).map(() => Math.random());

and just .

console.log(vals);

Solution 11 - Javascript

Since the range of numbers is constrained, I'd say the best thing to do is generate the array, fill it with numbers zero through 39 (in order), then shuffle it.

Solution 12 - Javascript

var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
  myArray.push(Math.floor(Math.random()*limit));
}

This above is the traditional way of doing it but I second @Pointy and @Phrogz if you want to avoid duplicates in your array without having to do expensive computation

Solution 13 - Javascript

Quirk single-line solutions on every day.

Values in arrays is total random, so when you will be use this snippets, it will different.

An array (length 10) with random chars in lowercase

Array.apply(null, Array(10)).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); })

> [ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j' ]

An array (length 10) with random integer numbers from 0 to 99

Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })

> [ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]

An array random dates (from 10 years to ago to now)

Array.apply(null, Array(10)).map(function() { return new Date((new Date()).getFullYear() - Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 29) )})

> [ 2008-08-22T21:00:00.000Z, 2007-07-17T21:00:00.000Z,
> 2015-05-05T21:00:00.000Z, 2011-06-14T21:00:00.000Z,
> 2009-07-23T21:00:00.000Z, 2009-11-13T22:00:00.000Z,
> 2010-05-09T21:00:00.000Z, 2008-01-05T22:00:00.000Z,
> 2016-05-06T21:00:00.000Z, 2014-08-06T21:00:00.000Z ]

An array (length 10) random strings

Array.apply(null, Array(10)).map(function() { return Array.apply(null, Array(Math.floor(Math.random() * 10  + 3))).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); }).join('') });


> [ 'cubjjhaph', > 'bmwy', > 'alhobd', > 'ceud', > 'tnyullyn', > 'vpkdflarhnf', > 'hvg', > 'arazuln', > 'jzz', > 'cyx' ]

Other useful things you may found here https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js

Solution 14 - Javascript

Using some new ES6 features, this can now be achieved using:

function getRandomInt(min, max) {
    "use strict";
    if (max < min) {
        // Swap min and max
        [min, max] = [min, max];
    }

    // Generate random number n, where min <= n <= max
    let range = max - min + 1;
    return Math.floor(Math.random() * range) + min;
}

let values = Array.from({length: 40}, () => getRandomInt(0, 40));

console.log(values);

Note that this solution will only work in modern browsers that support these ES6 features: arrow functions and Array.from().

Solution 15 - Javascript

function shuffle(maxElements) {
    //create ordered array : 0,1,2,3..maxElements
    for (var temArr = [], i = 0; i < maxElements; i++) {
        temArr[i] = i;
    }

    for (var finalArr = [maxElements], i = 0; i < maxElements; i++) {
        //remove rundom element form the temArr and push it into finalArrr
        finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0];
    }

    return finalArr
}

I guess this method will solve the issue with the probabilities, only limited by random numbers generator.

Solution 16 - Javascript

I am pretty sure that this is the shortest way to create your random array without any repeats

var random_array = new Array(40).fill().map((a, i) => a = i).sort(() => Math.random() - 0.5);

Solution 17 - Javascript

Refer below :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

Solution 18 - Javascript

Using Es6

Option 1

new Array(40).fill(0).map(_ => Math.random() * 40 | 0)

creating an empty array of length 40,then filling it with 0 and then replacing zeros with random number. Math.random() generates floating number,so to float to int,using Bitwise OR(|)

Option 2

[...Array(40)].map(_ => Math.random() * 40 | 0)

replaced new Array(40).fill(0) with [...Array(40)] - it will clone empty(undefined) array of length 40

Option 3

using Array.from

Array.from(arrayLike, mapFn)

> arrayLike > > An array-like or iterable object to convert to an array. > > mapFn (Optional) > > Map function to call on every element of the array.

Array.from({length: 10}, () => Math.floor(Math.random() * 100));

If you want to fill with UNIQUE random numbers

We will achieve this using Set,as we know set only allows to add unique values.

let set = new Set();
while (set.size <= 40) {
  set.add((Math.random() * 400) | 0);
}
let randomArray = [...set];

But here one thing is important,that you need to multiply with bigger number than array length...otherwise it will take too much time to generate unique number,it might freeze the execution for long time.try to take 10 times bigger number as I take here 400

Solution 19 - Javascript

from the page suggested by @Phrogz

for (var i=0,nums=[];i<49;i++) nums[i]={ n:i, rand:Math.random() };
nums.sort( function(a,b){ a=a.rand; b=b.rand; return a<b?-1:a>b?1:0 } );

Solution 20 - Javascript

I needed something a bit different than what these solutions gave, in that I needed to create an array with a number of distinct random numbers held to a specified range. Below is my solution.

function getDistinctRandomIntForArray(array, range){
   var n = Math.floor((Math.random() * range));
   if(array.indexOf(n) == -1){        
    return n; 
   } else {
    return getDistinctRandomIntForArray(array, range); 
   }
}

function generateArrayOfRandomInts(count, range) {
   var array = []; 
   for (i=0; i<count; ++i){
    array[i] = getDistinctRandomIntForArray(array, range);
   };
   return array; 
}

I would have preferred to not create a loop that has the possibility to end up with a lot of unnecessary calls (if your count, and range are high and are close to the same number) but this is the best I could come up with.

Solution 21 - Javascript

If you need it with random unique values from 0...length range:

const randomRange = length => {
  const results = []
  const possibleValues = Array.from({ length }, (value, i) => i)

  for (let i = 0; i < length; i += 1) {
    const possibleValuesRange = length - (length - possibleValues.length)
    const randomNumber = Math.floor(Math.random() * possibleValuesRange)
    const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange

    const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)

    results.push(nextNumber)
  }

  return results
}

randomRange(5) // [3, 0, 1, 4, 2]

Solution 22 - Javascript

A little late to the party, but I use randojs.com for randomness because it makes stuff like this super easy. You can get a randomly shuffled array of numbers from 0 through 39 just like this:

console.log(randoSequence(40));

<script src="https://randojs.com/1.0.0.js"></script>

No fuss with the logistics of it all- plus it's super readable and easy to understand :)

Solution 23 - Javascript

Generators

An array of length 40 of 40 random possible values (0 - 39) without repeating values is better to shuffle it as @Phrogz and @Jared Beck explain. Another approach, just for the records, could be using generators. But this approach lacks of performance compared to other proposed solutions.

function* generateRandomIterable(n, range) {
  for (let i = 0; i < n; i++) {
    yield ~~(Math.random() * range);
  }
}
const randomArr = [...generateRandomIterable(40,40)];

Solution 24 - Javascript

Here is a ES6 function that allows a min and a max and will generate an array of unique values in random order that contain all the number from min to max inclusive:

const createRandomNumbers = (min, max) => {
  const randomNumbers = new Set()
  const range = max - min + 1

  while (randomNumbers.size < range) {
    randomNumbers.add(~~(Math.random() * range))
  }

  return [...randomNumbers]
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexandraView Question on Stackoverflow
Solution 1 - JavascriptSimon BorskyView Answer on Stackoverflow
Solution 2 - JavascriptPhrogzView Answer on Stackoverflow
Solution 3 - JavascriptEugene KulabuhovView Answer on Stackoverflow
Solution 4 - JavascriptDamian PavlicaView Answer on Stackoverflow
Solution 5 - JavascriptCurtView Answer on Stackoverflow
Solution 6 - JavascriptRobertView Answer on Stackoverflow
Solution 7 - JavascriptJared BeckView Answer on Stackoverflow
Solution 8 - JavascriptRafaelView Answer on Stackoverflow
Solution 9 - Javascriptsup39View Answer on Stackoverflow
Solution 10 - JavascriptthegreytangentView Answer on Stackoverflow
Solution 11 - JavascriptPointyView Answer on Stackoverflow
Solution 12 - JavascriptAdy NgomView Answer on Stackoverflow
Solution 13 - JavascriptPADYMKOView Answer on Stackoverflow
Solution 14 - JavascriptLachlan HuntView Answer on Stackoverflow
Solution 15 - JavascriptPeter PshenichnyView Answer on Stackoverflow
Solution 16 - JavascriptJamie337nicholsView Answer on Stackoverflow
Solution 17 - JavascriptAvadhut ThoratView Answer on Stackoverflow
Solution 18 - JavascriptSaptarsiView Answer on Stackoverflow
Solution 19 - JavascriptLuis SiquotView Answer on Stackoverflow
Solution 20 - JavascriptJoeView Answer on Stackoverflow
Solution 21 - JavascriptideallifegeneratorView Answer on Stackoverflow
Solution 22 - JavascriptAaron PlocharczykView Answer on Stackoverflow
Solution 23 - JavascriptbrbnView Answer on Stackoverflow
Solution 24 - JavascriptCurtView Answer on Stackoverflow