please leave your comment

Thursday, May 6, 2010

Random Sequence without Repetition (Maxscript)

In practical use of scripting sometimes we really often using Random function to generate random numbers. But in some cases usually we also need to get random number in sequence without any repetition. for example how you get 5 sequence number without any same number in your result? By using "random 1 5" you will always have a chance to get the same number. Then how is the solution for this task...? After playing around little bit finally i found this solution:

-- CREATE FUNCTION
fn RandomSequence Num=
(   
    theSequence = for i=1 to Num collect i    -- Create Initial Sequence
    theResult =#() -- Create empty array for the result
   
    -- Loop
    range = theSequence.count+1
    for j=1 to theSequence.count do
    (   
        range -=1
        rand = random 1 range -- Create  random  start with higher range value until empty
        append theResult theSequence[rand]    -- Insert to the Result
        index = finditem theSequence theSequence[rand]    -- Check the index of result in thesequence
        deleteitem theSequence index     -- Then delete item in theSequence with indexed number
    )    -- End Loop
    theResult  -- Output the result
)

RandomSequence 10 -- Call the function


----------------Result---------------------
#(7, 8, 10, 5, 2, 4, 3, 6, 1, 9)


Every time you execute this function it will always generate new random number in sequence without any repetition. You can try use this number to manipulating object properties, transform, etc.

No comments:

Post a Comment