Algorithm - How to implement score ranking using PHP, any good ideas?
世界只因有你
世界只因有你 2017-05-16 13:16:24
0
5
1206

Make a ranking of students' scores. The scores are an array. After ranking, the ranking results are output:
For example, $scores = array(90,100,100); Custom function implementation returns array $rank(3,1,1);

世界只因有你
世界只因有你

reply all(5)
过去多啦不再A梦

<?php

$arr = [99,100,100];
$arr1=$arr;
rsort($arr1);
$c=[];
 foreach ( $arr as $v){
     $b= array_search($v, $arr1);
     $c[]=$b+1;
 }
 print_r($c);

?>

This can meet your needs, but I have a question. The two are tied for first place. Shouldn’t the one who got 99 in the exam be the second place?

左手右手慢动作

What the questioner wants is to display the rankings in the order of the original array (can be tied). The general idea is to supplement the original array with position information, and then reversely construct the ranking array based on the sorted results. It’s a bit long to write out:

get_ranks(a[1:n])
  s ← array(n)
  ranks ← array(n)
  for i from 1 to n                 ▷ s[i] has record type
    s[i] ← {position: i, value: a[i], rank: 0}
  descending_sort(s by value)       ▷ sort by s[i].value
  s[1].rank ← 1
  for i from 2 to n
    if s[i].value < s[i-1].value    ▷ dense rank
      s[i].rank ← s[i-1].rank + 1
    else
      s[i].rank ← s[i-1].rank
  for i from 1 to n                 ▷ construct result
    ranks[s[i].position] ← s[i].rank
  return ranks[]
  

Note that if there are multiple nth people tied for the nth place, the next person will be the n+1th person, which is a bit different from the example given by the questioner. The complexity bottleneck of the entire algorithm is sorting, which is O(n lgn).

Ty80

Use PHP’s own array sorting function?

phpcn_u1582

http://www.php.net/manual/zh/...
The built-in data sorting should be able to solve your problem

我想大声告诉你

First sort this array by score, and then revsert this array. Then just get the key according to the score.

In addition: your scores are not written in the database, so they are taken out in order

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template