Tim
Tim

Reputation: 137

generator with Ruby

Im trying to create a random team generator based on the user's input of names and the number of teams evenly. Similar to this https://www.jamestease.co.uk/team-generator/

So far i've .split and .shuffle the string of input into an array of names, but unsure how to proceed further.

names = gets.split(",").shuffle

names = ["Aaron", "Nick", "Ben", "Bob", "Ted"]

For Example:
lets say i want to have 2 teams (names do not have to be in any particular order/team):

team_1 = ["Nick", "Bob"]

team_2 = ["Aaron", "Ben", "Ted"]

Any help or tips would be greatly appreciated

Upvotes: 5

Views: 204

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110745

players = %w| Wilma Hector Alfonse Hans Luigi Bo Katz Themal Dotty Billy-Bob |

num_teams = 4

(players.shuffle + ["unfilled"]*(players.size % 4)).each_slice(num_teams).to_a.transpose
  #=> [["Katz", "Bo", "Hans"], ["Themal", "Luigi", "Billy-Bob"],
  #    ["Alfonse", "Hector", "unfilled"], ["Dotty", "Wilma", "unfilled"]] 

Upvotes: 0

Shiva
Shiva

Reputation: 12592

names = ["Aaron", "Nick", "Ben", "Bob", "Ted", 'shiva', 'hari', 'subash']

number_of_teams = 4

players_per_team = (names.count / number_of_teams.to_f).ceil

teams = []

(1..number_of_teams).each do |num|
  teams[num - 1] = names.sample(players_per_team)
  names = names - teams[num - 1]
end

> p teams
=> [["hari", "Ben"], ["Bob", "subash"], ["shiva", "Ted"], ["Nick", "Aaron"]]

and if

names = ["Aaron", "Nick", "Ben", "Bob", "Ted", 'hari', 'subash']

then

>   p teams
[["hari", "subash"], ["Bob", "Aaron"], ["Ben", "Nick"], ["Ted"]]

Note: this will result random players every time you shuffle

Upvotes: 2

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

Use Array#sample to pick random elements from the names array:

> names = ["Aaron", "Nick", "Ben", "Bob", "Ted"]
# => ["Aaron", "Nick", "Ben", "Bob", "Ted"] 
team_size = names.length/2
# => 2
> team_1 = names.sample(team_size) # pick 2 random team names
# => ["Nick", "Ben"] 
> team_2 = names - team_1 # get the remaining team names from the names array
# => ["Aaron", "Bob", "Ted"] 

Upvotes: 1

Related Questions