0

I'm working on a GameBuilder class that builds a Game object using a player count, array of player names, game board width/height, and a couple more irrelevant params. I'd like to allow a Game to be setup without specifying names. I have an array of default names I'd like to pick from if this is the case.

I have two constructors. The main one receives a player count, and an array of player names (see below).

public GameBuilder withPlayers(final Integer players, final String[] someNames) {
    if ((players >= MINIMUM_NUMBER_OF_PLAYERS) && (players <= MAXIMUM_NUMBER_OF_PLAYERS)) {
      if (someNames.length == players) {
        tempPlayers = players;
        names = someNames;
        return this;
      } else {
        throw new IllegalArgumentException("Player/Name mismatch!");
      }

    } else {
      throw new IllegalArgumentException("The number of players must be between " + MINIMUM_NUMBER_OF_PLAYERS + " and " + MAXIMUM_NUMBER_OF_PLAYERS + ".");
    }

(tempPlayers and names are declared elsewhere and eventually given to the Game constructor).

My second constructor takes only one parameter, player count, and chains onto the main constructor above. This is where I'd like to create an array of randomly picked names (from the default names array) up to the size of the specified player count, to then pass on to the main constructor, which will in turn, get passed to the Game object.

Is this possible?

  • "I have two constructors. The main one receives a player count, and an array of player names (see below)." The code below is not a constructor? – Nexevis Feb 21 '20 at 14:35
  • Wouldn't the array of names have a length of the same value as the player count? – deHaar Feb 21 '20 at 14:37

1 Answers1

0

Your problem boils down to constucting an array of unique integers of lenght players and in the interval [0, someNames.length -1].

Drawing from this earlier question, the easiest way to do achieve this is by creating an array of consecutive integers, shuffling them around, and then trimming at lenght players. Then just use these as random positions of the someNames array to initialize the names.


List<Integer> integers = IntStream.range(o, someNames.length);
Collections.shuffle(integers);
integers = integers.sublist(0,players)

names = new String[players];
for (int i = 0; i < players; i++) {
    int position = integers.get(i);
    names[i] = someNames[position];
}


Note that if the someNames array is very big, this approach is rather wasteful. But otherwise, it's easy to reason about and debug.

mtrycz
  • 91
  • 2