Table of Contents
Reply content:
Home Backend Development PHP Tutorial javascript - For Olympic medals, how to determine the national ranking according to the order of gold, silver and bronze (see the title for details)

javascript - For Olympic medals, how to determine the national ranking according to the order of gold, silver and bronze (see the title for details)

Oct 10, 2016 am 11:56 AM
c java javascript php python

The structure of the data is roughly like this

<code> $arr = [
          ['name'=>'国家一','score'=>[10,7,5]],
          ['name'=>'国家二','score'=>[10,9,5]],
          ['name'=>'国家三','score'=>[11,7,5]],
          ['name'=>'国家四','score'=>[10,7,9]],
        ];
</code>
Copy after login
Copy after login

The sorting rule is, gold medals are compared first, gold medals are always better than silver medals, silver medals are always better than bronze medals, bronze medals are always better than id, and id is the initial array sequence number

The three numbers in the score represent the amount of gold, silver and copper respectively

Those that require less use of built-in functions are best implemented in PHP

Reply content:

The structure of the data is roughly like this

<code> $arr = [
          ['name'=>'国家一','score'=>[10,7,5]],
          ['name'=>'国家二','score'=>[10,9,5]],
          ['name'=>'国家三','score'=>[11,7,5]],
          ['name'=>'国家四','score'=>[10,7,9]],
        ];
</code>
Copy after login
Copy after login

The sorting rule is, gold medals are compared first, gold medals are always better than silver medals, silver medals are always better than bronze medals, bronze medals are always better than id, and id is the initial array sequence number

The three numbers in the score represent the amount of gold, silver and copper respectively

Those that require less use of built-in functions are best implemented using PHP

There are three numbers that represent the number of medals. Can you at least tell me what the sorting rules are?

Is it the total number of medals? According to gold, silver and copper respectively? Or some strange permutation?


There are many ways. The lazy way is to compare four times directly. First sort by gold medal, select the ones with the same gold medal, and then sort by silver medal among the same ones... and so on

If you want to sort them at once, just change the gold, silver, and copper serial numbers into a number to sort them.
For example, your array can become like this——

<code>[010007005001,010009005002,011007005003,010007009004]</code>
Copy after login

The rules are very simple. Fill in the gold, silver, and copper serial numbers to three digits, then directly splice them together. Finally, just sort the group of numbers directly, and it will be done in one go.

PHP array_multisort implements sorting by multiple fields like SQL ORDER BY.
For example, the Olympic medal list is sorted in descending order by the number of gold medals, silver medals, and bronze medals.

<code><?php
header('Content-Type: text/plain; charset=utf-8');
$arr = array(
    '中国' => array(
        '金牌' => 8,
        '银牌' => 3,
        '铜牌' => 6,
    ),
    '俄罗斯' => array(
        '金牌' => 3,
        '银牌' => 6,
        '铜牌' => 3,
    ),
    '美国' => array(
        '金牌' => 6,
        '银牌' => 8,
        '铜牌' => 8,
    ),
    '澳大利亚' => array(
        '金牌' => 4,
        '银牌' => 0,
        '铜牌' => 4,
    ),
    '意大利' => array(
        '金牌' => 3,
        '银牌' => 4,
        '铜牌' => 2,
    ),

);
// 实现 ORDER BY
foreach($arr as $k => $v) {
    $sort['金牌'][$k] = $v['金牌'];
    $sort['银牌'][$k] = $v['银牌'];
    $sort['铜牌'][$k] = $v['铜牌'];
}
array_multisort(
    $sort['金牌'], SORT_DESC, 
    $sort['银牌'], SORT_DESC, 
    $sort['铜牌'], SORT_DESC, 
    $arr);
var_export($arr);</code>
Copy after login

Let’s make a python version, assuming that the number of each type of medals in each country will not exceed 999.

<code>arr = [
    {'name':'国家一','score':[10,7,5]},
    {'name':'国家二','score':[10,9,5]},
    {'name':'国家三','score':[11,7,5]},
    {'name':'国家四','score':[10,7,9]},
]

print sorted(arr, key=lambda a: '%03d%03d%03d' % tuple(a['score']), reverse=True)</code>
Copy after login

score is best separated when designing.
Design a class (including country, gold, silver, and bronze numbers), implement the Comparable interface, and implement the compare method according to the rules you described. Isn't it simple?

Gold Medal + Silver Medal + Bronze Medal + ID form a number and then sort it directly. For example, id13-[10, 2, 20] forms 10022013, and then sort it directly according to this number

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Apr 30, 2025 pm 07:24 PM

The built-in quantization tools on the exchange include: 1. Binance: Provides Binance Futures quantitative module, low handling fees, and supports AI-assisted transactions. 2. OKX (Ouyi): Supports multi-account management and intelligent order routing, and provides institutional-level risk control. The independent quantitative strategy platforms include: 3. 3Commas: drag-and-drop strategy generator, suitable for multi-platform hedging arbitrage. 4. Quadency: Professional-level algorithm strategy library, supporting customized risk thresholds. 5. Pionex: Built-in 16 preset strategy, low transaction fee. Vertical domain tools include: 6. Cryptohopper: cloud-based quantitative platform, supporting 150 technical indicators. 7. Bitsgap:

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How to rename a database in MySQL How to rename a database in MySQL Apr 29, 2025 pm 04:00 PM

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

What are the advantages of using Java for web applications that need to run on different servers? What are the advantages of using Java for web applications that need to run on different servers? May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

See all articles