A Flash Developer Resource Site

Results 1 to 2 of 2

Thread: generating unique elements in an array

  1. #1
    Junior Member
    Join Date
    Jan 2001
    Posts
    4
    I'm trying to generate an array with 3 random elements
    the problem is I want each element to have a unique value

    here is what I have so far but it seems to be an infinite loop. Is there an easier way or can this code be fixed

    winList = new Array();
    //
    for (i = 0; i < 3; i++) {
    ran = random(3)+1;
    winList[i] = ran;
    trace (winList);
    for (j = 0; j < i; j++) {
    do {
    ran = random(3)+1;
    winList[i] = ran;
    } while (winList[j] = winlist[i-1]);
    }
    }

  2. #2
    Hack
    Join Date
    Mar 2000
    Location
    Madison, WI
    Posts
    1,753
    Do you mean

    2, 1, 3 is ok
    1, 3, 2 is ok
    3, 1, 2 is ok, but
    1, 1, 2 is not
    3, 3, 1 is not etc?

    If so, here's what I do:

    source = new Array(1, 2, 3);
    target = new Array();
    while (target.length<3) {
    rand = random(source.length);
    target.push(source.splice(rand, 1));
    }

    PS You could have picked that little trick up in FAST file #3 (see link below)

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