Ruby Generator

I am trying to create a random command generator based on user input of names and the number of commands evenly. Like this https://www.jamestease.co.uk/team-generator/

So far I have had a .split and .shuffle input line in the names array, but I don't know how to proceed further.

 names = gets.split(",").shuffle names = ["Aaron", "Nick", "Ben", "Bob", "Ted"] 

Example:
let's say I want to have 2 commands (names should not be in a specific order / command):

 team_1 = ["Nick", "Bob"] team_2 = ["Aaron", "Ben", "Ted"] 

Any help or advice would be greatly appreciated.

+5
source share
3 answers
 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 in random players with every shuffle

+2
source

Use Array # sample to select 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"] 
+1
source
 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"]] 
0
source

Source: https://habr.com/ru/post/1234499/


All Articles