# Analysis of the realization method of Golang algorithm for Tianji Horse racing problem

• 2020-06-07 04:37:40
• OfStack

An example of Golang algorithm is presented in this paper. To share for your reference, specific as follows:

Tian Ji Horse Racing Problem

Input:

Enter multiple sets of test data. Each set of test data includes 3 rows:
Enter N(1≤N≤1000) in line 1 to indicate the number of horses.
The second line has N integer Numbers, i.e., the speed of yuanzi's N horse (large Numbers indicate fast speed).
Line 3 has the N integer number, the speed of the opponent's N horse.
Exit when N is 0.

Output:

If you can win the race (by more than half of the total number of RACES), then output "YES". Otherwise output "NO".

The sample input

5
2 3 3 4 5
1 2 3 4 5
4
2 2 1 2
2 2 3 1
0

Sample output

YES
NO

Code implementation (Golang) :

``````package huawei
//Date : 2015-8-14 15:43:11
import (
"fmt"
"io/ioutil"
"sort"
"strings"
)
// Idea: Use your strongest ( Half of the +1) A horse and the weakest opponent ( Half of the +1) A horse race
func Test11Base() {
strs := strings.Split(string(data), "\n")
index := 0
for {
count := strs[index]
if count == "0" {
break
}
teamA := convertToIntSlice(strings.Fields(strs[index+1]))
teamB := convertToIntSlice(strings.Fields(strs[index+2]))
if canWin(teamA, teamB) {
fmt.Println("YES")
} else {
fmt.Println("NO")
}
index += 3
}
}
// judge teamA Can we win
func canWin(teamA []int, teamB []int) bool {
sort.Ints(teamA)
sort.Ints(teamB)
length := len(teamA)
tryCount := length/2 + 1
for i := 0; i < tryCount; i++ {
//A Group of the most powerful 1 And a half
speedA := teamA[length-(tryCount-i)]
//B Set the weakest 1 And a half
speedB := teamB[i]
if speedA <= speedB {
return false
}
}
return true
}``````