javascript - Determining Powers of 2? -


i creating simple bracket system , need way check if there correct number of teams, or if program needs compensate bye rounds.

right now, checking "powers of two" function:

function validbracket(data) {     var x = data.teams.length;     return ((x != 0) && !(x & (x - 1))); } 

this works pretty well, needing know how many bye rounds add. instance, if had 16 teams, not need add anymore teams. however, if had 12 teams, need first 4 teams bye round.

how can calculate number of bye rounds add bracket? , hard-coding array of powers of 2 better?

in pseudo code, thinking of:

if(validatebracket(data)) {     // valid number of teams (power of two). keep going. } else {     var byerounds = calculatebyerounds(); } 

note: rather not use array of powers of 2 below:

var powersoftwo = [2,4,8,16,32,...];

the reasoning behind limiting number of teams put in system (however, don't think person have on 256 teams).

var needed = (1 << math.ceil(math.log2(n))) - n; 

more generalized solution extreme cases:

var needed = math.pow(2, math.ceil(math.log2(n))) - n; 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -