A Flash Developer Resource Site

Results 1 to 4 of 4

Thread: Random number generation

  1. #1
    Bunchprunk Dadger. punchbear's Avatar
    Join Date
    Jan 2001
    Location
    Munich, Germany
    Posts
    196

    Random number generation

    I want to generate numbers on suitcases for an advent calendar in Flash MX. I've tried modifying a script I found in a tutorial but to no avail.

    I want any number between 1 and 24 to be generated, to appear on one of 12 suitcases. The number can't be repeated though.

    I'm quite stuck on this one....

    Here's the Swf.

    And here's the Fla.

    Help much needed and very much appreciated

    Cheers in advance
    A: "Why the hell won't my footer work?"

    B: "Well son, if you stick yer arse out the window, someone's bound to throw stones at it."

  2. #2
    Senior Member
    Join Date
    Oct 2003
    Posts
    1,354
    code:

    //create a temp_array from 1 to 24
    temp_array = new array();
    for (i=0;i<24;i++){
    temp_array[i] = i+1;
    }
    // pull 12 random numbers out from the temp_array
    my_array = new array();
    for(i=0;i<12;i++){
    // as we splice indexes from temp_array, it's length will get smaller
    rand = Math.floor(Math.random() * temp_array.length);
    my_array[i] = temp_array[rand];
    temp_array.splice(rand,1); //remove the used index from temp_array
    }
    //test the array:
    for(i=0;i<11;i++){
    trace(my_array[i]);
    }


  3. #3
    Senior Moderator
    Join Date
    Apr 2000
    Location
    Sheffield, UK
    Posts
    3,881
    Or:

    Code:
    //shuffle extension
    //randomly arranges the elements of an array
    Array.prototype.shuffle=function()
    { 
    	var len = this.length; 
    	var i = len; 
    	while (i--)
    	{ 
    		var p = random(len); 
    		var t = this[i]; 
    		this[i] = this[p]; 
    		this[p] = t; 
    	}
    }
    dates=[1,2,3,4,5,6,7,8,9,10,11,12]
    dates.shuffle()

  4. #4
    Bunchprunk Dadger. punchbear's Avatar
    Join Date
    Jan 2001
    Location
    Munich, Germany
    Posts
    196
    Got this too:

    //create an empty array
    days=new Array();
    //fill it with numbers from 1-24
    for(i=1;i<25;i++){
    days.push(i);
    }
    function go(){
    //create a random number
    randomNumber=random(days.length);
    //remove the number from the array
    days.splice(randomNumber,1);
    trace(randomNumber);
    trace(days);
    }
    _root.onMouseDown=function(){
    go();
    }


    Cheers and thanks guys, I'll give it a shot
    A: "Why the hell won't my footer work?"

    B: "Well son, if you stick yer arse out the window, someone's bound to throw stones at it."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center