Visual LISP, AutoLISP and General Customization
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

cartesian product of a list of lists of atoms

3 REPLIES 3
Reply
Message 1 of 4
tom_brabant
713 Views, 3 Replies

cartesian product of a list of lists of atoms

 

Anybody know a way to get the cartesian product of a list of lists of atoms? 
For instance given a list ((1 2)(a b)(x y)) 
return this:
(
(1 a x) (1 a y)(1 b x)(1 b y)
(2 a x) (2 a y)(2 b x)(2 b y)
)

 

 

3 REPLIES 3
Message 2 of 4
lando7189
in reply to: tom_brabant

Enjoy!

 

(defun GetCartesianProduct ( li / s1 sr i1 ir)
  (if (null li)
    '()
    (progn
      (setq s1 (car li) sr (cdr li))
      (if (null sr)
        (mapcar 'list s1)
    (if (null s1)
      '()
      (progn
            (setq i1 (car s1) ir (cdr s1))
        (append
          (mapcar '(lambda (x) (cons i1 x)) (GetCartesianProduct sr))
              (GetCartesianProduct (cons ir sr))
        )
          )
        )
      )
    )
  )
)

 

- Lanny

Message 3 of 4
tom_brabant
in reply to: tom_brabant

Thank you so very much!

Message 4 of 4

Another version of this:

 

(defun cartesian-product (input / result)
  ;; ((1 2)(a b)(x y))  -> ((1 a x) (1 a y)(1 b x)(1 b y)(2 a x) (2 a y)(2 b x)(2 b y))
  (cond
    ((null input) nil)
    ((null (cdr input)) (mapcar 'list (car input)))
    (T (foreach item (car input)
         (foreach product (cartesian-product (cdr input))
           (setq result
                 (cons
                  (cons item product)
                  result))))
       (reverse result))))

 

--

 

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report

”Boost