Skip to main content
Participating Frequently
July 16, 2009
Answered

Generate Random Number ?!?

  • July 16, 2009
  • 1 reply
  • 956 views

Dear Guys I Want To Generate A Random Number Between 2 Number BUT Without Generating 2 Same Number I Mean If For Example Already Generated Number "2" Next Time Did Not Generate It , Is There Any Solution

This topic has been closed for replies.
Correct answer Ned Murphy

That function assumes you always start at 1, So all you need to do is modify that code to include the start value of your choice (changes in red):

function randList(start:Number max:Number, num:Number, shuffled:Boolean):Array { 
var tempArray:Array = []; 
for (i = (start-1); i < max && num > 0; ++i) { 
  if (Math.floor(Math.random() * (max - i)) < num) { 
   tempArray.push(i + 1); 
   num--; 
  } 

if (shuffled) { 
  tempArray.sort(function () { 
   return Math.floor(Math.random() * 2) ? true : false; 
  }); 

return (tempArray); 
}

var myArr:Array = randList(10, 20, 10, true); 
trace(myArr);

1 reply

Ned Murphy
Legend
July 16, 2009

While generating a random number between two numbers is fairly simple to do, the aspect of never generating the same number twice needs a little more explanation because it is always possible it can happen... that's the nature of random things.  Controls can be put in place to remember numbers already picked, but the complexity of those controls can vary.

Can you describe the scenario with a little more detail?  What are the two numbers?  Would the 'not the same' aspect be a session restriction or a forever restriction?

h_asalehAuthor
Participating Frequently
July 17, 2009

Check out this link

http://flashpants.blogspot.com/2009/03/generating-list-of-unique-random.html

thats work fine but i want to do that between 2 number i mean for example between 10 to 20 generate numbers in this range

Ned Murphy
Ned MurphyCorrect answer
Legend
July 17, 2009

That function assumes you always start at 1, So all you need to do is modify that code to include the start value of your choice (changes in red):

function randList(start:Number max:Number, num:Number, shuffled:Boolean):Array { 
var tempArray:Array = []; 
for (i = (start-1); i < max && num > 0; ++i) { 
  if (Math.floor(Math.random() * (max - i)) < num) { 
   tempArray.push(i + 1); 
   num--; 
  } 

if (shuffled) { 
  tempArray.sort(function () { 
   return Math.floor(Math.random() * 2) ? true : false; 
  }); 

return (tempArray); 
}

var myArr:Array = randList(10, 20, 10, true); 
trace(myArr);