[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Iterate through Array?

Zephyr Pellerin

11/22/2007 7:56:00 AM

I've been messing around with generating all possible combinations of a
set of letters, (Ala, a 6 letter set would start enumerating at "aaaaaa"
then move on to "aaaaab" so on and so forth, all the way down to
"zzzzz") by iterating through an array using slice() , Which is a pretty
good implementation for small tasks, But suppose I wanted to generate
larger sets, Is there a more efficient implementation than say

a=0
b=0
c=0
d=0
e=0
f=0
z = ["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"]

slice = z.slice(a) + z.slice(b) + z.slice(c) + z.slice(d) + z.slice(e) +
z.slice(f)

if...
else.... [Incrementing]

puts slice

Thank you in advance
4 Answers

Zephyr Pellerin

11/22/2007 10:02:00 AM

0

Sebastian Hungerecker wrote:
> Zephyr Pellerin wrote:
>> I've been messing around with generating all possible combinations of a
>> set of letters, (Ala, a 6 letter set would start enumerating at "aaaaaa"
>> then move on to "aaaaab" so on and so forth, all the way down to
>> "zzzzz")
>
> ("aaaaaa".."zzzzzz").each do |string|
> puts string
> end
>
> This will run for a good while, but it won't hog memory the way a solution
> populating an array would.
>
>
> HTH,
> Sebastian


Impressive, Signifigantly less RAM usage.

Sebastian Hungerecker

11/22/2007 8:22:00 PM

0

Zephyr Pellerin wrote:
> I've been messing around with generating all possible combinations of a
> set of letters, (Ala, a 6 letter set would start enumerating at "aaaaaa"
> then move on to "aaaaab" so on and so forth, all the way down to
> "zzzzz")

("aaaaaa".."zzzzzz").each do |string|
puts string
end

This will run for a good while, but it won't hog memory the way a solution
populating an array would.


HTH,
Sebastian
--
NP: Lake of Tears - Sweetwater
Jabber: sepp2k@jabber.org
ICQ: 205544826

Thomas Wieczorek

11/22/2007 8:26:00 PM

0

You might also try the Permutations gem at http://permutation.ruby...

Lloyd Linklater

11/23/2007 3:59:00 AM

0

What about something as simple as

i = 0
"aaaaa".upto("zzzzz") {|s| i += 1; puts "#{i}. #{s}"}

You could write to a file if you wish. Note that "aaaaa".upto("zzzzz")
is NOT the same as "a".upto("zzzzz")
--
Posted via http://www.ruby-....