All possible letter combinations?

T

Teme Rosi

Hi, im new to ruby. It is smiliar to perl. Can anyone convert this
script to ruby?



#!/usr/bin/perl

my $data = '0123456789abcdefghijklmnopqrstuvwxyz';
my @list = split //, $data;
for my $i (@list) {
for my $j (@list) {
for my $k (@list) {
for my $l (@list) {
print "$i $j $k $l\n";
}
}
}
}
 
T

Todd Benson

data='0123456789abcdefghijklmnopqrstuvwxyz'
list=data.split("")
list.each do |i|
list.each do |j|
list.each do |k|
list.each do |l|
puts "#{i} #{j} #{k} #{l} "
end
end
end
end

Logically equivalent on 1.8.7, but _don't_do_it_ (far too slow)...

s = "0123456789abcdefghijklmnopqrstuvwxyz"
b = ""
(s * 4).split(//).combination(4) {|group| b << group.join << "\n"}

...If just printing you could just use "p group.join", or "puts
group". I find it interesting that it is about 5x slower than the
code quoted above on my machine. I suppose it has to do with extra
method calls inside the block, since it is almost on par if you don't
do anything inside the block :) Having b as an array without the
join or "\n" basically halts my machine (10 seconds to recognize the
ctrl-c interrupt).

Todd
 
M

Martin Carpenter

Logically equivalent on 1.8.7, but _don't_do_it_ (far too slow)...

s = "0123456789abcdefghijklmnopqrstuvwxyz"
b = ""
(s * 4).split(//).combination(4) {|group| b << group.join << "\n"}


Alternatively:

STRING_LEN = 4 # length of each string to output
BASE = 36 # number of symbols in data string

(0..BASE ** STRING_LEN - 1).each do |i|
puts i.to_s(BASE).rjust(STRING_LEN, '0')
end

Here this runs ~the same speed as the nested loops solution. This won't
work for BASE > 36 however.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top