cartesian product of arrays

ruby

    Next

  • 1. select box question
    Hi, Yet another newbie here... I'm writing an appliction in Rails, and I've Ajaxified my select boxes so they update dynamically. I used the "observe_field" method to monitor changes to my select box. I find that it's kind of erratic... it updates constantly and makes the selection for me, based on where my mouse happens to be hovering when it does its observation. Not very user friendly. I'd much rather the onChange event, but I'm not sure exactly how to write the syntax for using the event. Here's my code as it is now: <select id="product[proddesc_pk]" name="product[proddesc_pk]"> <%= options_from_collection_for_select( Product.find_all, "proddesc_pk", "prod_name" ) %> </select></p> <%= observe_field("product[proddesc_pk]", :frequency =>0.25, :update => "component_id_list", :url => { :action => :fill_component_box}, :with => "'id='+value") %> How would I go about changing that code so that it updates based on an onChange event, rather than the observation? Any help would be greatly appreciated! Thanks, ~ Shanan
  • 2. Using Test::Unit to automate reporting of failures
    I'm using Test::Unit along with the Watir framework to run tests against my website. I would like to be able to do 2 things: 1. Pass in a "server" parameter to allow the tests to be run against the developement, staging or production sites. I know how to get parameters using GetoptLong, but I can't figure out how to pass these to my Test::Unit::TestCase class. I'm new to Ruby, so forgive me if I'm way off, but it seems that an instance of the TestCase class is created internally within Test::Unit. I can't see a way of creating an instance of my TestCase, passing it the server it should run the tests against and then running the tests. 2. Report any failures via email. This time I know how to send the email, but I don't know how to access the failures after the tests have run. I thought that the TestRunner might give me access to the failures after the tests have run, but it doesn't seem to be the case. Any help on these 2 issues would be much appreciated. Thanks, Ben Mills
  • 3. writing native ObjC extension to ruby ??
    i'd like to write a natine objc ext to ruby. i'm in search of an example or a tuto. (i've found how to write C ext)

cartesian product of arrays

Postby Thomas Hafner » Sat, 27 Jan 2007 19:52:10 GMT

Hello,

did I miss some standard library function? Anyway, then I'll do it on
my own:

def cartprod(*args)
  result = [[]]
  while [] != args
    t, result = result, []
    b, *args = args
    t.each do |a|
      b.each do |n|
        result << a + [n]
      end
    end
  end
  result
end

Example:
cartprod([1,2],[3,4,5],[6,7,8])
=> [[1, 3, 6], [1, 3, 7], [1, 3, 8], [1, 4, 6], [1, 4, 7], [1, 4, 8],
    [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 3, 6], [2, 3, 7], [2, 3, 8],
    [2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8]]

Regards
  Thomas

Re: cartesian product of arrays

Postby Peter Szinek » Sat, 27 Jan 2007 20:42:30 GMT


Cool!

Just a suggestion: it is also possible to reopen Enumerable and put your 
code there - in this case, all enumerable types will have this 
functionality (e.g. Sets), not only Arrays. Also it is maybe more 
intuitive (for me at least) to write:

first_ary.cartprod second_ary

Best wishes,
Peter

__
 http://www.**--****.com/ 





Re: cartesian product of arrays

Postby Thomas Hafner » Sat, 27 Jan 2007 21:33:08 GMT

Peter Szinek < XXXX@XXXXX.COM > wrote/schrieb < XXXX@XXXXX.COM >:


How should my example then look like?

It can't be [1,2].cartprod([3,4,5]).cartprod([6,7,8]), because then
the result would be different:
[[[1, 3], 6], [[1, 3], 7], [[1, 3], 8], [[1, 4], 6], [[1, 4], 7],
[[1, 4], 8], [[1, 5], 6], [[1, 5], 7], [[1, 5], 8], [[2, 3], 6],
[[2, 3], 7], [[2, 3], 8], [[2, 4], 6], [[2, 4], 7], [[2, 4], 8],
[[2, 5], 6], [[2, 5], 7], [[2, 5], 8]]

Do you appreciate [1,2].cartprod([3,4,5], [6,7,8]) ?

Regards
  Thomas

Re: cartesian product of arrays

Postby Peter Szinek » Sat, 27 Jan 2007 21:50:10 GMT


Well, you are right... it is much less intuitive if you have 3 or more 
arrays. However, I think your example, i.e.

[1,2].cartprod([3,4,5], [6,7,8])

is perfectly OK! Basically what changes is that you will refer to the 
array [1,2] as self (in Enumerable), and not as the first parameter (as 
in your original cartprod function).

Bye,
Peter

__
 http://www.**--****.com/ 


Re: cartesian product of arrays

Postby Thomas Hafner » Mon, 29 Jan 2007 02:56:04 GMT

Peter Szinek < XXXX@XXXXX.COM > wrote/schrieb < XXXX@XXXXX.COM >:


Does that follow your suggestion?:
#\\\
module Enumerable
  def cartprod(*args)
    result = [[]]
    ([self] + args).each do |b|
      t, result = result, []
      t.each do |a|
        b.each do |n|
          result << a + [n]
        end
      end
    end
    result
  end
end
#///

Example:
(1..2).cartprod((3..5), (6..8))

Regards
  Thomas

Re: cartesian product of arrays

Postby Peter Szinek » Mon, 29 Jan 2007 03:14:36 GMT


Exactly!

Cheers,
Peter

__
 http://www.**--****.com/ 



Re: cartesian product of arrays

Postby karoyakani » Tue, 30 Jan 2007 14:44:45 GMT

How about recursive version?

module Enumerable
  def cartprod(*args)
    return self if [] == args
    b = args.shift
    result = []
    self.each do |n|
      b.cartprod(*args).each do |a|
        result << [n] + (a.kind_of?(Array)? a: [a])
      end
    end
    result
  end
end

def cartprod(*args)
  args.shift.cartprod(args)
end

Then both forms work as below:
p (1..2).cartprod((3..5), (6..8))
p cartprod([1,2],[3,4,5],[6,7,8])

Further consideration would be to use a block for output formating:
e.g. replace result << [n] + a above to yield n, a and a block {|n,a| n
+a.join(' ')} for string concatination etc

FYI,
TJ








Re: cartesian product of arrays

Postby GOTO Kentaro » Tue, 30 Jan 2007 16:04:20 GMT



I wrote once like that. My product.rb is a mixin for enumerable.
 http://www.**--****.com/ ~gotoken/ruby/p/product/ruby-product-1.0.0.tar.gz
hope this helps,

gotoken


Re: cartesian product of arrays

Postby Thomas Hafner » Tue, 30 Jan 2007 20:42:43 GMT

"karoyakani" < XXXX@XXXXX.COM > wrote/schrieb < XXXX@XXXXX.COM >:

                        ^^^^
    args.shift.cartprod(*args)
with the additional ``*'' would be better ...


... otherwise the second statement produces different output.
Very nice!


Great, still more abstraction!

Regards
  Thomas

Re: cartesian product of arrays

Postby Trans » Wed, 31 Jan 2007 00:09:15 GMT





Hi--

I was going to say that Facets has cross:

  require 'facets/core/enumerable/cross'

  Enumerable.cross([1,2],[3,4,5],[6,7,8])
  => [[1, 3, 6], [1, 3, 7], [1, 3, 8], [1, 4, 6], [1, 4, 7], [1, 4, 
8], [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 3, 6], [2, 3, 7], [2, 3, 8], 
[2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8]]

Also when just deailing with a pair:

  require 'facets/core/enumerable/op_pow'

  [1,2] ** [3,4,5]
  => [[1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5]]

there are two considerations though: 1) your implementation retains an 
additional array level for each initial possibility. is that desired 
behavior? and 2) Facets' implementation is poorly named conveying the 
cross product, which it is not, so unless someone has an objection, 
I'll rename it to #cart and credit you.

