Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

remove repeating elements in array

Status
Not open for further replies.

mani5int

Programmer
Dec 15, 2007
1
US
hi people can any one tell me how do i remove elements in an array which repeat more than 4 times
i tried this for single time but how do i get it for 4 times
%seen = ();
@unique = ();

for each $elem (@array)
next if $seen{$elem}++
push @unique, $elem (@array)

plzzzzzz help me in this regard
 
That's using a hash to remove duplicates, but for what you want you need to walk a sorted array, and if the element occurs more than 4 times, splice it from the array

Code:
sort @array;
$last_seen='';
for (@array) {
  if ($last_seen eq $_) {
    $counter++;
    if ($counter >=4 ) {
      #I'll leave the splicing up to the reader
    }
    $last_seen=$_;
  } else {
    $last_seen=$_;
    $counter=1;
  }
}
Not tested ...

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
your question is vague, can you give an example of what you mean?

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I read your question as having two possible meanings:

1: Remove the 5th and onward duplicates, leaving the first 4 in the array

Code:
foreach $val (@array) {
  push @deduped, $val if $seen{$val}++ <4;
}

This is simply an extension of the original code, pushing 'as we go'.

2: Remove all matching elements that have 5 or more repetitions.

Code:
$seen{$_}++ foreach (@array);
@deduped = grep{ $seen{$_}<=4 } @array;

This is a little different in that it populates the hash fully before creating the deduped array.
 
This would just be a variation of:

perlfaq4 - How do I remove duplicate elements from a list or array?

Code:
[url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]%seen[/blue] = [red]([/red][red])[/red][red];[/red]
[black][b]my[/b][/black] [blue]@filtered[/blue] = [url=http://perldoc.perl.org/functions/grep.html][black][b]grep[/b][/black][/url] [red]{[/red] [blue]$seen[/blue][red]{[/red] [blue]$_[/blue] [red]}[/red]++ < [fuchsia]4[/fuchsia] [red]}[/red] [blue]@array[/blue][red];[/red]

- Miller
 
Assign all the elements as keys in a hash, then extract the keys from the hash. The redundancies will cancel:


foreach ( @array ) {
$hash{$_} = 1;
}

@array = keys(%hash);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top