< Back to IRCAM Forum

Lisp opération mathématique

Bonjour, petit problème mathématique, j’aimerais s’il vous plaît obtenir toutes les combinaisons possibles de N nombres positifs ≥ p dont la somme vaut X.

Par exemple :

  • si p = 2, X = 6 et N = 2, on aurait (2 4), (4 2) et (3 3).

  • si p = 0, X = 12 et N = 3, on aurait parmi les combinaisons : (12 0 0), (0 12 0), (11 1 0), (3 3 6), (9 2 1) etc…

Merci beaucoup par avance !

Lisa

Hello Lisa,

I once wrote a script which gives all possible non-redundant combinatory k-tupels
of a given set n. So you can use this to get all possible tupels.
In the next step you can filter out all tupels of which the checksum equals your X.
With permutations the formerly not generated “redundant” tupels are generated. And finally the thus generated duplicates are filtered out with the ‘remove duplicates’-loop.

Not the most elegant solution, but maybe it helps.

Best

Peter

PS: you need to copy the lisp-file into the user folder of your project or in the init-folder of your om-application.

checksum tupels.omp (10.9 KB)
com-rec2.lisp (257 Bytes)

Hello,

Thank you very much for this patch, it helps me a lot !
Could you please tell me how to filter out the combinaisons with some equal numbers ?
For example, filter out in the list of combinations (3 3), (6 1 1), (2 2 2), (6 9 4 4 2) etc…
Thank you !

Lisa

Hello Lisa,
just increment p in the first recursion:

(in-package :om)

(defun comb-rec2 (k p n)
(cond ((zerop k) '(()))
((< n p) ‘())
(t (append (mapcar #’(lambda (rest1) (cons p rest1))
(comb-rec2 (1- k) p n))
(comb-rec2 k (1+ p) n)))
))

(defun comb-rec3 (k p n)
(cond ((zerop k) '(()))
((< n p) ‘())
(t (append (mapcar #’(lambda (rest1) (cons p rest1))
(comb-rec3 (1- k) (1+ p) n))
(comb-rec3 k (1+ p) n)))
))

Peter

Could you please send it to me in “comb-rec3.lisp” form ? I’m not familiar yet with lisp linear writing and don’t know yet how to convert it in objects. Thank you in advance !

Lisa

just select the comb-rec2-function in your patch and type e to open the lisp listener. copy the script text comb-rec3 into the window after comb-rec2, afterwards type cmd-y to evaluate - or choose lisp/eval all in the menu. you can then create comb-rec3 as any other function.

Hello !

Do i mistake something ?
There’s an error message.

Hello,
oh sorry, it seems, that the text-editor here did interpret apostrophes as single quotation marks. (You can see the difference by comparing the lines 3 and 4 in …rec2 and …rec3 in your screenshot.)
Anyways: I send you the complete lisp file with which you can replace the previous one.
Best,
Peter
comb-rec21.lisp (500 Bytes)
.