garretruh
garretruh

Reputation: 94

Ruby nested while loop stops early

In attempting to iterate over an array of the alphabet and generate all 6-character (alpha only) strings, my iteration seems to end after a single while loop of the most inner-nested loop. Code below. Thoughts?


alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

x1 = 0
x2 = 0
x3 = 0
x4 = 0
x5 = 0
x6 = 0

while x1<26
    y1 = alpha[x1]
    while x2<26
        y2 = alpha[x2]
        while x3<26
            y3 = alpha[x3]
            while x4<26
                y4 = alpha[x4]
                while x5<26
                    y5 = alpha[x5]
                    while x6<26
                        y6 = alpha[x6]
                        puts y1 + y2 + y3 + y4 + y5 + y6
                        x6 = x6 + 1
                    end
                    x5 = x5 + 1
                end
                x4 = x4 + 1
            end
            x3 = x3 + 1
        end
        x2 = x2 + 1
    end
    x1 = x1 + 1
end

Edit: It's also VERY likely that I'm overlooking a much simpler way to achieve the desired results. If so, feel free to correct me.

Upvotes: 1

Views: 1043

Answers (3)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

To illustrate Ruby way more,

loop.inject 'aaaaaa' do |memo|
  puts memo
  break if memo == 'zzzzzz'
  memo.next
end

Or simply:

( 'aaaaaa'..'zzzzzz' ).each &method( :puts )

Upvotes: 4

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

[*?a..?z].repeated_permutation(6).to_a.map &:join

Gives FATAL, FAILED TO ALLOCATE MEMORY on my machine,

[*?a..?z].repeated_permutation(2).to_a.map &:join

works OK.

OK, it is a mistake to call #to_a after #repeated_permutation, this is how it works:

[*?a..?z].repeated_permutation( 6 ).each { |permutation| puts permutation.join }

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

Does this do what you want? It will generate all unique permutations, but won't double characters (like in "aaaabb")

('a'..'z').to_a.permutation(6).to_a

Here's a shorter version, for demo purposes:

res = ('a'..'c').to_a.permutation(2).to_a 
res # => [["a", "b"], ["a", "c"], ["b", "a"], ["b", "c"], ["c", "a"], ["c", "b"]]

Upvotes: 2

Related Questions