Jump to content

Decipher
 Share

Recommended Posts

_ArraySlice() its similar to list[n:n] in Python. I was converting a python script to autoit and was bored afterwords so I decided to create this UDF.

#AutoIt3Wrapper_Au3Check_Parameters=-q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
; #FUNCTION# ====================================================================================================================
; Name...........: _ArraySlice
; Description ...: Returns the specified elements as a zero based array.
; Syntax.........: _ArraySlice(Const ByRef $avArray[, $iStart = 0[, $iEnd = 0[, $iStep = 1]]])
; Parameters ....: $avArray - Array to Slice
;                 $iStart  - [optional] Index of array to start slicing
;                 $iEnd - [optional] Index of array to stop slicing
;                 $iStep    - [optional] Increment can be negative
; Return values .: Success - Array containing the specified portion or slices of the original.
;                 Failure - "", sets @error:
;                 |1 - $avArray is not an array
;                 |2 - $iStart is greater than $iEnd when increment is positive
;                 |3 - $avArray is not an 1 dimensional array
;                 |4 - $iStep is greater than the array
; Author ........: Decipher
; Modified.......:
; Remarks .......:
; Related .......: StringSplit, _ArrayToClip, _ArrayToString
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
#include <Array.au3> ; Needed for _ArrayDisplay only.

Example()

Func Example()

   Local $MyArray[10]
   $MyArray[0] = 9
   $MyArray[1] = "One"
   $MyArray[2] = "Two"
   $MyArray[3] = "Three"
   $MyArray[4] = "Four"
   $MyArray[5] = "Five"
   $MyArray[6] = "Six"
   $MyArray[7] = "Seven"
   $MyArray[8] = "Eight"
   $MyArray[9] = "Nine"

   Local $MyNewArray = _ArraySlice($MyArray, 9, 0, -2)
  _ArrayDisplay($MyNewArray)

   $MyNewArray = _ArraySlice($MyArray, 1)
  _ArrayDisplay($MyNewArray)

   $MyNewArray = _ArraySlice($MyArray, 1, 5)
  _ArrayDisplay($MyNewArray)

   $MyNewArray = _ArraySlice($MyArray, 5)
  _ArrayDisplay($MyNewArray)

   $MyNewArray = _ArraySlice($MyArray, 1, 3, 1)
  _ArrayDisplay($MyNewArray)

EndFunc   ;==>Example

Func _ArraySlice(Const ByRef $avArray, $iStart = 0, $iEnd = 0, $iStep = 1)
   If Not IsArray($avArray) Then Return SetError(1, 0, 0)
   If UBound($avArray, 0) <> 1 Then Return SetError(3, 0, "")

   Local $iNew = 0, $iUBound = UBound($avArray) - 1

   ; Bounds checking
   If $iStep > $iUBound Then Return SetError(4, 0, "")
   If $iEnd < 0 Or $iEnd > $iUBound Or $iEnd <= 0 And $iStep > 0 Then $iEnd = $iUBound
   If $iStart < 0 Then $iStart = 0
   If $iStart > $iEnd And $iStep >= 1 Then Return SetError(2, 0, "")

   Local $aNewArray[$iUBound]

   For $i = $iStart To $iEnd Step $iStep ; Create a new zero based array
      $aNewArray[$iNew] = $avArray[$i]
      $iNew +=1
   Next

   ReDim $aNewArray[$iNew]

   Return $aNewArray
EndFunc   ;==>_ArraySlice

_ArraySlice.au3

Edited by Decipher
Spoiler

censored.jpg

 

Link to comment
Share on other sites

I don't mean to bump this thread but really guies no comments whatsoever? I worked hard on this a little negative and positve critism is expected.

My only negative criticism is that you didn't give people a chance to reply. I have many threads in the examples section with no comments as well but I don't mind, especially when you posted this only 8 hours ago.

Edit: Changed last part as it could have been construed as being hostile

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

That was an slightly expected response. The UDF? I'm new to the forums. Hmm.. 8 hours isn't long enough then maybe I overestimated the size of the community.

Edited by Decipher
Spoiler

censored.jpg

 

Link to comment
Share on other sites

For me you wrote in the middle of the night. How can I respond while I am sleeping?

This UDF surely can be useful, but why are you creating a string and split it again? Since you already have a loop, you could just fill a new array directly.

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Link to comment
Share on other sites

