• Coding
  • Exercise - Team Balancing

var pool=[];
var team1=[];
var team2=[];
function randomRating(){
    return Math.floor(Math.random() * 200) + 1;
}
function average(array){
	var sum = 0;
	for(var i = 0; i < array.length; i++){
	    sum+=array[i];
	}
	return sum/array.length;
}
while(pool.length<10){
    pool.push(Number(randomRating()));
}
pool.sort(function(a, b){ return a-b });

for(var i = 0; i < pool.length; i++){
	i%2==0?team1.push(pool[i]):team2.push(pool[i]);
}
console.log('Team1: '+team1);
console.log('Average rating: '+average(team1));
console.log('Average rating %: '+(average(team1)*100/(average(team1)+average(team2))));
console.log('Team2: '+team2);
console.log('Average rating: '+average(team2));
console.log('Average rating %: '+(average(team2)*100/(average(team1)+average(team2))));
This code fills a random pool and then splits it into two teams.
Sample output:
Team1: 55,112,152,171,187 
Average rating: 135.4 
Average rating %: 48.04826117814052 
Team2: 91,118,155,173,195 
Average rating: 146.4 
Average rating %: 51.95173882185947
It's a bit slow on big pools, probably because of the push operations. I'll try to make it faster without looking at others'.