Click here to Skip to main content
       

JavaScript

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questiongenerate random numbers from specific arraymemberaeman29 Dec '12 - 22:16 
Hi,
 
I want to generate random numbers in js from specific set of numbers iteratively e.g:
 
generate random numbers from array of (2,3,4) excluding 1 and next time from (1,3,4) excluding 2 like that. I have used Math.floor and Math.random()but they generate the numbers from given range like(1 to 4). What if i want to exclude any number or want to generate number from given specific set of numbers??
AnswerRe: generate random numbers from specific arraymvpSandeep Mewara4 Jan '13 - 3:06 
aeman wrote:
want to generate number from given specific set of numbers

What's the problem with generating random number within a range, see if the random number is not the one you want and then re-get the random number in case it's the one you wanted to avoid?
 
Example;
Random number between 1 to 4.
You wanted one of (1,3,4)
If random number returned is 2, ignore and re-get it.
 
Define a method that takes range start, end and exclude number:
function getRandom(rangeStart, rangeEnd, excludeNo)
{
  var ranNo = GetRandom(rangeStart, rangeEnd);
 
  // ranNo either of: 1, 2, 3, 4
  if(ranNo == excludeNo)
    getRandom(rangeStart, rangeEnd, excludeNo);
  
  return ranNo;
}
Sandeep Mewara
Microsoft ASP.NET MVP 2012 & 2013
 

[My Latest Article(s)]:
How to extend a WPF Textbox to Custom Picker
Server side Delimiters in ASP.NET

AnswerRe: generate random numbers from specific arraymemberJoe DiNatale4 Jan '13 - 9:28 
Using your example, I would generate a random number between 0 and 2. Then use the result as an index to your three element array.
AnswerRe: generate random numbers from specific arraymemberJohn Y.19 Feb '13 - 5:47 
If you need to use this often for arrays, I would add a function to the array prototype:
Array.prototype.randomPick = function(){
	var M = this.length-1;
	var N = 0;
	var randomIndex = Math.floor(Math.random()*(1+M-N))+N;
	return this[randomIndex];
};
Then you can call it:
var arr = [2,3,4,5,4,6,8,9,7];
alert(arr.randomPick());
________
John Y.
Developer

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   


Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 24 May 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid