Jump to content

Sorting (sort of) 2-dimensional array... brain hurts, pls help


Recommended Posts

I have an array like this:

 

 

$aArray[300][15]
 

One of the columns, say the 12th, contains the data I want to sort on.  But by "sort", I mean I want (for example) all the indexes that have that subitem starting with the letter "T" come first, and then everything else comes after (I don't care about sorting within the "T" data nor do I care about the order of the remaining data).

 

A simplified example

 

Bob   | Smith | Yes | Local  | Japan
Steve | Jones | No  | Travel | USA
James | Stone | Yes | Travel | Canada
Kim   | Jung  | Yes | Zulu   | Mars
I want that to sort on the (0-based) 3rd column with the two "Travel" rows first and the others (in any order) coming last. So it is like so:

 

Steve | Jones | No  | Travel | USA
James | Stone | Yes | Travel | Canada
Kim   | Jung  | Yes | Zulu   | Mars
Bob   | Smith | Yes | Local  | Japan
Make sense?

I just can't seem to figure out how to do [anything] with a particular index in a 2D array. Not sure why this is confusing me so much. I'm thinking it must be simple.

Edited by LondonNDIB
Link to comment
Share on other sites

You're going to have to loop through the array and search the 12th subitem for the text you're looking for, put that into a second array to hold the contents of the first array as you're looping through it.

#include <Array.au3>
Global $Array[][] = [["Kim", "Jung", "Yes", "Zulu", "Mars"], _
        ["Steve", "Jones", "No", "Travel", "USA"], _
        ["James", "Stone", "Yes", "Travel", "Canada"], _
        ["Bob", "Smith", "Yes", "Local", "Japan"]]
_ArrayDisplay($Array, "$Array")
Global $iColumns = UBound($Array, 2), $iRows = UBound($Array, 1), $iStart = 0
Global $Array1[$iRows][$iColumns]
;~ loop through the original array
For $Loop = 0 To $iRows - 1
    If $Array[$Loop][3] <> "Travel" Then ; If we don't find "Travel" add the array element to the end of the new array
        For $Loop2 = 0 To $iColumns - 1
            $Array1[$iRows - 1][$Loop2] = $Array[$Loop][$Loop2]
        Next
        $iRows -= 1 ; This lowers the insertion point for all array elements that don't match "Travel"
    Else ; We found "Travel" 
        ; Loop through the array element and add it to the start of the new array
        For $Loop2 = 0 To $iColumns - 1
            $Array1[$iStart][$Loop2] = $Array[$Loop][$Loop2]
        Next
        $iStart += 1 ; increase the insertion point for all array elements that match "Travel"
    EndIf
Next
_ArrayDisplay($Array1, "$Array1")

This will loop through your array, add the non-matching lines to the end of the array and work backwards to the start of the new array. It will add any matching lines to the start of the new array and work upwards towards the end of the array. Because the number of non-matching and matching items can only ever equal the total number of lines in the array, they'll never overlap. Also, because you don't care what order the non-matching lines are in the array this will put them into the new array in whatever order it finds them.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

#include <Array.au3>

Global $Array[][] = [["Kim", "Jung", "Yes", "Zulu", "Mars"], _
        ["Steve", "Jones", "No", "Travel", "USA"], _
        ["James", "Stone", "Yes", "Travel", "Canada"], _
        ["Bob", "Smith", "Yes", "Local", "Japan"]]
_ArrayDisplay($Array, "$Array")

$sortby = "T"
$x=0

For $i =  0 to ubound($Array) - 1

    If StringUpper(stringleft($Array[$i][3] , 1)) = $sortby AND $i = $x Then
        $x+=1
    ElseIf StringUpper(stringleft($Array[$i][3] , 1)) = $sortby Then
        _ArraySwap($Array[$i][0] , $Array[$x][0])
        _ArraySwap($Array[$i][1] , $Array[$x][1])
        _ArraySwap($Array[$i][2] , $Array[$x][2])
        _ArraySwap($Array[$i][3] , $Array[$x][3])
        _ArraySwap($Array[$i][4] , $Array[$x][4])
        $x+=1
    EndIf

next


_ArrayDisplay($Array, "$Array")

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

  • Moderators

Looks like a fun string manipulation exercise... but to be honest, you should do yourself a huge favor and take a day and learn up on SQLite and the power of its query's.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Looks like a fun string manipulation exercise... but to be honest, you should do yourself a huge favor and take a day and learn up on SQLite and the power of its query's.

I think I might take that advice.

Give me a clue: if I go down that road, would I be able to directly interact with a mysql database residing on a web server?

Link to comment
Share on other sites

  • Moderators

Oh, now you're talking fun stuff.

SQL query's are very similar across the board, whether it's SQLite/MySQL/MS SQL.  Each of course have their own rules.

I use primarily SQLite and MySQL (when I use my app to interact with our server).

I believe ProgAndy wrote the MySQL udf I use.

Answering your question directly... Yes, with the proper credentials you can interact with a MySQL db on a web server.

... searching for udf I use ...

Edit:

Found.. this should tell you how much I used it, knowing who wrote it :) ...

'?do=embed' frameborder='0' data-embedContent>>

Edited by SmOke_N

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Incidentally, BrewManNH's example worked wonderfully TY!

boththose's, unfortunately, did not. First off it wouldn't run (incorrect number of parameters for _ArraySwap - missing the array). After that was fixed, it still... well, it didn't work. Data wasn't sorted.

Link to comment
Share on other sites

