AnApprentice
AnApprentice

Reputation: 110940

How to generate a random word with a number?

I'm looking for a method to generate a invite code. I would prefer the code not looks like garbled text: JakSj12

But rather more like heroku, using a fun word with 3 numbers.

lightspeed131 or happy124, jetski99

How can I build a method that takes a list of words, maybe 100? and randomly assigns 3 numbers to them?

Thanks

Upvotes: 3

Views: 2834

Answers (5)

Mario Uher
Mario Uher

Reputation: 12397

I would use following (very readable IMHO) solution:

names = %w[tinky\ winky dipsy laa-laa po]

def random_name(names)
  [names, (100..999).to_a].collect(&:sample).join
end

3.times.collect { random_name(names) }
# => ["dipsy147", "dipsy990", "po756"]

More memory friendly solution:

def random_name(names)
  @numbers ||= (100..999).to_a
  [names, @numbers].collect(&:sample).join
end

Upvotes: 1

Phrogz
Phrogz

Reputation: 303136

def random_word_and_number( words, max=999 )
  "%s%0#{max.to_s.length}d" % [ words.sample, rand(max+1) ]
end 

(1..4).map{ random_word_and_number( %w[ foo bar jim jam ] ) }
#=> ["jim048", "bar567", "jim252", "foo397"]

Let's you specify an arbitrary maximum value while ensuring that all answers have the same number of digits.

Upvotes: 1

rwat
rwat

Reputation: 833

Other answers given here are a bit slow, since they shuffle their lists on every call. Here's something a bit faster:

def wordwithnumber(words)
   words[rand(words.length)]+(rand(900)+100).to_s()
end

wordwithnumber(["lightspeed", "happy", "jetski"])

This gives you three digits every time, if you want a number from 0 to 999 modify the rand() call accordingly.

Upvotes: 3

tokland
tokland

Reputation: 67850

Always 3 different numbers? not very efficient but simple:

words.zip((100..999).to_a.shuffle).map(&:join)

If you don't mind getting repeated numbers (I guess not):

words.map { |word| word + 3.times.map { rand(10) }.join }

Or simply in Ruby 1.9:

words.map { |word| word + Random.new.rand(100..999).to_s }

([edit] This generate 100 words with numbers, which is what I understood. )

Upvotes: 2

Thiago Silveira
Thiago Silveira

Reputation: 5133

def random_name(words, number = nil)
  number ||= rand(999)

  words.sample.to_s + number.to_s # concatenate a random word and the number
end

# example:
random_name(["lightspeed", "happy"]) # lightspeedXXX, happyXXX (where XXX is a random number)
random_name(["lightspeed", "happy"], 5) # lightspeed5, happy5

Upvotes: 2

Related Questions