E
Endy Tjahjono
Hello all,
I have just created a function that returns all letter permutation in
a word, so if I put 'abc', it will return 'abc', 'acb', 'bac', 'bca',
'cab', 'cba'.
I want to know other ways to achieve the same result. Can you help?
Here's my code:
def geta(astr)
return [astr] if astr.length < 2
ret = []
0.upto(astr.length - 1) do |n|
rest = astr.split('')
picked = rest.delete_at(n)
geta(rest.join).each do |x|
ret << picked + x
end
end
ret
end
print "word: "
ainput = gets.chomp
puts geta(ainput)
BTW this post is inspired by the ruby quiz. Seeing the various ways
people solve the problems has been very educational. Too bad most of
the problems are too big for beginners like me to participate.
I have just created a function that returns all letter permutation in
a word, so if I put 'abc', it will return 'abc', 'acb', 'bac', 'bca',
'cab', 'cba'.
I want to know other ways to achieve the same result. Can you help?
Here's my code:
def geta(astr)
return [astr] if astr.length < 2
ret = []
0.upto(astr.length - 1) do |n|
rest = astr.split('')
picked = rest.delete_at(n)
geta(rest.join).each do |x|
ret << picked + x
end
end
ret
end
print "word: "
ainput = gets.chomp
puts geta(ainput)
BTW this post is inspired by the ruby quiz. Seeing the various ways
people solve the problems has been very educational. Too bad most of
the problems are too big for beginners like me to participate.