Jump to content

Arrays 101: All you need to know about them!


TheDcoder
 Share

Recommended Posts

Anyway, it is not only the cpu cycles we need to consider.. I agree that in Autoit it may be less relevant in many cases..
I came to realization that "optimization" should not only about cpu performance. but it also about ram performance and even more -
also about how much the code readable..

About CPU optimization vs RAM optimization, I Understand that it is not possible to make optimization that is perect in RAM and CPU..
You will always have to choose between the two. Optimization which is perfect in RAM and CPU can not be, because I understand that it is against the laws of physics..
About "code readable" optimization (that is the performance of your brain while you read the code) - I think that it may be more easy to make such optimization if you focus on RAM optimization.. the problem in Autoit that you have very few tools to make such optimization.. what you have is #Region , #cs & #ce ";".. what more? in C++ you have lot of tools that help you easly make such optimization. the #define is very powerfull tool and I I'm talking mostly about the preprocessor option (before compile). This is another reason I think to start using C++

Edited by Guest
Link to comment
Share on other sites

4 minutes ago, gil900 said:

This is another reason I think to start using 

Start using what?

Edit: Just saw your edit completing the sentence.

Edited by TheDcoder

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Smelling premature optimization.

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)

Link to comment
Share on other sites

4 minutes ago, TheDcoder said:

Start using what?

C++

Quote

Smelling premature optimization.

You suggest it's possible to do perfect optimization in RAM and CPU both ? I do not think it's possible

Edited by Guest
Link to comment
Share on other sites

I searched " premature optimization" on google and now I know  what are you talking about.
I agree that it is usually unnecessary to deal with optimizing CPU or RAM .. As time goes on I realize that the most important
optimization is the "code readable" optimization (that is the performance of your brain while you read the code). I do not know if there is an exact word-definition for such optimization ... And this kind of optimization more easy to do in C++

 

Edited by Guest
Link to comment
Share on other sites

It's called "robust coding" whatever language you use.

 

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)

Link to comment
Share on other sites

1 hour ago, gil900 said:

I realize that the most important optimization is the "code readable" optimization

AutoIt and other BASIC languages are pre-optimized for that, unlike C or C++ :)

Edited by TheDcoder

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

 

 

1 hour ago, TheDcoder said:

AutoIt and other BASIC languages are pre-optimized for that, unlike C or C++ :)

I agree, But your options to make additional costum optimization is very limited

Link to comment
Share on other sites

16 minutes ago, gil900 said:

But your options to make additional costum optimization is very limited

I disagree, it is limited to the point until further optimization has very little benefit. It still has a lot of room for optimization... especially "visual" optimization :)

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

  • 1 year later...

Don't mean to necro - just the most reasonable topic to add to.

Trap for people coming from many other languages, multi-dimensional arrays are not arrays of arrays.

https://www.autoitscript.com/wiki/Arrays#Multi_Dimensional_Arrays

It's explained somewhat in that wiki article, but to clarify with a bit more granularity:

; need this include to run some of the code

#include <Array.au3>

; This is a multi-dimensional array with 2 rows and 3 columns
Local $aMultidimensionalArray = [["a","b","c"],["d","e","f"]]

