I have strong feeling that the code below is ugly at least as there are 2 same "cons".
I would appreciate if you advise me ways to improve it.

The code produces all allocation by n items from list lst.

(defun allocations (lst n)
  (if (= n 1)
      (loop for i in lst
       collect (cons i nil))
      (loop for i in lst
   append (mapcar #'(lambda (l) (cons i l))
                      (allocations (remove i lst) (- n 1))))))
  • 1
    \$\begingroup\$ To make sure I understood you: you are trying to do permutations based on an assumption that the elements of the list are unique non-negative integers? In that case, I'd rather use a general purpose permutation algorithm instead. Actually, complexity-wise you'd only gain from that. Also variable names like lst and l can be improved by expanding them to the full length. The first branch in the if is equivalent to (mapcar #'list lst). \$\endgroup\$ – wvxvw Dec 14 '12 at 13:08
  • \$\begingroup\$ thanks @wvxvw! Yes, you are right. List elements are unique and non-negative integers. I will try to use general purpose permutation algorithm. \$\endgroup\$ – korabelnik Dec 14 '12 at 13:27
(defun allocations (source length)
  (if (= 1 length)
      (list (list (car source)))
      (loop for processed = nil then (cons (car i) processed)
         for i on source
         for todo = (cdr i)
           (loop for intermediate
              in (allocations
                  (append (reverse processed) todo)
                  (1- length))
                (loop for prefix = nil then (cons (car suffix) prefix)
                   for suffix on intermediate
                   collect (append prefix (list (car i)) suffix))))))

This should be a more general case of the problem (i.e. it makes no assumption of the nature of the elements in the list), but it doesn't verify that there is enough of the elements in the source list to build the required number of permutations.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.