Sign in to follow this  
Followers 0
picea892

Randomly Sort an Array

49 posts in this topic

Hi all

So, I'm considering my options for randomly sorting an array. _arraySort can sort ascending/descending.

I would have to utilize the random function. Except that continuously choosing random numbers between the array max and min seems to be a poor way of doing it. Does anyone have a thought on how to accomplish this?

Picea

Share this post


Link to post
Share on other sites



picea892,

I would do it this way - unless the array is seriously large, when all the Redims would slow it down unacceptably.

#include <Array.au3>

Global $aInput[9] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Global $aOutput[UBound($aInput)]

For $i = 0 To UBound($aInput) - 1

    _Get_Element($i)

Next

_ArrayDisplay($aOutput, "Output")

Func _Get_Element($iOutPutIndex)

    $iInputIndex = Random(0, UBound($aInput) - 1, 1)

    $aOutput[$iOutPutIndex] = $aInput[$iInputIndex]
    _ArrayDelete($aInput, $iInputIndex)

EndFunc

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

#Include <Array.au3>

Dim $Data[10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

_ArrayDisplay($Data)
For $i = 1 To 100
    $A = Random(0, UBound($Data) - 1, 1)
    $B = Random(0, UBound($Data) - 1, 1)
    $Temp = $Data[$A]
    $Data[$A] = $Data[$B]
    $Data[$B] = $Temp
Next
_ArrayDisplay($Data)

1 person likes this

Share this post


Link to post
Share on other sites

Wow...great examples guys....And the solutions appear to be random....no solution is duplicated. I think that Melba23's example seems more random somehow.

Thanks again for these excellent solutions

Share this post


Link to post
Share on other sites

picea892,

Yashied's code is much faster if you are looking to randomise really large arrays - it is the _ArrayDelete (running ReDim internally) which is the killer. For a 10000 element array, my code takes around 90 sec, Yashied's a mere 1 sec. No contest really! :mellow:

Moral: try to avoid ReDim if you can - particularly for large arrays!

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

picea892,

Yashied's code is much faster if you are looking to randomise really large arrays - it is the _ArrayDelete (running ReDim internally) which is the killer. For a 10000 element array, my code takes around 90 sec, Yashied's a mere 1 sec. No contest really! :mellow:

Moral: try to avoid ReDim if you can - particularly for large arrays!

M23

Melba23

Yashied's code will not randomize large arrays.

The For-Next loop loops 100 times. The possible maximum number of elements that could be randomized is 200. For a 10,000 element array, 9,800 elements would remain the same, untouched.

Share this post


Link to post
Share on other sites

Malkey,

I had, of course, modified his code to run the loop 10 times the number of elements in the array. :mellow:

He still won! :(

M23

P.S. If you are interested:

#include <Array.au3>

Global $aInput[10000]
For $i = 0 To 9999
    $aInput[$i] = $i
Next

ConsoleWrite("Yashied starts" & @CRLF)

$iBegin = TimerInit()

For $i = 1 To UBound($aInput) * 10
    $A = Random(0, UBound($aInput) - 1, 1)
    $B = Random(0, UBound($aInput) - 1, 1)
    $Temp = $aInput[$A]
    $aInput[$A] = $aInput[$B]
    $aInput[$B] = $Temp
Next

ConsoleWrite("Yashied: " & TimerDiff($iBegin) & @CRLF)

ConsoleWrite("M23 starts" & @CRLF)

$iBegin = TimerInit()

Global $aOutput[UBound($aInput)]

For $i = 0 To UBound($aInput) - 1

    _Get_Element($i)

Next

ConsoleWrite("M23: " & TimerDiff($iBegin) & @CRLF)

Func _Get_Element($iOutPutIndex)

    $iInputIndex = Random(0, UBound($aInput) - 1, 1)

    $aOutput[$iOutPutIndex] = $aInput[$iInputIndex]
    _ArrayDelete($aInput, $iInputIndex)

EndFunc


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Yashied,

Makes you even faster! :mellow:

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Yashied,

[serious]

I believe your statement as it seems quite reasonable from a common-sense point of view, but do you have a mathematical basis for saying 2*array_size is the minimum?

[/serious]

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

whatever Edited by MvGulik

"Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions."
"The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014)

"Believing what you know ain't so" ...

Knock Knock ...
 

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

I believe your statement as it seems quite reasonable from a common-sense point of view, but do you have a mathematical basis for saying 2*array_size is the minimum?

IMHO

#Include <Array.au3>

Dim $Data[1000]

For $i = 0 To UBound($Data) - 1
    $Data[$i] = $i
Next

For $i = 1 To 9
    $Count = 0
    $Temp = $Data
    _ArraySortRandom($Temp, $i)
    For $j = 0 To UBound($Temp) - 1
        If $Temp[$j] = $Data[$j] Then
            $Count += 1
        EndIf
    Next
    ConsoleWrite('x' & $i & ' => ' & (100 * $Count / UBound($Data)) & '% matches' & @CR)
Next

Func _ArraySortRandom(ByRef $aArray, $iMultiplier = 2)

    Local $A, $B, $Temp

    For $i = 1 To $iMultiplier * UBound($aArray)
        $A = Random(0, UBound($aArray) - 1, 1)
        $B = Random(0, UBound($aArray) - 1, 1)
        $Temp = $aArray[$A]
        $aArray[$A] = $aArray[$B]
        $aArray[$B] = $Temp
    Next
EndFunc   ;==>_ArraySortRandom

~2% (20 of 1000) matches for 1k points with x2 multiplier. More than x4 does not make sense to choose.

:mellow:

Edited by Yashied

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

Why is the match % at x1 always so much higher than the rest? Result always looks like this:

x1 => 14.5% matches
x2 => 2.2% matches
x3 => 0.1% matches
x4 => 0.1% matches
x5 => 0.1% matches
x6 => 0.1% matches
x7 => 0.2% matches
x8 => 0.1% matches
x9 => 0.1% matches

Very strange right? $Temp always gets initialized back to $Data, which doesn't change, but still the % matches is extremely high (relatively) @ x1 compared to x2 and up...

~ edit

Oh lol nvm, I thought you were just running it 9 times with multiplier 2 but you use a different multiplier ($i from 1 To 9)

Edited by d4ni

Share this post


Link to post
Share on other sites

Yashied,

Thanks. :mellow:

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

#18 ·  Posted (edited)

whatever Edited by MvGulik

"Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions."
"The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014)

"Believing what you know ain't so" ...

Knock Knock ...
 

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

There is no need to scan the array multiple times as it can be done in O(N) instead of O(kN).

Durstenfeld variant of the Fisher–Yates algorithm works in a single pass, uses only one call to Random() and guarantees randomness not worst than the one provided by Random(). (And AutoIt Random is very good.)

#Include <Array.au3>

;;;;;; SRandom(@AutoItPID) don't use that.

Local Const $limit = 10000
Dim $Data[$limit]

For $i = 0 To $limit - 1
    $Data[$i] = $i
Next
_ArrayDisplay($Data)

For $i = UBound($Data) - 1 To 1 Step -1
    $j = Random(0, $i, 1)
    $Temp = $Data[$j]
    $Data[$j] = $Data[$i]
    $Data[$i] = $Temp
Next
_ArrayDisplay($Data)

EDIT: I didn't mean to actually use SRandom() at all. To be honest I don't remember why it was left there...

Edited by jchd
1 person likes this

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

#20 ·  Posted

Here's one that I got from SmOke_N several months back that might do what you want.

Func _ArrayRandomShuffle($av_array, $i_lbound = 0)
    Local $i_ubound = UBound($av_array) - 1
    Local $icc, $s_temp, $i_random
    
    For $icc = $i_lbound To $i_ubound
        $s_temp = $av_array[$icc]
        $i_random = Random($i_lbound, $i_ubound, 1)
        $av_array[$icc] = $av_array[$i_random]
        $av_array[$i_random] = $s_temp
    Next
    
    Return $av_array
EndFunc

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

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