Posted February 17, 20223 yr 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 see: https://www.geeksforgeeks.org/find-all-combinations-that-adds-upto-given-number-2/ Best, Achim
February 17, 20223 yr (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?
February 17, 20223 yr Author I use this to select different unique modules for Live-Electronics. Here ist my adapted function: (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))
Create an account or sign in to comment