Sign in to follow this  
Followers 0
Coestar

2D array sorting by priority

13 posts in this topic

Hello everyone.

 

I haven't read much of the forums, so I'm not sure if this has been posted here before. Recently I started coding a small project and there is one thing I'm stuck on.

 

Say all the inputs from the user look like that (grade, branch, name, surname):

[4][A][John][Smith]
[6][B][John][Doe]
[4][B][Steve][Dennis]
[7][A][James][Lee]

I need them to be sorted first by grade (ascendingly), then by branch (alphabetically), then by name (alphabetically again) and lastly by surname (alphabetically once more). So after sorting the array should look like that:

[4][A][John][Smith]
[4][B][Steve][Dennis]
[6][B][John][Doe]
[7][A][James][Lee]
If you could help me with this function, I'd be very grateful.

Share this post


Link to post
Share on other sites



Where $a is your array:

#include <Array.au3>
Local $a[4][4]=[[4,"A","",""],[6,"B","",""],[4,"B","",""],[7,"A","",""]]
_ArraySort($a,1,0,0,1)
_ArraySort($a,0,0,0,0)
_ArrayDisplay($a)

output:

[0]|4|A||
[1]|4|B||
[2]|6|B||
[3]|7|A||
 


IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.

Share this post


Link to post
Share on other sites

Coestar,

You might find this UDF useful - it does exactly what you want. :)

M23

P.S. You and MrHudson use the same IP and joined within minutes of each other earlier this evening - you would not be one and the same person by any chance? We do not permit multiple accounts here. ;)


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

#5 ·  Posted (edited)

another way could be as this:
I had an idea to use sql to manage the array (with this little array is a little inappropriate), but with big arrays and if complex manipulations are needed then SQL is very powerful.
Here a simple "experiment" that transform an array to a temporary sql table
allows you to use sql query on that table
and at the end returns back data again into an array
Just an attempt without pretensions, but I found it interesting to make practice with SQL on big arrays (also with good performances)

#include <Array.au3>
#include <SQLite.au3>
#include <SQLite.dll.au3>
Global $aResult, $iRows, $iColumns, $iRval
; ---------------------------------------------------------------------------------------------------------------------------
Local $Array[4][4] = [[4, "A", "John", "Smith"],[6, "B", "John", "Doe"],[4, "B", "Steve", "Dennis"],[7, "A", "James", "Lee"]]
; ---------------------------------------------------------------------------------------------------------------------------
_SQLite_Startup()
_SQLite_Open()

_ArrayToSqlTable($Array) ; clone array to a temporary sql db

$iRval = _SQLite_GetTable2d(-1, "SELECT * FROM array;", $aResult, $iRows, $iColumns)
If $iRval = $SQLITE_OK Then
    ; _SQLite_Display2DResult($aResult)
    _ArrayDisplay($aResult, "Before sort")
Else
    MsgBox(16, "SQLite Error: " & $iRval, _SQLite_ErrMsg())
EndIf
; --- use sql to manage the array ------------------------------------------------------------------------
$iRval = _SQLite_GetTable2d(-1, "SELECT * FROM array order by field0,field1,field2;", $aResult, $iRows, $iColumns)
; --------------------------------------------------------------------------------------------------------

If $iRval = $SQLITE_OK Then
    ; _SQLite_Display2DResult($aResult)
    _ArrayDisplay($aResult, "After sort")
Else
    MsgBox(16, "SQLite Error: " & $iRval, _SQLite_ErrMsg())
EndIf

_SQLite_Close()
_SQLite_Shutdown()
; -- the end --