; To explain rows/columns vs their indices (arrays in AutoIt are zero-based):
; [
;   ["a","b","c"], ; row 1, index 0
;   ["d","e","f"] ; row 2, index 1
;     |   |   `- column 3, index 2
;     |   `- column 2, index 1
;     `- column 1, index 0
; ]

; You can access the element in the 1st row, 2nd column
$value = $aMultidimensionalArray[0][1]
ConsoleWrite("Value: "&$value&@CRLF) ; writes 'b'

; But you cannot access a row expecting to get that as an array as you might in other languages:
$row = $aMultidimensionalArray[0] ; error line
ConsoleWrite(_ArrayToString($row)&@CRLF)

; This results in the following error:
; ==> Array variable has incorrect number of subscripts or subscript dimension range exceeded.
; Let's call this 'The Error'

; Which means you cannot get the size of the second dimension this way either, also resulting in The Error:
$iDimensionSize = UBound($aMultidimensionalArray[0])

; Instead, UBound takes a second parameter where you specify the Nth (1-based*) dimension to measure:
; (* specifying '0' measures the number of dimensions)
$iDimensionSize = UBound($aMultidimensionalArray,2)
ConsoleWrite($iDimensionSize&@CRLF) ; writes '3'

; You *must* always specify the single element you want to access
; If your multi-dimensional array has 4 dimensions, you can only ever access the single elements via
; $aFourDimensionalArray[x][y][z][n]

; This is true both for retrieving values, and for setting values.
; I.e. the following will trigger The Error:
$aMultidimensionalArray[1] = ["g","h","i"]

; You will have to split it up:
$aMultidimensionalArray[1][0] = "g"
$aMultidimensionalArray[1][1] = "h"
$aMultidimensionalArray[1][2] = "i"

; This is an array-of-arrays
Local $aArray1 = ["a","b","c"]
Local $aArray2 = ["d","e","f"]
Local $aArrayOfArrays = [$aArray1,$aArray2]

; The result is the same row and column data in a '2D table'
; But internally, these are VERY different

; You *can* access the row:
$row = $aArrayOfArrays[0]
ConsoleWrite(_ArrayToString($row)&@CRLF) ; writes 'a|b|c'

; And similarly get the size:
$iDimensionSize = UBound($aArrayOfArrays[0])
ConsoleWrite("Size: "&$iDimensionSize&@CRLF) ; writes '3'

; But you cannot set the row the same way, it will trigger The Error
$aArrayOfArrays[1] = ["g","h","i"]

; This is because as far as the syntax is concerned,
; you're trying to define a new array with space for 1 element, but assigning it 3 elements.
; To get around that, you'll have to do something like this instead:
Local $aArray2New = ["g","h","i"]
$aArrayOfArrays[1] = $aArray2New

; Unlike a multi-dimensional array, you cannot access single elements via multi-dimensional indexing:
$value = $aArrayOfArrays[0][1] ; error line
ConsoleWrite("Value: "&$value&@CRLF)

; This results in the following error:
; ==> Array variable has incorrect number of subscripts or subscript dimension range exceeded.
; Because as far as the syntax is concerned, you're trying to access a multi-dimensional array,
; when $aArrayOfArrays only has a single dimension, even though it has two levels.

; Instead, you'll have to make clear that $aArrayOfArrays[0] is its own row,
; and then get the value from that row's column:
$row = $aArrayOfArrays[0]
$value = $row[1]
ConsoleWrite("Value: "&$value&@CRLF) ; writes 'b'

; Or, in short-hand:
$value = ($aArrayOfArrays[0])[1] ; Note the parentheses
ConsoleWrite("Value: "&$value&@CRLF) ; writes 'b'

; If your array of arrays has 4 levels (not dimensions!), you can only ever access the single elements via
; ((($aArrayOfArrays[x])[y])[z])[n]
; or by assignment to variables, as in the earlier example, if you value readability

; However, you can't get the number of levels of your array-of-arrays via UBound
; In fact, because an array-of-arrays can have sub-arrays of different counts,
; that value would be meaningless unless your array-of-arrays is set up to always have the same sub-counts

; Both multi-dimensional arrays and arrays-of-arrays have their uses,
; and for some ease of use one may be preferable to the other.
; Multi-dimensional arrays are very strict, you can define them in any size you want,
; (and use ReDim to re-dimensions them)
; but you can access and write to only a single element at a time
; array-of-arrays are more flexible, but can lead to errors if you don't take good care of realizing that
; not each constituent sub-array neccessarilly has the same bounds as the others, that sub-arrays may
; get inadvertently modified by functions that operate on arrays, and that accessing a single element
; introduces parentheses/bracket inanity

; An alternative is to use/ write functions that take a multi-dimensional array,
; but let you treat it as an array of arrays for the most common use case: getting a row, or a beam, etc.
; from the multi-dimensional array for further processing.
; The function _ArrayExtract from Array.au3 does exactly this for simple 2D arrays:
$row = _ArrayExtract($aMultidimensionalArray,0)
ConsoleWrite(_ArrayToString($row)&@CRLF) ; prints 'a|b|c'

; But this function cannot be used to extract e.g. a column of data as an array.
; Though that is also not part of most other programming languages' syntax and would have to
; be dealt with using a custom function in those languages as well
Func _ArrayExtractColumn(ByRef $aMultiDimArray,$column=0)
    $iRowCount = UBound($aMultiDimArray)
    Local $aResult[$iRowCount]
    For $i = 0 To $iRowCount - 1
        $aResult[$i] = $aMultiDimArray[$i][$column]
    Next
    Return $aResult
EndFunc
$column = _ArrayExtractColumn($aMultidimensionalArray,1)
ConsoleWrite(_ArrayToString($column)&@CRLF) ; Writes 'b|h' if you followed row assignment, 'b|e' if you skipped that

Corrections, additions, etc. very welcomed.  My AutoIt is a tad rusty (2013 was my last post here) and I only recently had to deal with multi-dimensional arrays in a way where i ran into The Error and an array-of-arrays started looking real attractive.

Link to comment
Share on other sites

36 minutes ago, kamiquasi said:

Trap for people coming from many other languages, multi-dimensional arrays are not arrays of arrays.

The arrays in AutoIt are the same as in C/C++ and PHP, they're just  called arrays in arrays, even though they're the same as in AutoIt.

An array of arrays, by the description we use, is putting another array into a single element of an array, not the row/column concept that we generally use around here for 2D arrays, which is how other languages generally refer to as an array in an array.

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

@TheDcoder

Do you think that could be useful (and to "complete" the explanation) of looping through arrays, describing the Step parameter of the For...Next...Step loop? :)

In some cases, when you have a defined set of elements, which may be "structured" in the same way in the content of the array, and you are looking for a specific element that you know you can find every five elements for example, you could use the Step parameter.

By the way, amazing and definitely useful post! :huggles:

Edited by FrancescoDiMuro

Click here to see my signature:

Spoiler

ALWAYS GOOD TO READ:

 

Link to comment
Share on other sites

41 minutes ago, FrancescoDiMuro said:

Do you think that could be useful (and to "complete" the explanation) of looping through arrays, describing the Step parameter of the For...Next...Step loop?

It's described already, it's in the help file. That's not an array specific function For/Next/Step is in the there with a good enough explanation that should enable anyone with the will to learn how to use it.

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

@FrancescoDiMuro Yes, you are right, it would be indeed useful to explain the use of Step keyword in the For loop.

It has been a while since I have updated the main post and I now see multiple issues with it... I am too busy with other work at the moment so I cannot really take out time now.

Maybe someone else can take up the task? :)

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

@TheDcoder
Something like this (I'm busy at work too!):

Spoiler
#include <Array.au3>

; Sample #1

ConsoleWrite("Sample #1" & @CRLF & @CRLF)

; Declaring a 1-Dimensional empty array, dimensioned with 100 elements
Global $arrNumbers[100]

; Populate the array with numbers from 1 to 100
For $i = 0 To UBound($arrNumbers) - 1 Step 1
    $arrNumbers[$i] = $i + 1
Next

; Print the odd numbers
ConsoleWrite("Odd numbers: " & @CRLF)
For $i = 0 To UBound($arrNumbers) - 1 Step 2
    ConsoleWrite("Array element #" & $i & " = " & $arrNumbers[$i] & @CRLF)
Next

; Print the even numbers
ConsoleWrite(@CRLF & "Even numbers: " & @CRLF)
For $i = 1 To UBound($arrNumbers) - 1 Step 2
    ConsoleWrite("Array element #" & $i & " = " & $arrNumbers[$i] & @CRLF)
Next

ConsoleWrite("--------------------------------------------------" & @CRLF)

; Sample #2

ConsoleWrite("Sample #1" & @CRLF & @CRLF)

Global $strINIFileName = @ScriptDir & "\Config.ini", _ ; Path of the INI file
       $arrINISectionNames[0], _                       ; Declaring a 1-Dimensional empty array
       $arrINISectionValues[0][2], _                   ; Declaring a 2-Dimensional empty array, dimensioned with two columns
       $arrINIContent[0][2]                            ; Declaring a 2-Dimensional empty array, dimensioned with two columns

; Read all the INI section names from the INI file
$arrINISectionNames = IniReadSectionNames($strINIFileName)
If @error Then
    ConsoleWrite("!Error while reading the INI section names from the file '" & $strINIFileName & "'. Error: " & @error & @CRLF)
Else
    ; Loop through the array in which are stored all the INI section names, to get the key names/key values of the current section
    ; In this case, since we are looping all the elemens one by one, we could omit the parameter Step, since its default value is 1.
    For $i = 1 To UBound($arrINISectionNames) - 1 Step 1

        ; Read the INI section keys/values
        $arrINISectionValues = IniReadSection($strINIFileName, $arrINISectionNames[$i])
        If @error Then
            ConsoleWrite("!Error while reading the section '" & $arrINISectionNames[$i] & "' from the file '" & $strINIFileName & "'. Error: " & @error & @CRLF)
        Else
            ; Deleting the first (0th) element in the array, in which is stored the number of keys in the current section
            _ArrayDelete($arrINISectionValues, 0)
            ; Add the section to the "general" array
            _ArrayAdd($arrINIContent, $arrINISectionValues)
        EndIf
    Next
EndIf

; Using the Step parameter of the For...Next...Step loop
; - $i = 0, Step = 1: Loop all the array elements one by one
; - $i = 0, Step = 3: Print all the SourcePaths
; - $i = 1, Step = 3: Print all the InstallPaths
; - $i = 2, Step = 3: Print all the InstallerNames

For $i = 2 To UBound($arrINIContent) - 1 Step 3
    ConsoleWrite("Array element #" & $i & ":" & $arrINIContent[$i][0] & " = " & $arrINIContent[$i][1] & @CRLF)
Next

ConsoleWrite(@CRLF)

 

A couple of samples when the use of Step parameter in a For...Next...Step loop could be useful :) 

Edited by FrancescoDiMuro

Click here to see my signature:

Spoiler

ALWAYS GOOD TO READ:

 

Link to comment
Share on other sites

@FrancescoDiMuro Done, in the end I wrote my own code to keep it simple but also linked to your post :)

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

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

×
×
  • Create New...