-1

I'm 'new' (kind of) to javascript and I like making small "games" for myself. I've been trying to create a FIFA World Cup simulator and I want to add 31 random teams to the groups besides qatar. I ran into the issue of needing to check to see if multiple of the same team are in the tournament at once. Does anyone know an easy way to fix this without creating fifty if statements?

The only way I might know to fix this is creating an if statement to check every team (all 31 teams besides Qatar), which seems to repetitive to be the only way.

David Jones
  • 2,879
  • 2
  • 18
  • 23
Hyyped
  • 33
  • 4
  • 1
    Hi. For future reference, the `basic` tag is for the BASIC programming language and not for problems that might be considered simple or 'basic'. – David Jones Jan 19 '23 at 15:26

2 Answers2

1

There are a few ways:

  1. Use a Set and check if the team is already in the set (theSet.has(team)) before adding the team (theSet.add(team)).
  2. Build an array of all 30 teams, shuffle it, and then draw your teams sequentially from the shuffled array.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • You wouldn't even need to check if `theSet.has(team)` because a Set would filter out duplicates anyways – rileyjsumner Jan 19 '23 at 15:31
  • 1
    @rileyjsumner - True, but you wouldn't know whether you'd "consumed" the team you passed to `add` or not. My understanding from the question is that it would matter to know that. (`Set.prototype.add` doesn't tell you whether it added the element or not, though you can infer it from `size` before vs. after -- easier just to use `has` first). – T.J. Crowder Jan 19 '23 at 16:11
1

Here is a short version using arrays, if I understood your question correctly. Please let me know if you meant something else or you want something more.

const teams = ["England","Holland","Morocco","France","Argentina","Portugal","Brazil","Senegal","Switzerland","Japan","Australia","Croatia","USA","Spain","Germany","Ecuador","South Korea","Cameroon","Poland","Uruguay","Tunisia","Mexico","Belgium","Ghana","Saudi Arabia","Iran","Costa Rica","Denmark","Serbia","Wales","Canada","Qatar"
];
const groups = Array.from({length: 8}, () => []);  //create array of 8 empty sub-arrays

teams.sort(() => Math.random() - 0.5);  //shuffle 'teams' array randomly
teams.forEach((team, i) => groups[i % 8].push(team)); //iterate over the 'teams' array and push each team into one of the 8 groups

console.log(groups);

This prints the eight groups randomly every time like so:

[
  [ 'Switzerland', 'Spain', 'Portugal', 'Uruguay' ],
  [ 'Iran', 'Ghana', 'France', 'Poland' ],
  [ 'England', 'Saudi Arabia', 'Serbia', 'Denmark' ],
  [ 'Mexico', 'Morocco', 'South Korea', 'Ecuador' ],
  [ 'Costa Rica', 'Tunisia', 'Senegal', 'Australia' ],
  [ 'Qatar', 'Japan', 'Brazil', 'Croatia' ],
  [ 'Canada', 'Wales', 'Cameroon', 'Belgium' ],
  [ 'Germany', 'Holland', 'USA', 'Argentina' ]
]
Ietu
  • 823
  • 2
  • 9