For me you wrote in the middle of the night. How can I respond while I am sleeping?

This UDF surely can be useful, but why are you creating a string and split it again? Since you already have a loop, you could just fill a new array directly.

Thanks, I'll rewrite it. You did respond didn't you? I didn't think of just creating another array instead of the stringsplit. I was going for what was simplicit and effective for me at the time. I just thought to share it.

Spoiler

censored.jpg

 

Link to comment
Share on other sites

Change

$sDelim = "-[Index|Delim]-"
to
$sDelim = Chr(01)
due to the fact if someone has the string '-[index|Delim]-' will yield incorrect results.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Change

$sDelim = "-[Index|Delim]-"
to
$sDelim = Chr(01)
due to the fact if someone has the string '-[index|Delim]-' will yield incorrect results.

Thanks, would you directly create a new array that would require more code or use the array to stingsplit method?

Advantages/Dis...

Spoiler

censored.jpg

 

Link to comment
Share on other sites

I would create a new array myself, but then I haven't done any speed tests on whether this would increase the execution time.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Thanks, I'll rewrite it. You did respond didn't you? I didn't think of just creating another array instead of the stringsplit. I was going for what was simplicit and effective for me at the time. I just thought to share it.

I'm awake now ;) Yes, it seems to be a simple method, but using arrays directly is not more effort and keeps the variable types intact (e.g. a HWnd is not converted to a string)
Local $aResult[$iEnd-$iStart+1]
    ; Combine
    For $i = $iStart To $iEnd Step $iStep
        $aResult[$i-$iStart] = $avArray[$i]
    Next
    Return $aResult
Edited by ProgAndy

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Link to comment
Share on other sites

I'm awake now Posted Image Yes, it seems to be a simple method, but using arrays directly is not more effort and keeps the variable types intact (e.g. a HWnd is not converted to a string)

Local $aResult[$iEnd-$iStart+1]
    ; Combine
    For $i = $iStart To $iEnd Step $iStep
        $aResult[$i-$iStart] = $avArray[$i]
    Next
    Return $aResult

You make a great point. I'm working on it currently. Edited by Decipher
Spoiler

censored.jpg

 

Link to comment
Share on other sites

I wonder if using redim to increase the array size by one each iteration could possibly be a bad techinque?

Func _ArraySlice(Const ByRef $avArray, $iStart = 0, $iEnd = 0, $iStep = 1)
   If Not IsArray($avArray) Then Return SetError(1, 0, 0)
   If UBound($avArray, 0) <> 1 Then Return SetError(3, 0, "")
   Local $iNew = 1, $iUBound = UBound($avArray) - 1
   ; Bounds checking
   If $iStep > $iUBound Then Return SetError(4, 0, "")
   If $iEnd < 0 Or $iEnd > $iUBound Or $iEnd <= 0 And $iStep > 0 Then $iEnd = $iUBound
   If $iStart < 0 Then $iStart = 0
   If $iStart > $iEnd And $iStep >= 1 Then Return SetError(2, 0, "")
   Local $aNewArray[$iNew]
   For $i = $iStart To $iEnd Step $iStep
   $aNewArray[$iNew-1] = $avArray[$i]
   $iNew +=1
   ReDim $aNewArray[$iNew]
   Next
   ReDim $aNewArray[$iNew-1]
   Return $aNewArray
EndFunc   ;==>_ArraySlice
Edited by Decipher
Spoiler

censored.jpg

 

Link to comment
Share on other sites

  • Moderators

Decipher,

I wonder if using redim to increase the array size my one each iteration could possibly be a bad techinque?

Yes, ReDim is one of the slowest Array functions. :)

You might want to look at the tip I gave at the bottom of this tutorial to see how you might do it more efficiently. ;)

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

Decipher,

Yes, ReDim is one of the slowest Array functions. :)

You might want to look at the tip I gave at the bottom of this tutorial to see how you might do it more efficiently. :)

M23

Updated. ;)

Edited by Decipher
Spoiler

censored.jpg

 

Link to comment
Share on other sites

  • 4 years later...

This is a good function ,liked

one question : how can I make the new array include array[0] = count 
or add "count" to any array  ..


Thanks

 

EDIT: resolved to using:

_ArrayInsert($aNewArray, 0, UBound($aNewArray))

 

Edited by Deye
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...