0
public class Lottery extends Sprite {

    public var text0:TextField, text1:TextField, text2:TextField, text3:TextField, text4:TextField, text5:TextField;
    public var backImage:Sprite, luckyBtn:Sprite, clearBtn:Sprite;
    public var tfFormat:TextFormat = new TextFormat;

    public function Lottery()
    {
        setTextFieldFormat();
        loadGUI();
    }

    public function luckyDip(event:MouseEvent):void {
        for (var i:uint = 0; i <= 49; i++) {
            this["text" + i].text = Math.ceil(Math.random() * 49);
        }
    }

    public function resetFields(event:MouseEvent):void {
        for (var i:uint = 0; i <= 49; i++) {
            this["text" + i].text = "";
        }
    }

How do I modify this so I can still generate a random sequence, but not repeat any of the entries?

  • The normal approach is to make a list with every number then randomly remove them. – aebabis Mar 11 '14 at 00:40
  • 2
    Use a [*shuffle* algorithm](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) over the numbers. Then take/consume the numbers in sequence. This will ensure a decent distribution and prevent any duplicate choices. – user2864740 Mar 11 '14 at 00:42
  • possible duplicate of [How to randomize (shuffle) a javascript array?](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – user2864740 Mar 11 '14 at 00:46
  • (I voted as a duplicate because creating the initial sequence and then consuming the shuffled results are mostly inconsequential task details; there are also AS-specific questions easily found by searching for "actionscript shuffle".) – user2864740 Mar 11 '14 at 00:48

1 Answers1

0

In the lottery game you have limited numbers of results, for example: 5 numbers from 1-50. All you need is to create list of random unique numbers from 1-N.

//How to use, one of the results: 9,40,44,29,4
trace(lotteryGenerator(5));

private function lotteryGenerator(results: uint, maxValue:uint = 50):Array{
    var i: uint, luckyNumber: uint, result: Array = [], added: uint;

    while(added < results){
        luckyNumber = 1 + Math.random() * (maxValue - 1);
        if(result.indexOf(luckyNumber) == -1){
            result.push(luckyNumber);
            added++;
        }
    }

    return result;
}
Nicolas Siver
  • 2,875
  • 3
  • 16
  • 25