Javascript generate random unique number every time
-
Ok so i need to create four randomly generated numbers between 1-10 and they cannot be the same. so my thought is to add each number to an array but how can I check to see if the number is in the array, and if it is, re-generate the number and if it isnt add the new number to the array? so basically it will go, 1.create new number and add to array 2.create second new number, check to see if it exist already, if it doesn't exist, add to array. If it does exist, re-create new number, check again etc... 3.same as above and so on.
-
Answer:
You want what is called a 'random grab bag'. Consider you have a 'bag' of numbers, each number is only represented once in this bag. You take the numbers out, at random, for as many as you need. The problem with some of the other solutions presented here is that they randomly generate the number, and check to see if it was already used. This will take longer and longer to complete (theoretically up to an infinite amount of time) because you are waiting for the random() function to return a value you don't already have (and it doesn't have to do that, it could give you 1-9 forever, but never return 10). There are a lot of ways to implement a grab-bag type solution, each with varying degrees of cost (though, if done correctly, won't ever be infinite). The most basic solution to your problem would be the following: var grabBag = [1,2,3,4,5,6,7,8,9,10]; // randomize order of elements with a sort function that randomly returns -1/0/1 grabBag.sort(function(xx,yy){ return Math.floor(Math.random() * 3) - 1; }) function getNextRandom(){ return grabBag.shift(); }; var originalLength = grabBag.length; for(var i = 0; i < originalLength .length; i++){ console.log(getNextRandom()); } This is of course destructive to the original grabBag array. And I'm not sure how 'truly random' that sort is, but for many applications it could be 'good enough'. An slightly different approach would be to store all the unused elements in an array, randomly select an index, and then remove the element at that index. The cost here is how frequently you are creating/destroying arrays each time you remove an element.
Greg Thompson at Stack Overflow Visit the source
Other answers
Use an array to see if the number has already been generated. var randomArr = [], trackingArr = [], targetCount = 4, currentCount = 0, min = 1, max = 10, rnd; while (currentCount < targetCount) { rnd = Math.floor(Math.random() * (max - min + 1)) + min; if (!trackingArr[rnd]) { trackingArr[rnd] = rnd; randomArr[currentCount] = rnd; currentCount += 1; } } alert(randomArr); // Will contain four unique, random numbers between 1 and 10. Working example: http://jsfiddle.net/FishBasketGordo/J4Ly7/
FishBasketGordo
var a = []; for (var i = 0; i < 5; i++) { var r = Math.floor(Math.random()*10) + 1; if(!(r in a)) a.push(r); else i--; } That'll do it for you. But be careful. If you make the number of random numbers generated greater than the may number (10) you'll hit an infinite loop.
Joseph Marikle
Here are a couple versions using Matt's grabBag technique: function getRandoms(numPicks) { var nums = [1,2,3,4,5,6,7,8,9,10]; var selections = []; // randomly pick one from the array for (var i = 0; i < numPicks; i++) { var index = Math.floor(Math.random() * nums.length); selections.push(nums[index]); nums.splice(index, 1); } return(selections); } You can see it work here: http://jsfiddle.net/jfriend00/b3MF3/. And, here's a version that lets you pass in the range you want to cover: function getRandoms(numPicks, low, high) { var len = high - low + 1; var nums = new Array(len); var selections = [], i; // initialize the array for (i = 0; i < len; i++) { nums[i] = i + low; } // randomly pick one from the array for (var i = 0; i < numPicks; i++) { var index = Math.floor(Math.random() * nums.length); selections.push(nums[index]); nums.splice(index, 1); } return(selections); } And a fiddle for that one: http://jsfiddle.net/jfriend00/UXnGB/
jfriend00
I'm using a recursive function. The test function pick 6 unique value between 1 and 9. //test(1, 9, 6); function test(min, max, nbValue){ var result = recursValue(min, max, nbValue, []); alert(result); } function recursValue(min, max, nbValue, result){ var randomNum = Math.random() * (max-min); randomNum = Math.round(randomNum) + min; if(!in_array(randomNum, result)){ result.push(randomNum); nbValue--; } if(nbValue>0){ recursValue(min, max, nbValue, result); } return result; } function in_array(value, my_array){ for(var i=0;i< my_array.length; i++){ if(my_array[i] == value){ console.log(my_array+" val "+value); return true; } } return false; }
wenders
Related Q & A:
- What to do to avoid having to login to facebook every time?Best solution by uk.answers.yahoo.com
- how to generate random isotropic vectors using R?Best solution by Stack Overflow
- Why do I have to completely "sign in" every time I log on for mail?Best solution by Yahoo! Answers
- Why am I vomiting all the time every time I eat?Best solution by medhelp.org
- Suggestions for a unique number plate?Best solution by coolpl8z.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.