Assume we have following tree:
1
9
2
13
3
10
4
15
5
11
6
14
7
12
8
Where elements(matches):
1-8 is round 1
9-12 is round 2
13-14 is round 3
15 is round 4
How I can determinate round of element "n" in shuch tree?
My current formulas are:
total_rounds = floor(log(totalTeams,2));
matches_per_round = (totalTeams / pow(2, current_round))
next_match_id = (totalTeams/2) + ceil(match_id/2)
total_matches = total_teams - 1
Imagine the tree was numbered in reverse.
15
7
14
3
13
6
12
1
11
5
10
2
9
4
8
In that case, it'd simply be the logarithm of the number, rounded down. Now we simply subtract this number from the number of rounds, and we're done.
reverse_number = total_matches - match_number + 1;
reverse_match_round = floor(log(reverse_number, 2));
match_round = total_rounds - match_round;
(Note, reverse_match_round
is actually 0-indexed, unlike match_round. However, since we subtract it from total_rounds
, it's easier to keep it that way than to 1-index it. If you prefer it 1-indexed, simply add +1
to each of the last two lines.)