Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Created March 8, 2014 11:38
Show Gist options
  • Save emad-elsaid/9429208 to your computer and use it in GitHub Desktop.
Save emad-elsaid/9429208 to your computer and use it in GitHub Desktop.
generate random string from a canonical for, useful for software responding like humans
#!/usr/bin/env ruby
# generate a single sentence from a canonical form
# canonical sentence is a multi sentences combined in one
# form, generator will generate a sentence from it randomly
# based on the form, for example:
# "Hello [Emad|Elsaid]" , may generate "Hello Emad" or
# "Hello Elsaid" the result is random.
# also you could nest [] inside each other to gain a multi level
# canonical sentence example:
# "[[Hi|Hello] [Emad|elsaid] | good [morning|night] sir]"
def generate(result)
while result.include? '['
s_start = result.index '['
s_end = s_start+1
while s_end<result.length and result[s_end]!=']'
s_start = s_end if result[s_end] == '['
s_end += 1
end
sentence = result[(s_start+1)...s_end]
sentence = sentence.split '|'
result = result[0...s_start] + sentence.sample + result[s_end+1...result.length]
end
result
end
10.times do
puts generate '[Hello|Hi] my [friend|dear], how [are you [today|these days]|is your brother]?'
end
# Hello my friend, how is your brother?
# Hi my dear, how is your brother?
# Hello my dear, how is your brother?
# Hello my dear, how is your brother?
# Hi my friend, how is your brother?
# Hi my friend, how is your brother?
# Hello my friend, how are you these days?
# Hello my friend, how is your brother?
# Hello my friend, how are you these days?
# Hi my friend, how is your brother?
@kotp
Copy link

kotp commented Mar 10, 2014

Decided to write this equivalent string. Shows usage, and may be easier to track nesting.

def choices(array)                                              
  '[' + array.join('|') + ']'                                   
end                                                             

greetings = choices(%w[Hello Hi Hey])                           
titles = choices(%w[friend dear])                               
concerns = choices(                                             
  [                                                             
    "are you #{choices(['today', 'these days'])}",              
    "is your #{choices(%w[sister mother father brother])}"      
   ]                                                             
)

20.times do                                                     
  puts generate("#{greetings} my #{titles}, how #{concerns}?") 
end                                                             

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment