I am creating a simple bracket system and I need a way to check if there are a correct number of teams, OR if my program needs to compensate for bye rounds.
Right now, I am checking for "powers of two" with this function:
function validBracket(data) {
var x = data.teams.length;
return ((x != 0) && !(x & (x - 1)));
}
This works pretty well, but I am needing to know how many Bye rounds to add.
For instance, if I had 16 teams
, I would not need to add anymore teams. However, if I had 12 teams
, I would need the first 4 teams
to get a bye round.
How can I calculate number of bye rounds to add to my bracket? And would hard-coding an array of powers of two be better?
In pseudo code, something like this is what i was thinking of:
if(validateBracket(data)) {
// Valid number of teams (power of two). Keep going.
} else {
var byeRounds = calculateByeRounds();
}
NOTE: I would rather not use an array of powers of two like below:
var powersOfTwo = [2,4,8,16,32,...];
The reasoning behind this is that I would be limiting the number of teams that could be put in the system (however, I don't think a person would have over 256 teams).
When multiplying 2x × 2y, remember that you simply add the exponents together. For example, 23 (8) × 27 (128) = 27+3 = 210 (1024). Similarly, you can break up a single power of 2 into two powers which add up to the original power, such as 29 (512) = 26+3 = 26 (64) × 23 (8).
A power of two, when expressed in binary, will always look like 1 followed by n zeroes where n is greater than or equal to 0. Ex: Decimal Binary 1 1 (1 followed by 0 zero) 2 10 (1 followed by 1 zero) 4 100 (1 followed by 2 zeroes) 8 1000 (1 followed by 3 zeroes) . . . . . .
var needed = (1 << Math.ceil(Math.log2(n))) - n;
More generalized solution for extreme cases:
var needed = Math.pow(2, Math.ceil(Math.log2(n))) - n;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With