欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java田忌和齊威王各有三匹賽馬

Java程序設(shè)計(jì)中,經(jīng)常會(huì)用到一些傳統(tǒng)的算法問(wèn)題,比如田忌和齊威王的賽馬問(wèn)題。這個(gè)問(wèn)題的背景是,田忌和齊威王各有三匹賽馬,要進(jìn)行三場(chǎng)比賽,比賽的規(guī)則是每場(chǎng)比賽各自出一匹馬進(jìn)行比拼,贏一場(chǎng)得一分,平局不得分,輸了沒(méi)有得分。為了保持懸念,如果某次比賽打平,那么就用盡情況對(duì)方的最差馬與自己的最好馬比賽。

// Java代碼
public class Horse {
private String name;
private int speed;
public Horse(String name, int speed) {
this.name = name;
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public String toString() {
return name;
}
}

為了讓比賽更有意義,我們可以先將每位馬主手中的馬按照速度進(jìn)行排序,然后對(duì)比賽場(chǎng)數(shù)進(jìn)行貪婪選擇,優(yōu)先讓自己的最好馬與對(duì)方的最差馬比賽,這樣才能在賽場(chǎng)上立于不敗之地。

// Java代碼
public class Racing {
public static int match(Horse[] team1, Horse[] team2) {
Arrays.sort(team1, Comparator.comparing(Horse::getSpeed).reversed());
Arrays.sort(team2, Comparator.comparing(Horse::getSpeed).reversed());
int score = 0;
for (int i = 0, j = 0; i< team1.length && j< team2.length; ) {
if (team1[i].getSpeed() >team2[j].getSpeed()) {
score++;
i++;
j++;
} else {
if (team1[i].getSpeed()< team2[team2.length-1].getSpeed()) {
j++;
}
i++;
}
}
return score;
}
}

這個(gè)田忌和齊威王賽馬問(wèn)題看似簡(jiǎn)單,但其實(shí)涉及到了算法設(shè)計(jì)中的貪婪策略和排序算法等相關(guān)問(wèn)題。完整的Java代碼如上所示,有興趣的同學(xué)可以自行實(shí)現(xiàn)并嘗試優(yōu)化。