t.

( http://www.**--****.com/ )



Re: cartesian product of arrays

Postby Paulo Kh » Wed, 31 Jan 2007 00:37:58 GMT




Can I suggest using the full name (#cartesian_product) instead of  
short hand names?

Paulo Jorge Duarte Kh
 XXXX@XXXXX.COM 




Re: cartesian product of arrays

Postby GOTO Kentaro » Wed, 31 Jan 2007 02:57:07 GMT



Confusing operand order...

In set theory, e.g.,  http://www.**--****.com/ 
the notation A^B, where A and B are arbitrary sets, is used to denote the
set of maps from B to A.  Then we get (a**b).size == (a.size)**(b.size)


Gotoken


Re: cartesian product of arrays

Postby Trans » Wed, 31 Jan 2007 04:26:58 GMT







that's doable. thanks.

t.



Re: cartesian product of arrays

Postby Trans » Wed, 31 Jan 2007 05:11:56 GMT







ignore that one, the layout of the result confused me.

T.



Re: cartesian product of arrays

Postby Trans » Wed, 31 Jan 2007 05:14:34 GMT







so maybe, i should probably get rid of that, maybe use it for actual 
cross-product instead?

t.



Similar Threads:

1.cartesian product - next to last version

Hello,

Since the original thread got a little long, I decided to post my next to 
last version in a new thread. My previous version gave results like 
[[1,4],7] for more than two arrays when you really wanted [1,4,7]. The trick 
is to flatten each element of the product. The following works for any 
number of arrays. Of course you might want a product in which the elements 
of that product are arrays. Any suggestions?

class Array

  def cartprod(b=[])
    if b.empty? then
      #assume self an array of arrays
      inject {|cp,x| cp.cartprod(x) }
    else
      z = inject([]) {|a,x| b.inject(a) {|a,y| a << [x,y]}}
      z.collect! {|x| x.flatten }
    end
  end

end


a=[1,2,3]
b=[4,5,6]
c=[7,8,9]

# works fine
p [a,b,c].cartprod

# doesn't work since [1,4,7,[10,11]] is [1,4,7,10,11]
d=[10, [11,12]]
p [a,b,c,d].cartprod


2.cartesian product

Hello,

How would I create a function that will take list (array) of integers and 
return their cartesian product?

Thank You,

Walter Kehowski
nuby 


3.Cartesian and polar coordinates library

Hello,

For a personal project I had to create a library of cartesian and polar
coordinates. Is anyone else interested in this code? If so I'll try to turn
it in to a library and release it on rubyforge.
Just my way of saying thanks for Ruby, this turns out to be a really nice
language!

Regards,
Bart

4.Fastest way to compute dot product (inner product) in Ruby?

5.Product Class #2

[Note:  parts of this message were removed to make it a legal post.]

I was wondering if anyone had any ideas on how I could make the following
method "return "$#{@price}0" if "@price" only has one 0 after the ".", and
just "return "$#{@price}" if it has two?
Thanks.

(The following method is inside a class called "Product"... Hence the
subject)

    def price
        if @price.to_s.length == 4
            return "$#{@price}"
        else @price.to_s.length
            return "$#{@price}0"
        end
    end

6. how to create a product instance?

7. dot-product operators and strides for linear algebra

8. Howto ? :: multi notes for same product in rails



Return to ruby

 

Who is online

Users browsing this forum: No registered users and 82 guest