0

Thank you for your help yesterday and for teaching me something new as well. :)

I have another question based on permutation... the algorithm I have works however I have the issue that identical adjacent characters are missing from the list generated.

For example, if I have the character list a-z,0-9,- and let's say that the maximum length is 2, then I should see aa, bb, cc, dd, ee, ff, etc. ad nauseum.

length = 1
alphabet = [('a'..'z').to_a, ('0'..'9').to_a, ('-').to_a].flatten
prefix = 'file-'
suffix = '.txt'


while length < 3


alphabet.permutation(length).each do |x|

@name =  prefix+x.join('').to_s+suffix
puts @name

end

length += 1

end

However, I am only seeing the following:

file-ba.txt
file-bc.txt

note the missing "bb" and this continues on until the program is finished.

I am sure I am missing something, just not sure what?

2 Answers2

3

I think you want to use repeated_permutation instead of permutation.

http://www.ruby-doc.org/core/classes/Array.html#M000289

It will generate all permutations including "file-bb.txt".

Evgeny Shadchnev
  • 7,320
  • 4
  • 27
  • 30
  • 1
    That looks like it will do the job. :) I am now stuck as to why it is not liking it... test.rb:10: undefined method `repeated_permutation' for # (NoMethodError). All I did was substitute permutation for repeated_permutation??? – To Perm or Not To Perm May 31 '11 at 15:01
  • This method is only available in ruby 1.9 and you're probably using 1.8. Consider switching to 1.9, that's the current stable version. – Evgeny Shadchnev May 31 '11 at 15:09
  • Thank you. You are correct, I am using 1.8(7) on Ubuntu... switching to 1.9 is going to be a pain but worth a try. Is there a way to do this on 1.8(7) without switching to 1.9 though? – To Perm or Not To Perm May 31 '11 at 15:16
  • It's a ruby method, so you'll either have to upgrade or to reimplement it yourself. By the way, upgrading really isn't a massive pain if you use rvm to manage different versions. – Evgeny Shadchnev May 31 '11 at 15:32
  • Hi Evgeny, I am not using RVM however I am setting it up now so all that is left is to say THANK YOU for your answer and quick responses. :) – To Perm or Not To Perm May 31 '11 at 15:39
1

That's what a permutation is. The only 6 permutations of [1,2,3] are

123
132
213
231
312
321
Gareth
  • 133,157
  • 36
  • 148
  • 157
  • Wow... I must have misunderstood the term permutation in this case as I thought that using your example, we would also have 112, 122, etc as they are also unique. Now I need to find another way of doing what I want to do? :( – To Perm or Not To Perm May 31 '11 at 14:54