in reply to wisdom needed: sorting an array

Hi monks, not sure if i explained my problem clearly enough, sorry! anyway i'll show you what i've done and it might make it easier to correct me. i am trying to count every number in $array[0] (shown below); all of the same numbers are the same thing (eg all the 1's are the same), i just need to know which occurs the most. i have tried counting every number etc but i cant seem to find which is the most frequent, i just get the number of numbers present returned to me. hope someone can help.
1 1 1 1 2 2 3 4 4 4
i want the number which occurs the most to be ranked at the top of the output (only one of each number needs to be ranked)
e.g 1 4 2 3
n.b
#! /usr/local/bin/perl -w use strict; my $num_of_params; $num_of_params = @ARGV; if ($num_of_params < 2) { die ("\n You haven't entered enough parameters !! \n\n"); } open (FILE, $ARGV[0]) or die "unable to open file"; open (OUTFILE, ">$ARGV[1]"); my $line; my @array; my $number; my $count=0; while (<FILE>) { $line = $_; chomp ($line); @array = (); @array = split (/\s+/, $line); foreach $number ($array[0]) { ++$count; print "$count\n"; print OUTFILE "$count\n"; if ($number != $number-1 ) { print "$number\n"; print OUTFILE "$number\n"; } } }

Replies are listed 'Best First'.
Re: Re: wisdom needed
by Juerd (Abbot) on Jun 06, 2002 at 10:43 UTC

    sub occurence { my %count; $count{$_}++ for @_; return sort { $count{$b} <=> $count{$a} } keys %count; } print "$_\n" for occurence qw(1 1 1 2 2 3 4 4 4 4);
    In the future, please reply to the node you're replying to (sounds logical, doesn't it?).

    - Yes, I reinvent wheels.
    - Spam: Visit eurotraQ.
    

Re: Re: wisdom needed
by marvell (Pilgrim) on Jun 06, 2002 at 10:50 UTC

    The principal of counting frequency is based on this type of code:

    my @array = (1,1,1,2,3,3,4,4,4,4); my %count; $count{$_}++ for @array; my @ordered = sort {$count{$b} <=> $count{$a}} keys %count; print map {"$_\n"} @ordered;

    The hash stores the count in the value and the item in the key. The keys are then sorted by comparing the values with eachother, with respect to the keys.

    --
    Steve Marvell

      thanks marvell, this runs well, but the only problem is that the output prints every number (i only want one of each number printed) it also prints every number again when it comes across a new number!! e.g
      @array = (1,1,1,1,2,2,3,3,3,4,4,4,5,5) OUTPUT 1 1 1 1 2 1 2 1 3 2 1 3 2 1 ETC
      I am also not sure if is printing the most frequent value at the top or not. any suggestions??? :-) the help so far is much appreciated.