Jump to content
yhu420

[SOLVED]Count duplicates in an array

Recommended Posts

Hello everyone,

I just have a beginner question: is there a way to count duplicates in an array? If you don't see what I mean, here is an example of what I mean:

$arr[5] = ['a', 'a', 'b', 'b', 'c'] ; the array

countDuplicates($arr); Representing the data in a bidimensionnal array, this would return:

#cs
['a'][2]
['b'][2]
['c'][1]

Of course this is a bit messy, but that's just for you to get the idea
#ce

I'm trying to achieve this to check whether yes or no an array has more or same amount of occurrences of a character than another array.

Am I doing this the right way?

Does such a function exist?

Thanks for everything :)

Spoiler
Spoiler

 

Edited by yhu420
added solved tag

Share this post


Link to post
Share on other sites

There is no func (@Dev's please correct when wrong) to this job. But you can solve like this:

#include <Array.au3>

$txt = ""
For $i=0 to 100
    $txt &= Random(1,30,1)&@CRLF
Next



;$txt = FileRead('test.txt') ;if txt is ia in a file

;startpoint
;ConsoleWrite($txt & @CRLF)
_ArrayDisplay(_countUniqueNumbers($txt), '_countUniqueNumbers')

Func _countUniqueNumbers($sText='Test', $sDelim=@CRLF)
    ;ConsoleWrite($sText & @CRLF)
    ;returns the count of each unique number in a String
    ;autor: autobert (autoit.de) 11/2009
    $sText = @CRLF&StringReplace($sText, ' ', '')
    $sText = StringReplace($sText, $sDelim, $sDelim & ' ')
    $aSource = StringSplit($sText, $sDelim, 3)
    _ArrayDelete($aSource, 0)
    ;_ArrayDisplay($aSource,'Original')
    $aUnique = _ArrayUnique($aSource)
    _ArrayDelete($aUnique, 0)
    Dim $aUnique2D[UBound($aUnique)][2]
    For $x = UBound($aUnique) - 1 To 0 Step -1
        $aUnique2D[$x][0] = $aUnique[$x]
        StringReplace($sText, $aUnique[$x] & $sDelim, 'a')
        $aUnique2D[$x][1] = @extended
        If StringStripWS($aUnique2D[$x][0],8)='' Then _ArrayDelete($aUnique2D,$x)
    Next
    _ArraySort($aUnique2D)
    Return $aUnique2D
EndFunc   ;==>_countUniqueNumbers

 

Share this post


Link to post
Share on other sites

Try this :

#Include <Array.au3>

Local $arr = ['a', 'a', 'b', 'b', 'c', 'e', 'f', 'a'] 
Local $aDup = _ArrayCountOcc($arr, 2)
_ArrayDisplay($aDup)

; iOrdByNumber = 0 : Do not sort
;                1 : Sort by number of occurences
;                2 : Sort by number of occurences, in descending order
Func _ArrayCountOcc($aArray, $iOrdByNumber = 0)
    If UBound($aArray, 0) <> 1 Then Return SetError(1, 0, 0)
    If Not IsInt($iOrdByNumber) Or $iOrdByNumber < 0 Or $iOrdByNumber > 2 Then Return SetError(2, 0, 0)
    Local $aRet[UBound($aArray)][2], $last, $iIndex = 0
    _ArraySort($aArray)
    For $i = 0 To UBound($aArray) - 1
        If $aArray[$i] = $last And $i <> 0 Then
            $aRet[$iIndex - 1][1] += 1
        Else
            $aRet[$iIndex][0] = $aArray[$i]
            $aRet[$iIndex][1] = 1
            $last = $aArray[$i]
            $iIndex += 1
        EndIf
    Next
    Redim $aRet[$iIndex][2]
    If $iOrdByNumber Then _ArraySort($aRet, ($iOrdByNumber = 2 ? 1 : 0), 0, 0, 1)
    Return $aRet
EndFunc

 

Edited by jguinch

Share this post


Link to post
Share on other sites

Sorry first example was to count in text, this one is for counting in array:

#include <Array.au3>

#cs
Dim $aArray[101]
For $i=0 to 100
    $aArray[$i] = Random(1,30,1)
Next
#ce
Local $aArray[5]    = ["a", "a", "b", "b", "c"]
_ArrayDisplay(_countUniqueElements($aArray), '_countUniqueElements')

Func _countUniqueElements($aSource)
    ;returns the count of each unique element in a Array
    ;autor: autobert
    Local $aUnique = _ArrayUnique($aSource)
    _ArrayDelete($aUnique, 0)   
    Dim $aUnique2D[UBound($aUnique)][2]
    For $x = 0 to UBound($aUnique) - 1 
        $aUnique2D[$x][0] = $aUnique[$x]
        $aCount=_ArrayFindAll($aSource,$aUnique[$x])
        $aUnique2D[$x][1] = UBound($aCount)
    Next
    _ArraySort($aUnique2D)
    Return $aUnique2D
EndFunc   ;==>_countUniqueElements^

 

Share this post


Link to post
Share on other sites
#include<array.au3>

Local $aArray[8]    = ["a", "a", "b", "b", "c" , "c" , "c" , "d"]

Local $aOut[0][2]

for $i = ubound($aArray) - 1 to 0 step -1
        $aFound = _ArrayFindAll($aArray , $aArray[$i])
        _ArrayAdd($aOut , $aArray[$aFound[0]] & "|" & ubound($aFound) ,  0)
        _ArrayDelete($aArray , _ArrayToString($aFound , ";"))
        $i -= ubound($aFound) - 1
next

_ArrayDisplay($aOut)

 


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

Share this post


Link to post
Share on other sites

First of all, sorry for the late reply.

Thanks to all of you who answered, I feel sorry for posting a duplicate thread, but I hope I will help out people asking the same question.

Special thanks to iamtheky, his solution seemed the most effective and everything indeed works fine :D

Thanks again to all of you for helping me out!

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

  • Similar Content

    • By sksbir
      Hi
      Trying this from autoit v3.3.14.5 and SCITE 3.19.102.1901.0 :
      help file , page "Language Reference - Variables" , sample autoit script about maps:

      Maps must be declared before use by defining their scope using the 'Global/Local/Static' keywords. Local $mControls[]
      So is my test script : only with this local declation.
      -check syntax is OK
      - running script : 

      test.au3" (13) : ==> Variable subscript badly formatted.: Local $mControls[] Local $mControls[^ ERROR ->14:51:49 AutoIt3.exe ended.rc:1
      any clue ?
    • By MightyWeird
      Hello,
       
      I am alwasy struggeling to do multiple things  at the same time.
      I have a main screen with a button which calls the function ninite1.
      The function "ninite1" then executes and fires a new gui.
      The program start to run with the gui (test) in the back ground
       
      Now I would like to have a counter (_count() which shows how long this program is running within this gui (ninitegui)
      Somebody?
       
      #include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> #include <StaticConstants.au3> #include <ColorConstantS.au3> #include <EditConstants.au3> #include <WindowsConstants.au3> #include <ButtonConstants.au3> #include <InetConstants.au3> _ninite1() Func _ninite1() GLOBAL $count = 0 Local $NINITEGUI = GUICreate("Runtimes", @DesktopWidth, @DesktopHeight, 0, 0, $WS_POPUP) Local $idLabel2 = GUICtrlCreateLabel("test", 600, 150, @DesktopWidth, 150) GLOBAL $lblData = GuICtrlCreateLabel("", 40, 40,50,50) _Count() Sleep(1000) GUISetState(@SW_SHOW, $NINITEGUI) Run(@ScriptDir & "\Resources" & "\Runtime\ninite.exe") ;Run(@ScriptDir & "\Resources" & "\Runtime\vlcetc.exe") While 1 If ControlCommand("Ninite", "Close", "[CLASS:Button; INSTANCE:1]", "IsEnabled", "") Then ControlClick("Ninite", "Close", 2) Sleep(15) ; Important or you eat all the CPU which will not help the defrag! ExitLoop EndIf WEnd GUIDelete($NINITEGUI) EndFunc ;==>_ninite1 Func _Count() For $i = $count To 100 GuiCtrlSetData($lblData, $i) Sleep(1000) Next EndFunc  
    • By rm4453
      Hello,
       
      I am tasked with creating a program that will scan a window for an image, if the image is detected it will need to click it, and download it. (I can handle the download part)
       
      I have attempted searching online, with no avail.
      The closest thing I have found is the following:
      https://www.autoitscript.com/forum/topic/189338-imagesearchau3-help/
      I attempted to run the sample / example provided by Danyfirex which the post owner claimed worked for him.
      I receive no output back from Scite, and am unable to get it working.
       
      *what shows in console after attempting to run (Yes I tried running Scite as Admin):
      >"C:\Users\rmatt\OneDrive\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Users\rmatt\OneDrive\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\rmatt\OneDrive\Autoit Projects\GMR Auto Logger\GMR Auto Logger - LUA.au3" /UserParams >Exit code: 1 Time: 0.1236  
    • By Blitzkid
      Hello, i want to search several directories for files with the largest numbers behind them (Like "video123") . They dont have a datatype. But there are also files with longer names and datatypes in these folders (Like "video778.mp4"). Is it possible to filter the _FileListToArray Syntax from
      to smth. like
       
      Here is my Code
      #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <array.au3> #include <File.au3> $filedir = @ScriptDir & "\" _checkfile() Func _checkfile() ConsoleWrite("______________________" & @CRLF) Local $arr[3] = ["music", "picture", "video"] For $i = 0 To UBound($arr) - 1 Local $arrayfiles = _FileListToArray($filedir & $arr[$i], $arr[$i] & "*", 1) If @error = 1 Then ConsoleWrite($arr[$i] & "Error 1") EndIf If @error = 4 Then ConsoleWrite($arr[$i] & "Error 2") ;Exit EndIf $arrayfilter = _ArrayMax($arrayfiles, 0, 1) Global $stringfiles = StringReplace($arrayfilter, $arr[$i], "") ConsoleWrite($arrayfilter & @CRLF) Next EndFunc ;==>_checkfile  
    • By GHOSTYAIRO
      Hi, I haven't used Autoit in like 3 years so I'm not sure if something has changed and I'm doing something wrong but the Send() function is not working for me. I'm trying to send 4 Tabs then 2 Enters then some text. I thought it could be the window I'm working with so I just did a simple test and the keys are not being sent.
      Run("C:\WINDOWS\system32\notepad.exe") WinWait("Untitled - Notepad",0.0) WinActivate("Untitled - Notepad",0.0) WinWaitActive("Untitled - Notepad",0.0) Sleep(3) Send("{TAB}",0) Send("test",0) Send("t",0) Send("e",0) Send("s",0) Send("t",0) Notepad opens fine but then it just sits there. This is the output log:
       
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "E:\AutoIt Projects\test.au3" /UserParams +>16:03:41 Starting AutoIt3Wrapper v.19.102.1901.0 SciTE v.4.1.2.0 Keyboard:00000409 OS:WIN_10/ CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\User\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\User\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:E:\AutoIt Projects\test.au3 +>16:03:41 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "E:\AutoIt Projects\test.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop >Process failed to respond; forcing abrupt termination... >Exit code: 1 Time: 11.86 I have to stop it because it doesn't do anything at all.
      I already tried to use sleep thinking it was sending the keys too fast but no dice.
      Thanks for your help.
×
×
  • Create New...