im on 3.3.10.2 and it works fine.  Dont know if that rev included the new array udf...

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

In the last 3.3.12.0 release _ArraySwap() was modified

Using the old one the code works nice

#include <Array.au3>

Global $Array[][] = [["Kim", "Jung", "Yes", "Zulu", "Mars"], _
        ["Steve", "Jones", "No", "Travel", "USA"], _
        ["James", "Stone", "Yes", "Travel", "Canada"], _
        ["Bob", "Smith", "Yes", "Local", "Japan"]]
_ArrayDisplay($Array, "$Array")

$sortby = "T"
$x=0

For $i =  0 to ubound($Array) - 1
    If StringUpper(stringleft($Array[$i][3] , 1)) = $sortby AND $i = $x Then
        $x+=1
    ElseIf StringUpper(stringleft($Array[$i][3] , 1)) = $sortby Then
        _ArraySwapOld($Array[$i][0] , $Array[$x][0])
        _ArraySwapOld($Array[$i][1] , $Array[$x][1])
        _ArraySwapOld($Array[$i][2] , $Array[$x][2])
        _ArraySwapOld($Array[$i][3] , $Array[$x][3])
        _ArraySwapOld($Array[$i][4] , $Array[$x][4])
        $x+=1
    EndIf
next
_ArrayDisplay($Array, "$Array")

Func _ArraySwapOld(ByRef $vItem1, ByRef $vItem2)  ; before 3.3.12.0
    Local $vTmp = $vItem1
    $vItem1 = $vItem2
    $vItem2 = $vTmp
EndFunc   ;==>_ArraySwap
Link to comment
Share on other sites

thanks mikell,

I would totally vote to call that _ArraySwapSimple and add it back if it makes solutions as my example easier to script.

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

The old _ArraySwap was something that is so easy to write that it shouldn't have been in the Array UDF in the first place. It's just swapping 2 variables or arrays. It consisted of 3 lines.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

 It's just swapping 2 variables or arrays. It consisted of 3 lines.

 

 

I would use that as the defense for leaving it in.  If it is used at all, and only 3 lines, and there is no suitable replacement other than writing that same function yourself, where is the loss in leaving be?

And I dont understand LondonNIBs comment if _ArraySwap doesnt even exist in 3.3.12, seems the error would have been different than stated.

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

... just for a proof of concept, here another way to achieve the wanted result with SQL using a >simple udf I posted today

#include <ArraySQL.au3> ; <-- Get this from the following link
; http://www.autoitscript.com/forum/topic/166536-manage-arrays-by-means-of-sql/?p=1216612
;
Global $Array[][] = [["Kim", "Jung", "Yes", "Zulu", "Mars"], _
        ["Steve", "Jones", "No", "Travel", "USA"], _
        ["James", "Stone", "Yes", "Travel", "Canada"], _
        ["Bob", "Smith", "Yes", "Local", "Japan"]]
        ;
$sQuery = "SELECT * FROM array WHERE column3 = 'Travel' UNION ALL SELECT * FROM array WHERE column3 <> 'Travel';"
$aResult = _ArraySQL($Array, $sQuery)
If Not @error Then
    _ArrayDisplay($aResult)
Else
    MsgBox(0, "error", $g__sSQLiteError)
EndIf

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

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

Link to comment
Share on other sites

I would use that as the defense for leaving it in.  If it is used at all, and only 3 lines, and there is no suitable replacement other than writing that same function yourself, where is the loss in leaving be?

And I dont understand LondonNIBs comment if _ArraySwap doesnt even exist in 3.3.12, seems the error would have been different than stated.

It still exists, but it was rewritten to do things the original didn't do and doesn't do the original function at all any longer. Swapping the value of two variables or arrays are simple enough that they don't need to exist in the official release UDFs because a 3 line function is easily reproducible by most people. 

This is similar to the reason that _ArrayCreate was eliminated from the Array UDF, it didn't need to be in there because it was so easy to create something similar to it for most people.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Swapping the value of two variables or arrays are simple enough that they don't need to exist in the official release UDFs because a 3 line function is easily reproducible by most people. 

This is similar to the reason that _ArrayCreate was eliminated from the Array UDF, it didn't need to be in there because it was so easy to create something similar to it for most people.

 

Thus it becomes difficult to understand why the udf Math.au3 even exists, assuming users are able to make their own error checking all the funcs inside are one-liners

Link to comment
Share on other sites

It is an argument, when taken to the Nth degree, where we end up wondering why AutoIT even exists considering we can - if we know how - code it all in zeros and ones.

I would think that if any UDF saves someone typing anything at all, that it is worthwhile to some degree.

Link to comment
Share on other sites

  • Moderators

Hi,

As the person who rewrote much of the Array UDF I thought I might give some of the reasoning behind the _ArraySwap change. :)

The old version of the function had no real place in the Array library - it merely transposed 2 variables, which could be any combination of array elements or simple variables. It seems logical to replace it by a new function which actually enabled multiple array elements to be manipulated - which is the main aim of the library. We discussed whether to keep the old function in some form, but decided that it was really too simple.

Remember that any UDF which is added to the standard install means that the task of the few of us who keep the whole package under control becomes just that bit more difficult - hence our reluctance to add many of the excellent UDFs that are found in the Examples section. Once included it becomes our job to maintain the code, ensuring compatibility with all the other UDFs (have you ever noticed how many of them call each other?) and dealing with bug reports and feature requests. So although I sympathise with the "any UDF is worthwhile" point of view, I would ask you think of the reverse side of that particular argument as well. ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see 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

 

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...