# resolved Find all combinations that add upto given number

## Recommended Posts

Is something like this implemented in OM or has anybody written a function for it?

```Input: N = 3
Output:
1 1 1
1 2
3
Input: N = 5
Output:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5 ```

Best, Achim

##### Share on other sites

`(rnd-sum 3 '(1 2 3))`

##### Share on other sites

I would actually need ALL possibilities …

##### Share on other sites

```(defun comb-to-sum (n)
(let ((nums (gen-integer 1 n))
(x 0))
(find-unique
(sort-asc
(flatten-sublist
(loop repeat n
for i = (combination2 (incf x) nums)
collect (loop for c in i
if (= (sum c) n)
collect c)))))))

(comb-to-sum 3)
=> ((3) (1 2) (1 1 1))

(comb-to-sum 5)
=> ((5) (1 4) (2 3) (1 1 3) (1 2 2) (1 1 1 2) (1 1 1 1 1))```

If you need the function in the OM system I could add it with the next update.

In what context you are using this combination?

##### Share on other sites

I use this to select different unique modules for Live-Electronics.

```(defun comb-to-sum (n &key (reps t))
(let* ((nums (gen-integer 1 n))
(x 0)
(result
(find-unique
(sort-asc
(flatten-sublist
(loop repeat n
for i = (combination2 (incf x) nums)
collect (loop for c in i
if (= (sum c) n)
collect c)))))))
(if reps
result
(loop for i in result
when (equal (sum (remove-duplicates i)) n)
collect i))))

(comb-to-sum 5 :reps nil) ; => ((5) (1 4) (2 3))```

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×

• Lessons