找到给定总和

时间:2017-10-23 08:56:56

标签: list lisp

给出一个列表L=(M,A1,A2,...,An)。查找L1=(Ai,Ai+1,...,Ai+k), i+k<=N, i>=1,

所在的M=Ai+Ai+1+...Ai+k子列表

例如1:L=(12 1 3 -16 5 7 8 2 2), M=12 结果:L=((1 3 -16)(5 7)(8 2 2)) 1+3-16=12, 5+7=12, 8+2+2=12

例外L=(14 1 15 -1 14 5 6) 结果:L=((15 -1)(14)) 适用于1=14->no1+15=14->no1+15-1=14->no1+15-1+14=14->no1+15-1+14+5=14->no1+15-1+14+5+6=14->no
我们转到下一个项15=14->no15-1=14->YES!提取(15 -1) 我们继续讨论下一项14=14->YES!提取(14) 我们继续讨论下一个项目5=14->no5+6=14->no 完成结果(15 -1) (14)

如何在Lisp中解决它?

我的代码

(setq l '(6 1 2 3 6 14 3))
(setq comb nil)
(setq rez nil)
(defun sublist (lst)
    (secondfunction (car lst) (cdr lst)) 
)
(defun pairnil (list1)
  (mapcar #'(lambda (x) (cons x nil)) list1)
)
(defun pair (a list1)
  (mapcar #'(lambda (x) (append  x  (list a))) list1)
)
(defun secondfunction (head other)
    (run (cdr other) (cdr other) (pairnil other) (cdr(pairnil other)) (pairnil(car(pairnil other))))
    (final comb head nil)
)
(defun final (lst el result)
(if (>(length lst) 0)
    (progn
        (if(eq(loop for x in (car lst) sum x) el) (final (cdr lst) el (append result (cons (car lst) nil)))
        (if(>(length lst) 0)(final (cdr lst) el result )))
    ) 
    (setq rez result)   
))
(final comb (car l) nil)
(defun run (lst1 ilst1 lst2 ilst2 temp)
    (if (eq(car ilst1) nil) (setq comb lst2))
    (when (>(length lst1)0)
        (if (>(length ilst1)0) (run lst1 (cdr ilst1) (append lst2 (pair (car ilst1) temp)) ilst2 (append temp (pair (car ilst1) temp))))
        (if (=(length ilst1)0) (run (cdr lst1) (cdr lst1) lst2 (cdr ilst2) (pairnil(car ilst2))))       
    ))
(sublist l)

结果((6) (1 2 3) (1 2 3) (3 3)),但这不能正常工作。在示例中,我已经解释了它应该如何工作。

2 个答案:

答案 0 :(得分:1)

一种简单的方法:

map over all sublists of list and append the results
    map over all sublists of this reversed sublist and append the results
      when the sum of the items is M then collect a list of the reverse sublist

需要的功能:

  • mapcon用于映射
  • reverse用于撤消
  • reduce求和

答案 1 :(得分:0)

解决方案:

(setq l '(6 1 2 3 4 5 6 7 -1))
(setq comb nil)
(setq rez nil)

(defun sublist (lst)
(secondfunction (car lst) (cdr lst)) 
)

(defun secondfunction (head other)
(run (cdr other) (cdr other) (list(car other)) (list(list(car other))))
(final comb head nil)
)

(defun final (lst el result)

(if (>(length lst) 0)
(progn
    (if(eq(loop for x in (car lst) sum x) el) (final (cdr lst) el (append result (cons (car lst) nil)))
    (if(>(length lst) 0)(final (cdr lst) el result )))
) 
(setq rez result)   
)

)

(final comb (car l) nil)

(defun run (lst1  lst2 temp r)

(if (not(eq(car lst1) nil))
    (if (not(eq(car lst2) nil))
        (run lst1 (cdr lst2) (append temp (list (car lst2))) (append r (list (append temp (list (car lst2))))))
        (run (cdr lst1) (cdr lst1) (list(car lst1)) (append r (list(list (car lst1)))))
    )
    (setq comb r)
)




)


(sublist l)