Func _ArrayToSqlTable($Array) ; Pass an array to a temporary SQL table
    If Not IsArray($Array) Then Return SetError(1, 0, 0)
    Local $DBfields = ""
    Local $DBvalues = ""
    Local $records = UBound($Array, 1) - 1
    Local $fields = UBound($Array, 2) - 1
    For $x = 0 To $fields
        $DBfields &= "field" & String($x) & ","
    Next
    $DBfields = StringTrimRight($DBfields, 1) ; remove the last comma

    If Not _SQLite_Exec(-1, "CREATE TEMP TABLE array (" & $DBfields & ");") = $SQLITE_OK Then
        MsgBox(16, "SQLite Error", _SQLite_ErrMsg())
    Else
        ; fill table with array's values
        For $x = 0 To $records
            For $y = 0 To $fields
                If IsNumber($Array[$x][$y]) Then
                    $DBvalues &= $Array[$x][$y] & ","
                Else
                    ; $DBvalues &= "'" & $Array[$x][$y] & "'" & ","
                    $DBvalues &= _SQLite_FastEscape($Array[$x][$y]) & ","
                EndIf
            Next
            $DBvalues = StringTrimRight($DBvalues, 1)
            ; insert row to table
            If Not _SQLite_Exec(-1, "INSERT INTO array VALUES (" & $DBvalues & ");") = $SQLITE_OK Then MsgBox(16, "SQLite insert Error", _SQLite_ErrMsg())
            $DBvalues = ""
        Next
    EndIf
EndFunc   ;==>_ArrayToSqlTable

P.S.

(I hope jchd will not laugh too much for my primitive attempt...... :unsure:)

Edited by PincoPanco

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites

I always smile but never sneer when SQLite is put at use. Congrats!


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

tks :)


small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites

Where $a is your array:

#include <Array.au3>
Local $a[4][4]=[[4,"A","",""],[6,"B","",""],[4,"B","",""],[7,"A","",""]]
_ArraySort($a,1,0,0,1)
_ArraySort($a,0,0,0,0)
_ArrayDisplay($a)
output:

[0]|4|A||

[1]|4|B||

[2]|6|B||

[3]|7|A||

Thanks a lot, that looks like the best and most lightweight solution, I will try to input it into the code and tell you if it worked.

P.S. You and MrHudson use the same IP and joined within minutes of each other earlier this evening - you would not be one and the same person by any chance? We do not permit multiple accounts here. ;)

Hudson's my neighbor and we decided to both register while tinkering with this project when I was at his place.

Share this post


Link to post
Share on other sites

Coestar,

 

Hudson's my neighbor and we decided to both register while tinkering with this project when I was at his place

Then welcome to you both. :)

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

#10 ·  Posted (edited)

OK, so I've taken a look at this UDF you posted but I don't really understand this, could you please elaborate?

$aSortData - 2D array holding details of the sort format;

Format: [Column to be sorted, Sort order];

Sort order can be either numeric (0/1 = ascending/descending) or a ordered string of items;

Any elements not matched in string are left unsorted after all sorted elements

Edited by Coestar

Share this post


Link to post
Share on other sites

Coestar,

 

could you please elaborate?

Of course. :)

You need the the columns to be sorted in ascending order - so you need to set the sort mode for each column to 0. You do this in the $aSortData array as you can see in this example:

#include <Array.au3>
#include "ArrayMultiColSort.au3"

; Here is the data to sort
Global $aArray[4][4] = [[4, "A", "John", "Smith"], _
                        [6, "B", "John", "Doe"], _
                        [4, "B", "Steve", "Dennis"], _
                        [7, "A", "James", "Lee"]]

; And here we set the sort order for each column - all the same in this case
Global $aSortData[4][2] = [ _
        [0, 0], _
        [1, 0], _
        [2, 0], _
        [3, 0]]

; Now we sort the array
_ArrayMultiColSort($aArray, $aSortData)

; And display the result - which is what you wanted
_ArrayDisplay($aArray, "Sorted")
Clearer? Try it with more lines of data and see if you get what you expect. :)

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

Oh, I get it, thanks a lot! Also, is there a way to use it on an already existing ListView?

Share this post


Link to post
Share on other sites

Coestar,

You would need to extract the data from the ListView into an array, sort the array and then rewrite the ListView. :)

If, as a new coder, the thought of doing that fills you with dread I just happen to have a UDF that could help you. Look at the GUIListViewEx UDF in my sig and play with the examples. Let me know if you think it could be useful (you do not have to utilise all the available functionality) and we can work on getting to play nicely with your script. ;)

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

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