I'm having a function which is adding 16 football teams with highest number of points in 4 groups. Every group must have 4 teams and must not have more than 2 teams from same league.
I've added a property in every team object with league name in arr
and sorted it by highest number of points.
I can't figure out how to put condition that one group can't have more than 2 teams from one league?
JSFIDDLE link: http://jsfiddle.net/6jdjjqfw/
Code:
var tournaments = ['bundes', 'league1', 'premier', 'primera', 'seriea'];
var teams = [];
var groups = [];
function getData(id) {
var url = "http://api.helloworld.ba/n/app.php?f=" + id;
return $.getJSON(url);
}
var AJAX = [];
for (i = 0; i < tournaments.length; i++) {
AJAX.push(getData(tournaments[i]));
}
$.when.apply($, AJAX).done(function () {
for (var i = 0, len = arguments.length; i < len; i++) {
teams.push(arguments[i][0]);
}
createGroups(teams);
});
function createGroups(teams) {
var
arr = [],
arra = [],
arrb = [],
arrc = [],
arrd = [],
br = 1;
for (i = 0; i < teams.length; i++)
for (var j = 0; j < teams[i].standing.length; j++) {
teams[i].standing[j].league = teams[i].leagueCaption;
arr.push(teams[i].standing[j]);
}
arr.sort(function (a, b) {
return b.points - a.points;
});
for (i = 0; i < 4; i++)
{
arra.push(arr[i].teamName);
arrb.push(arr[i+4].teamName);
arrc.push(arr[i+8].teamName);
arrd.push(arr[i+12].teamName);
}
groups.push(arra);
groups.push(arrb);
groups.push(arrc);
groups.push(arrd);
console.log(teams);
console.log(arr);
console.log("Groups listed:
");
for(i=0; i<groups.length;i++)
{
console.log("Group " + br +" " + groups[i]);
br++;
}
}
Try doing this :
Iterate on the teams (16 items)in a while loop
Use a switch on a random int between 1 and 4 to choose the group of each team
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Add a method to test if a team has already 2 member of the league before adding it to the group. Test also if the group is not full (4 members) If the method returns false then don't add the team to the group and don't increase the team counter, you'll get a new random number in your loop.