phatzilla

Getting unique elements from 2D arrays

18 posts in this topic

#1 ·  Posted (edited)

I'm back begging for more help.

say i have a 2d array (read from file)with ":" as a delimeter

87000026:abc
87000090:def
87000021:ghi
87000027:def
87000089:abc
87000028:abc
87000094:def

The output should be

87000021:ghi
87000028:abc
87000094:def

So i want to get rid of the all duplicates in column 2 (except the LAST one), while maintaining the corresponding string in column 1.

_arrayunique only creates a new 1d array of either column 1 or 2, not both...  Keep in mind this will be used on files with over 1M lines...

Edited by phatzilla

Share this post


Link to post
Share on other sites



Ha! In fact your problem turns out to be a bit more complex than the first thread said.

Still you can get by with the scripting dictionary. Since it's a key/value store, you can store the second column in the key and the first column in the value.

Then if the key is found, update the value field, else store both key and value.


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

Actually, this is a separate issue from the other thread ;)

Share this post


Link to post
Share on other sites

This one works with your example

#include <Array.au3>
#include <File.au3>

Local $a
_FileReadToArray("1.txt", $a, 0, ":")
_ArrayDisplay($a, "array")

Local $sda = ObjCreate("Scripting.Dictionary")
For $i = UBound($a)-1 to 0 step -1
    $sda.add($a[$i][1], $a[$i][0])
Next
Local $count = $sda.Count, $res[$count][2]
For $i = 0 to $count-1
   $res[$i][0] = $sda.Item($sda.Keys[$count-$i-1])
   $res[$i][1] = $sda.Keys[$count-$i-1]
Next
_ArrayDisplay($res, "result")

 

Share this post


Link to post
Share on other sites

If you can stringsplit on just @LF and leave it 1D, you could

#include<array.au3>

$s= "87000026:abc" & @LF & _
"87000090:def"  & @LF & _
"87000021:ghi"  & @LF & _
"87000027:def" & @LF & _
"87000089:abc" & @LF & _
"87000028:abc" & @LF & _
"87000094:def"

$a = stringsplit($s , @LF , 2)

for $i = ubound($a) - 1 to 0 step - 1
    $tgt = stringright($a[$i] , 3)
        For $x = $i - 1 to 0 step - 1
            If stringright($a[$x] , 3) = $tgt Then
                _ArrayDelete($a , $x)
                $i -= 1
            EndIf
        Next
next

_arraydisplay($a)

 


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

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

This one works with your example

#include <Array.au3>
#include <File.au3>

Local $a
_FileReadToArray("1.txt", $a, 0, ":")
_ArrayDisplay($a, "array")

Local $sda = ObjCreate("Scripting.Dictionary")
For $i = UBound($a)-1 to 0 step -1
    $sda.add($a[$i][1], $a[$i][0])
Next
Local $count = $sda.Count, $res[$count][2]
For $i = 0 to $count-1
   $res[$i][0] = $sda.Item($sda.Keys[$count-$i-1])
   $res[$i][1] = $sda.Keys[$count-$i-1]
Next
_ArrayDisplay($res, "result")

 

 

Hi mikell,

 

It appears your solution works, however i tested with a dataset of ~6k lines, and it took about 25 seconds....  

Im working with over 1M lines here, so i don't know if its viable.  Is there anyway to greatly optimize this, or is it just a fact i'll have to deal with?

I guess in theory i will have to scan 1,000,000 * 1,000,000 array elements -- which is quite a bit, so maybe im screwed.  Unless there's a way to systematically break it down to smaller arrays of 1000 * 1000 and then combine or something...   Another thing that's worth mentioning is that column 1 contains no duplicates, it's only column 2 which does.

Edited by phatzilla

Share this post


Link to post
Share on other sites

Then just enter them backwards into the dictionary with no further checks, as duplicate keys will error? If that dedup eliminates a large percentage, reading the dictionary backwards should be quicker.


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

Share this post


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

Global $sInput = _
"87000026:abc" & @CRLF & _
"87000090:def"  & @CRLF & _
"87000021:ghi"  & @CRLF & _
"87000027:def" & @CRLF & _
"87000089:abc" & @CRLF & _
"87000028:abc" & @CRLF & _
"87000094:def"

Global $aSplit = StringSplit(StringStripCR($sInput), @LF, 2)
Global $aResult[UBound($aSplit)][2], $c
For $i = 0 To UBound($aSplit) - 1
    If _ArraySearch($aSplit, StringRegExpReplace($aSplit[$i], ".+\:(.+)", "$1"), $i + 1, 0, 0, 1) = -1 Then
        $aResult[$c][0] = StringRegExpReplace($aSplit[$i], "(.+)\:.+", "$1")
        $aResult[$c][1] = StringRegExpReplace($aSplit[$i], ".+\:(.+)", "$1")
        $c += 1
    EndIf
Next
ReDim $aResult[$c][2]
_ArrayDisplay($aResult)

 


Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post


Link to post
Share on other sites

Another way, directly from the text using a regex :

#include <Array.au3>

Global $sInput = _
"87000026:abc" & @CRLF & _
"87000090:def"  & @CRLF & _
"87000021:ghi"  & @CRLF & _
"87000027:def" & @CRLF & _
"87000089:abc" & @CRLF & _
"87000028:abc" & @CRLF & _
"87000094:def"

