On 26.12.2008 10:30, andrea wrote:
I’m studying ruby (and I really love it even more than python) and I
want to do a little exercise.
Welcome to the pack! What a nice Christmas occupation.
I want to create an efficient module to generate every possible
anagrams of a word, of any given size…
Do you really mean “anagrams” or rather “permutations”? To decide on
anagrams you likely need some kind of dictionary which is significantly
more difficult than just permuting.
I already done this in python, I want to see how can it be elegant in
ruby…
I need a good permutation algorithm (this
Johnson-Trotter Algorithm: Listing All Permutations
works fine) and I’d like to use enumerators in the best and most
efficient way.
From 1.8.7 on you can do this
irb(main):009:0> “abc”.scan(/./).permutation {|x| p x.join}
“abc”
“acb”
“bac”
“bca”
“cab”
“cba”
=> [“a”, “b”, “c”]
irb(main):010:0> “abc”.chars.to_a.permutation {|x| p x.join}
“abc”
“acb”
“bac”
“bca”
“cab”
“cba”
=> [“a”, “b”, “c”]
irb(main):011:0>
Now you only need a filter that properly decides which of those is a
proper word and use that to decide which words to print and which not.
I also looked at callcc which is great for backtracking, could be used
in this case??
I would try to avoid it as it makes code very hard to read - at least
for me.
end
def each(&block)
@word.chars
end
def initialize(word)
@word = word
end
end
What exactly should be the responsibility of this class? Especially,
why do you call it “anagrams” but store only one word in it?
Cheers
robert