开发者

Flash AS3 Random function, 0-9, EXCEPT 3 for example

I wonder how to make a Math.random() function, or something similar where it chooses a number from 0-9. But as the program progresses, another random variable will appear开发者_运维技巧. That random value is what I want removed from the 0-9 scale. (The other random variable is also from 0-9)


Math.random( ) returns a number from 0-1

function randomNum( modifier:int ):Number{
    return Math.floor(Math.random()*(9-modifier));
}

New edited code
Pass the array you want to grab an element out of and it will return the value of the randomed element. use seedArray.splice(0, 1); to remove elements from the array in this case it would be the first element.

var seedArray:Array = [10,1000,20,245,874687,57,3456];
trace(this.randomElement(seedArray) )
seedArray.splice(0, 1);
trace(this.randomElement(seedArray) )
seedArray.splice(0, 1);
trace(this.randomElement(seedArray) )
seedArray.splice(0, 1);
trace(this.randomElement(seedArray) )
seedArray.splice(0, 1);
trace(this.randomElement(seedArray) )
seedArray.splice(0, 1);
trace(this.randomElement(seedArray) )
seedArray.splice(0, 1);
trace(this.randomElement(seedArray) )

    function randomElement( arr:Array ):Number{
      var rand:int = Math.floor(Math.random()*arr.length)
      return arr[rand];
    }


this should work

private function zeroToNineExcept(toExclude:int):int{
    var retVal: int = -1;
    if(toExclude < 0 || toExclude > 9) {
        //trace a message, throw an argument error, ...
        return retVal;
    }
    while(retVal = Math.round(Math.random() * 9)){
        if(retVal == toExclude){ 
            continue;
        }else{ 
            return retVal;
        }
    }
}


I think it's best to do the randomization up front:

var randomValues:Array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
randomValues.sort(function(a:int, b:int):int {return Math.random() < 0.5 ? -1 : 1});

After this initialization, randomValues.pop() will get you an unused value from the array.


This function will get a random array element. Then splice that element out of the array and return the value of the element. The return value and result data types are the only thing that should have to be changed.

private function getRandomArrayElement(arr:Array):string
{
    var index:int = Math.floor(Math.random() * arr.length);
    var result:string = arr[index];
    arr.splice(index, 1);

    return result;
}

If your wanting to maintain the data in the array and return a randomized array This will work.

private function randomizeArray(arr:Array):Array
{
    var result:Array = [];

    while (arr.length > 0)
    {
        result.push(arr.splice(Math.floor(Math.random() * arr.length), 1));
    }

    return result;
}

My test data was as follows.

var testArray:Array = ["Hi", "Bye", "Okay", "Yes", "No", "Maybe", "Sometimes", "Anywhere", "You said it!"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