Sign in to follow this  
Followers 0
sgmailer

Randomize Elements of an Array

4 posts in this topic

Hi,

Let's just say that we've already assigned values to each element of an array. Is it possible to randomly mixed those elements up without losing any of the elements (in other words, keeping every element)?

If needed, I wonder if it's possible to store all of the elements in a text file and have the script read each line randomly?

Thanks for any help in advance.

Share this post


Link to post
Share on other sites



Search for shuffle:

#479925

Share this post


Link to post
Share on other sites

Let's just say that we've already assigned values to each element of an array. Is it possible to randomly mixed those elements up without losing any of the elements (in other words, keeping every element)?

Doesn't sound hard. Loop through the array, using Random() to pick a new location for each element.

If needed, I wonder if it's possible to store all of the elements in a text file and have the script read each line randomly?

Certainly possible, but it sounds like more work than the suggestion above.

:)


Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law

Share this post


Link to post
Share on other sites

My example is for a 2d array. It should be easy to alter to a single array. Similar to weaponx's example.

Theory is - Randomly swap all data in the array, one at a time. You randomly select the index of the array to choose which data is swapped.

;Randomize existing data in in array (matrix)   
Func RandomizeMatrixData($m)
    ; Shuffle
    Local $c, $rx, $ry
    Dim $irow= UBound($m), $icol = UBound($m, 2)    
        for $loop5 = 1 to 5
        For $x = 0 To $irow - 1 
           for $y = 0 to $icol -1
                $c = $m[$x][$y]                   ; swap
                $rx = Random (0,($irow -1),1)     ; Random x index
                $ry = Random (0,($icol -1),1)     ; Random y index
                $m[$x][$y] = $m[$rx][$ry]         ; swap
                $m[$rx][$ry] = $c                 ; final swap            
            Next
        Next    
        next
    return $m
EndFunc

There is an extra For - Next loop which runs through the swapping process 5 times to ensure it looks random

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0