By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,848 Members | 1,363 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,848 IT Pros & Developers. It's quick & easy.

Arranging an array so that duplicates will turn up first

P: 1
Hi All,

I have an array that contains duplicates as well unique numbers.
ex- (21, 33, 35, 21, 33, 70, 33, 35, 50)

I need to arrange it in such a way that all the duplicates will come up first followed by unique numbers.

Result for the given example should be:
(21, 21, 33, 33, 35, 35, 70, 50)

This a trivial problem in C, creating a binary search tree from the array solves the problem.

As I am new to Perl I don't know indepth of the language.
Would appreciate any help on this regard.

~Ashim
Jan 24 '08 #1
Share this Question
Share on Google+
3 Replies


KevinADC
Expert 2.5K+
P: 4,059
Hi All,

I have an array that contains duplicates as well unique numbers.
ex- (21, 33, 35, 21, 33, 70, 33, 35, 50)

I need to arrange it in such a way that all the duplicates will come up first followed by unique numbers.

Result for the given example should be:
(21, 21, 33, 33, 35, 35, 70, 50)

This a trivial problem in C, creating a binary search tree from the array solves the problem.

As I am new to Perl I don't know indepth of the language.
Would appreciate any help on this regard.


~Ashim
All you have to do is sort the array numerically.

Expand|Select|Wrap|Line Numbers
  1. @sorted_list = sort {$a <=> $b} @unsoted_list;
See the sort() man page for details or the "Sorting Data with Perl - Part One" article in the Howto section of this website.
Jan 24 '08 #2

KevinADC
Expert 2.5K+
P: 4,059
On second look, I think I misunderstood your requirements. The sample data will sort as needed just by sorting it numerically, but real data probably will not. A hash of arrays would work.
Jan 24 '08 #3

nithinpes
Expert 100+
P: 410
Ashim,
You can try the following script:
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. use warnings;
  3.  
  4. my @final; my @duplicates; my @single;
  5. my %hash=();
  6. my @a=(11,34,55,67,88,101,97,88,11,11,34,83,101,67); ##your array
  7.  
  8. foreach(@a)
  9. {
  10.  
  11.   if(exists $hash{$_})   ##check if the element was processed before
  12.   { 
  13.      push @{$hash{$_}},$_ ; 
  14.   } 
  15.  else {
  16.   $hash{$_}= [$_];
  17. }    
  18. }
  19.  
  20. foreach(keys %hash) {
  21. if(@{$hash{$_}}>1) {
  22. push @duplicates,@{$hash{$_}}; ##take duplicates into this array
  23. }
  24.  else {
  25. push @single,@{$hash{$_}}; ##take single elements in this array
  26. }
  27. }
  28. @final = sort {$a <=> $b} @duplicates;
  29. push @final,@single;
  30.  
  31. ###Result #####
  32. print "$_\t" foreach(@final);
  33.  
Jan 25 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.