Match Table
Read full article from Match Table
Given n teams, output the game match table. The best team always match with the worst team.- Use Queue
For example, given n = 8, the result should be "(((1,8),(4,5)),((2,7),(3,6)))".
public String getMatchTable(int n) { assert n > 1 && isPow2(n); String[] teams = new String[n]; for (int i = 0; i < n; i++) { teams[i] = String.valueOf(i + 1); } while (n > 1) { for (int i = 0; i < n / 2; i++) { teams[i] = match(teams[i], teams[n - i - 1]); } n /= 2; } return teams[0]; } private boolean isPow2(int n) { return n > 0 && (n & (n - 1)) == 0; } private String match(String team1, String team2) { return String.format("(%s,%s)", team1, team2); }