Skip to content

Instantly share code, notes, and snippets.

@dtinth
Created November 6, 2013 14:14
Show Gist options
  • Save dtinth/7336694 to your computer and use it in GitHub Desktop.
Save dtinth/7336694 to your computer and use it in GitHub Desktop.
Single Statement Pam Kuan Solution (Ruby)
gets.to_i.times { puts gets.strip
.gsub(/^([^aeiou]*)([aeiou]\w*)( [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')
.gsub(/^([^aeiou]*)([aeiou]\w*)( \w+ [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')
.gsub(/^(\w+ [^aeiou]*)([aeiou]\w*)( \w+ [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')
.gsub(/^(\w+ [^aeiou]*)([aeiou]\w*)( \w+ \w+ [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')
.gsub(/^(\w+ \w+ [^aeiou]*)([aeiou]\w*)( \w+ \w+ [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')
.gsub(/^(\w+ \w+ [^aeiou]*)([aeiou]\w*)( \w+ \w+ \w+ [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2') }
@neizod
Copy link

neizod commented Nov 6, 2013

can be collapse this

.gsub(/^([^aeiou]*)([aeiou]\w*)( [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')
.gsub(/^([^aeiou]*)([aeiou]\w*)( \w+ [^aeiou]*)([aeiou]\w*)$/, '\\1\\4\\3\\2')

into

.gsub(/^([^aeiou]*)([aeiou]\w*)(( \w+)? [^aeiou]*)([aeiou]\w*)$/, '\\1\\5\\3\\2')

or, more readable w/o nested group

.gsub(/^([^aeiou]*)([aeiou]\w*)( \w+)?( [^aeiou]*)([aeiou]\w*)$/, '\\1\\5\\3\\4\\2')

and so on.

finally, with the help of lambda, we could do something like meta-regex, such as

gets.to_i.times do
  puts lambda { |ws|
    ws.gsub /#{ '^(' +
                '\w+ ' * (ws.split.count/2-1) +
                '[^aeiou]*)([aeiou]\w*)( \w+)?( ' +
                '\w+ ' * (ws.split.count/2-1) +
                '[^aeiou]*)([aeiou]\w*)$'}/,
           '\\1\\5\\3\\4\\2'
  } [gets.strip]
end

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