学生排名关联得分PHP代码

时间:2013-08-19 09:33:25

标签: php ranking

请帮我排名,例如:

std_no    score        rank  

 1        50           1
 4        45           2
 3        45           3
 2        45           4
 5        45           5
 6        30           6

上面的例子是正确的,但我想要这样。

std_no   score        rank  

 1       50            1
 4       45            3.5
 3       45            3.5
 2       45            3.5
 5       45            3.5
 6       30            6

我怎么得到3.5?公式排名。 2,3,4,5加上则除以4,这是相同等级45的数量。

1 个答案:

答案 0 :(得分:0)

因为没有指定标签或语言我选择perl(转换为php:http://www.cs.wcupa.edu/~rkline/perl2php/):

    #!/usr/bin/perl

    use strict;
    use warnings;
    use Data::Dumper;
    use Clone qw(clone);

    sub _minRank
    {
        my ($couple, $tmpInput)    = @_;
        my $minRank                = @$couple[1];

        foreach my $key (keys %{$tmpInput}) {
            my $StudentCouple = $tmpInput->{$key};

            if (@$StudentCouple[0] == @$couple[0] && @$StudentCouple[1] < $minRank) {
                $minRank = @$StudentCouple[1];
            }
        }
        return $minRank;
    }

    sub _maxRank
    {
        my ($couple, $tmpInput)    = @_;
        my $maxRank                = @$couple[1];

        foreach my $key (keys %{$tmpInput}) {
            my $StudentCouple = $tmpInput->{$key};

            if (@$StudentCouple[0] == @$couple[0] && @$StudentCouple[1] > $maxRank) {
                $maxRank = @$StudentCouple[1];
            }
        }
        return $maxRank;
    }

    sub _nbIteration
    {
        my ($couple, $tmpInput)    = @_;
        my $nbIteration            = 0;

        foreach my $key (keys %{$tmpInput}) {
            my $StudentCouple = $tmpInput->{$key};

            if (@$StudentCouple[0] == @$couple[0]) {
                $nbIteration++;
            }
        }

        return $nbIteration;
    }

    sub _computeRank
    {
        my ($couple, $tmpInput) = @_;

        my $tmpInput1   = $tmpInput;
        my $nbIteration = _nbIteration($couple, $tmpInput1);
        my $rank        = @$couple[1];

        if ($nbIteration > 1) {
            my $tmpInput2   = $tmpInput;
            my $minRank     = _minRank($couple, $tmpInput2);

            my $tmpInput3   = $tmpInput;
            my $maxRank     = _maxRank($couple, $tmpInput3);

            $rank = ($minRank + $maxRank) / 2;
        }

        return $rank;
    }

    #         Std_no => [score, rank]
    my %input = (  1 => [50, 1], 
                   4 => [45, 2], 
                   3 => [45, 3], 
                   2 => [45, 4],
                   5 => [45, 5], 
                   6 => [30, 6] );

    my %output = %{clone(\%input)};

    foreach my $key (keys %input) {
        my $StudentCouple  = $input{$key};
        my %tmpInput       = %input;
        my $outputCouple   = $output{$key};

        @$outputCouple[1] = _computeRank($StudentCouple, \%tmpInput);
    }

    print Dumper(\%output);

我希望它会帮助你。

警告!!这段代码没有优化!!