method that generate block?

N

Nanyang Zhan

Hi, could anyone tell me how to code a method/methods that generates
these blocks? thanks.
vds[0].each do |d0|
vds[1].each do |d1|
...
vds[n].each do |dn|
ds = [d0, d1..., dn]
create_new_filter(ds)
end
end
...
end
 
C

Ckvok Kovsky

0..10.times do |time|
vds[time].each do |my_var|
ds = << my_var
end
end

create_new_filter(ds)
 
N

Nanyang Zhan

Ckvok said:
0..10.times do |time|
vds[time].each do |my_var|
ds = << my_var
end
end

create_new_filter(ds)

thanks,but yours will only create one filter, and I want to create
vds[0].size*vds[1].size*...*vds[n].size filters, basing on every ds
value. Each ds value is a arrary that contains one value from the vds
array.

I mean this:
n = vds.size
dss = []
vds[0].each do |d0|
vds[1].each do |d1|
...
vds[n].each do |dn|
dss << [d0, d1, ... , dn]
end
...
end
end

dss.each {|ds| create_filter(ds) }
 
N

Nanyang Zhan

I mean this:
n = vds.size
dss = []
vds[0].each do |d0|
vds[1].each do |d1|
...
vds[n].each do |dn|
dss << [d0, d1, ... , dn]
end
...
end
end


OK, now I know I just need a cartesian product method and I've got one
from http://www.ruby-forum.com/topic/95519#615075 :

def cart_prod( *args )
args.inject([[]]){|old,lst|
new = []
lst.each{|e| new += old.map{|c| c.dup << e }}
new
}
end

The problem is this method take arrays as argument, how can I pass into
only one array as argument? (this one array will contains sub arrays
that I want to make a cartesian product from, for example: vds =
[[1,2],["a","b"]], how to pass the vds array into the method to get
cartesian product of [1,2] and ["a","b"]?)
 
P

Paolo Bonzini

def cart_prod( *args )
args.inject([[]]){|old,lst|
new = []
lst.each{|e| new += old.map{|c| c.dup << e }}
new
}
end

The problem is this method take arrays as argument, how can I pass into
only one array as argument? (this one array will contains sub arrays
that I want to make a cartesian product from, for example: vds =
[[1,2],["a","b"]], how to pass the vds array into the method to get
cartesian product of [1,2] and ["a","b"]?)

Remove the * from *args.

Paolo
 

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

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top