Think about Loose Coupling PerlMonks

### Re: Finding unique elements in an array

by pelagic (Priest)
 on Mar 15, 2005 at 13:28 UTC ( #439619=note: print w/replies, xml ) Need Help??

in reply to Finding unique elements in an array

Please ignore:
I don't remember where I pinched this one, it might have been around here somewhere ;-)
This shows some different ways to do it and benchmarks:
use Benchmark; my @list; for ( 0..9999 ) { push @list, sprintf "%d", 100 * rand ; } timethese( 1000, { 'keys_map_1' => sub { my @uniq = keys %{{ map {\$_ => 1} + @list }}; }, 'keys_map_undef' => sub { my @uniq = keys %{{ map {\$_ => un +def} @list }}; }, 'grep_seen' => sub { my %seen; my @uniq = grep ! \$seen +{\$_}++, @list; }, } ); __END__ Benchmark: timing 1000 iterations of grep_seen, keys_map_1, keys_map_u +ndef... grep_seen: 15 wallclock secs (14.86 usr + 0.01 sys = 14.87 CPU) +@ 67.23/s (n=1000) keys_map_1: 50 wallclock secs (46.78 usr + 0.83 sys = 47.61 CPU) +@ 21.00/s (n=1000) keys_map_undef: 43 wallclock secs (42.16 usr + 0.94 sys = 43.09 CPU) +@ 23.21/s (n=1000)
The benchmark results are very much dependant of the size of the array. I took a 10,000 items array as an example.

Update:
To post something reasonable that does implement uniq as in OP's question, here's my solution (somewhat similar to Joost's):
my @b = map {\$a[\$_] eq \$a[\$_ + 1] ? () : \$a[\$_]} 0..\$#a;

pelagic

Replies are listed 'Best First'.
Re^2: Finding unique elements in an array
by ikegami (Pope) on Mar 15, 2005 at 15:51 UTC
None of these perform the function of uniq as the parent requested. uniq only looks at the previous item, not all previous items.

Log In?
 Username: Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://439619]
help
Chatterbox?
and the voices are still...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2018-04-25 17:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (92 votes). Check out past polls.

Notices?