Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Extracting Unique Characters from a Array

by rsriram (Hermit)
on Sep 07, 2006 at 17:08 UTC ( #571748=note: print w/ replies, xml ) Need Help??


in reply to Extracting Unique Characters from a Array

Hi, Assuming that your array of numbers is:

@array= qw/10 10 48 22 34 54 23 65 22/;

The easiest way to do it is first sort the array

@sarray=sort(@array);

Now I am checking through every element in the array and storing it to a variable $last_element. The current element will be stored in $i. In the if condition, I am checking if the current element is equal to the last element and if the condition is false, I am printing the element. And here is the code:

@array= qw/10 10 48 22 34 54 23 65 22/; @sarray=sort(@array); my $last_element = ""; foreach $i (@sarray) { if ($last_element ne $i) { print "$i\n"; $last_element = $i; } }

You can have answers for these types of questions at Super search.


Comment on Re: Extracting Unique Characters from a Array
Select or Download Code
Re^2: Extracting Unique Characters from a Array
by ps (Initiate) on Sep 07, 2006 at 17:21 UTC

    Hi,

    Thank you, your code works well!! But I am still unable to understand your logic on how you are using $i and $last_element. Can you explain it to me further?

Re^2: Extracting Unique Characters from a Array
by Fletch (Chancellor) on Sep 07, 2006 at 17:24 UTC

    Yeah, let's turn a single O(n) scan with a hash (the right way to do it) into an O(n log n) sort followed by another O(n) scan. Aside from the added inefficiency you've lost the original ordering if that needed to be preserved.

    Update: Ah, a followup did note that the list was to be sorted. Still makes more sense to do the O(n) cull of duplicates first and then the O(n log n) sort of the smaller list.

    When in doubt:

    #!/usr/bin/perl use Benchmark qw( timethese cmpthese ); use constant SIZE => 6_000; use constant COUNT => 500; my $count = shift || COUNT; my $size = shift || SIZE; my @source = map { int( rand($size) ) } 1 .. $size; cmpthese( $count, { sort_first => sub { my @sorted = sort @source; my $le = undef; my @uniq; for (@sorted) { if ( $le != $_ ) { $le = $_; push @uniq, $_; } } }, cull_first => sub { my %seen; my @uniq = grep { !$seen{$_}++ } @source; my @sorted = sort @uniq; } } ); exit 0; __END__

    The cull_first version is from 8-20% faster for lists of from 5 to several thousand items.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://571748]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (13)
As of 2014-09-16 20:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (47 votes), past polls