Local $aUniqs = StringRegExp($sInput, "((\V+:(\V+))(?:\R|$))(?!(?1)*\V+:\3)", 3)
Local $aResult[UBound($aUniqs) / 3][2]

For $i = 0 To UBound($aUniqs) - 1 Step 3
    $aResult[$i / 3][0] = StringRegExpReplace($aUniqs[$i + 1], ":.+", "")
    $aResult[$i / 3][1] = StringRegExpReplace($aUniqs[$i + 1], ".+:", "")
Next

_ArrayDisplay($aResult)

 

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

With 1M lines maybe it's worth to try SQlite  :sweating:

Edit
Argh I didn't see the post from kylomas in the othe thread...

Edited by mikell

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

With 1M lines maybe it's worth to try SQlite  :sweating:

Edit
Argh I didn't see the post from kylomas in the othe thread...

 

unfortunately his solution doesn't necessarily apply to the problem i presented in this thread, rather the problem you had already helped me solve in the other thread

Edited by phatzilla

Share this post


Link to post
Share on other sites

phatzilla,

So i want to get rid of the all duplicates in column 2 (except the LAST one), while maintaining the corresponding string in column 1.

"LAST one" by order of appearance? 


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

phatzilla,

Try this (follows jchd's advice).  I added some timings to detect where you bog down...

#include <Array.au3>
#include <File.au3>

Local $a, $st = timerinit()

_FileReadToArray(@scriptdir & "\test.txt", $a, 0, ":")
ConsoleWrite('Time to load array from file = ' & round(timerdiff($st)/1000,4) & @CRLF)
_ArrayDisplay($a, "array")

$st = timerinit()
Local $sda = ObjCreate("Scripting.Dictionary")
if @ERROR then exit msgbox(17,'','ERROR getting object')

For $i = 0 to ubound($a) - 1
    if not $sda.exists($a[$i][1]) then
        $sda.add($a[$i][1], $a[$i][0])
    Else
        $sda.item($a[$i][1]) = $a[$i][0]
    endif

Next

ConsoleWrite('Time to load dictionary = ' & round(timerdiff($st)/1000,4) & @CRLF)

$st = timerinit()
Local $keys = $sda.keys(), $res[$sda.count()][2]
For $i = 0 to ubound($keys) - 1
   $res[$i][0] = $sda.Item($keys[$i])
   $res[$i][1] = $keys[$i]
Next

ConsoleWrite('Time to load unique array = ' & round(timerdiff($st)/1000,4) & @CRLF)

_ArrayDisplay($res, "result")

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

You may speed it up further with a fileopen and the returning on @error may be dirty, but hopefully this is a decent example of letting the dictionary fail out the duplicates.

 

#include<array.au3>
#include<file.au3>



$st = timerinit()

$mTest = _MapFromFile_Rev("test.txt")

ConsoleWrite('Time to load unique dictionary with entries reversed ' & round(timerdiff($st)/1000,4) & @CRLF)

$st = timerinit()


$aTest = _MapTo2dArray_Rev($mTest)

ConsoleWrite('Time to read them out backwards into array = ' & round(timerdiff($st)/1000,4) & @CRLF)

_ArrayDisplay($aTest)



Func _MapFromFile_Rev($filepath)
Local $map = ObjCreate("Scripting.Dictionary")
Local $i = 0
$max = _FileCountLines($filepath)

    do
      $a = stringsplit(filereadline($filepath , $max - $i) , ":" , 2)
      If @error Then return $map
    _MapAddKeyValuePair($map , $a[1] , $a[0])
    $i += 1

    until $max - 1 = 1

return $map

EndFunc ;_MapToArray

Func _MapTo2dArray_Rev($map)
local $aArray[$map.count][2]

    $i = 0
    for $key in $map.Keys
        $aArray[$i][1] = $key
        $aArray[$i][0] = $map.Item($key)
        $i += 1
    Next

return $aArray
EndFunc ;_MapTo2dArray

Func _MapAddKeyValuePair($map , $key , $value)
    If $map.Exists($key) Then
       return 0
    Else
        $map.Add($key, $value)
    EndIf
EndFunc ;_MapAddKeyValuePair

                         

Edited by boththose

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

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

phatzilla,

"LAST one" by order of appearance? 

 

Yes, last one as it appears in the text file.  Im currently trying the solutions presented in this thread, will report back

update1: kylomas, your script's performance (based on 3M lines file)

Time to load array from file = 21.6615
Time to load dictionary = 95.1497
Time to load unique array = 23.6044

Not bad ;), i thought it'd take longer!

Edited by phatzilla

Share this post


Link to post
Share on other sites

#17 ·  Posted (edited)

kylomas,
This should be a little faster (?)

For $i = 0 to ubound($a) - 1
  ;  if not $sda.exists($a[$i][1]) then
  ;      $sda.add($a[$i][1], $a[$i][0])
  ;  Else
        $sda.item($a[$i][1]) = $a[$i][0]
  ;  endif
Next

Edit
Playing with SD features  :D

Edited by mikell

Share this post


Link to post
Share on other sites

How many unique lines remain on average?


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

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