Skip to main content
Known Participant
May 17, 2013
Question

Weird code Hiccup

  • May 17, 2013
  • 1 reply
  • 1006 views

I am using the following code in a project. It runs in two parts. The first randomizes the numbers 0-2.

The second part randomized the numbers 0-2 so that none of the numbers in the first set match the number in the second set. For example, if the first number in the first part is "1", then the second part will only return "0" or "2" in the first position.

The code works how I'd like it to work, except one out of maybe 15 times, the function skips the first part of the code and goes straight to the second part causing an overflow. Why does the code occasionally skip the first part?

var pi=3;

var t1:Array=[0,1,2];

var t2:Array=new Array();

var trasher:Array=new Array();

chooseThem()

function chooseThem():void

{for (var j:uint=0;j<3;j++)

     {trace ("working");

     var m=Math.floor(Math.random()*pi);

     t1.push(t1);

     trasher.push(t1);

     t1.splice(m,1);

     pi-=1};

for (var q:uint=0;t2.length<3;q++)

     {var f=Math.floor(Math.random()*trasher.length);

     trace (trasher.length+"trasher");

     if (trasher!=t1[pi]) {t2.push(trasher);trasher.splice(f,1);pi+=1}

     }

trace (t1);trace (t2+"t2")}

This topic has been closed for replies.

1 reply

kglad
Community Expert
Community Expert
May 17, 2013

you can use:

var t1:Array = [0,1,2];

var t2:Array = t1.slice();;

shuffle(t1);

shuffleExcept(t2,t1);

// don't change anything below

function shuffle(a:Array) {

    var p:int;

    var t:*;

    var ivar:int;

    for (ivar = a.length-1; ivar>=0; ivar--) {

        p=nextIndexF(ivar);

        t = a[ivar];

        a[ivar] = a

;

        a

= t;

    }

}

function shuffleExcept(a:Array,b:Array) {

    var p:int;

    var t:*;

    var ivar:int;

    for (ivar = a.length-1; ivar>=0; ivar--) {

        p = nextIndexF(ivar);

        while(a

==b[ivar]){

            p = nextIndexF(ivar);

        }

        t = a[ivar];

        a[ivar] = a

;

        a

= t;

    }

}

function nextIndexF(ivar:int):int{

    return Math.floor((ivar+1)*Math.random());

}

withertonAuthor
Known Participant
May 17, 2013

Thanks for the rresponse. I really appreciate it.

Do you have any idea why the the the first part of the code I posted is sometimes dropped? It's not just that it's not working properly. I have a trace statement right at the beginning of the first part and even that doesn't trace.

kglad
Community Expert
Community Expert
May 18, 2013

i didn't check your code any further than to see it was a bit of a mess and it would be easier to start from scratch and code it more logically.