0

I'm trying to generate a word with a specific set of letters.

The first letter of the word must contain the letters P,G,T,K the second A,E,I,O,U

I have tried generating them with the code blow with no success. Once I store all of these random letters as variables I will then join them together to make the randomized word

letter1 = rand(80,84,75,71).chr
letter2 = rand(97,101,105,111,117,121).chr

name = letter1 + letter2 + letter2 + letter1 + letter2

puts name
Phrogz
  • 296,393
  • 112
  • 651
  • 745

2 Answers2

4
puts 'PGTK'[rand(4), 1] + 'AEIOU'[rand(5), 1]

For some real fun, use actual noise-derived entropy:

def noise_index s
  s[@f.sysread(1).unpack('C').first/256.0*s.length, 1]
end
def run
  open '/dev/random', 'r' do |f|
    @f = f
    100.times do
      puts noise_index('PGTK') + noise_index('AEIOU')
    end
  end
end
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
2

If you need just a final word of two letters:

['PGTK', 'AEIOU'].map { |s| s.chars.to_a.sample }.join

Or following the example in your question:

letter1, letter2 = ['PGTK', 'AEIOU'].map { |s| s.chars.to_a.sample }
name = letter1 + letter2 + letter2 + letter1 + letter2
tokland
  • 66,169
  • 13
  • 144
  • 170
  • Thank you for the great feedback! Both were excellent suggestions. The was the first use I have seen of .map. Just learning ruby and love seeing all of these different ways of achieving the end goal :) – ScrubDubbins Jul 07 '11 at 20:32