2013-08-19 38 views
0

請幫我在例如像公式排名:學生排名成績關係的PHP代碼

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.

+0

至少顯示你的代碼 –

+1

通常,4名同分的學生應該是全部第二,而不是3.5。 – goto

+1

std_no不應該是唯一的嗎?因爲這是2 std_no 1 –

回答

0

的量因爲沒有標籤或i指定選擇的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); 

我希望它能幫助你。

警告!這段代碼沒有優化!

相關問題