0

我很难完全理解 CL 的 Loop 宏。这是我的 Project Euler Nr 的代码。32:

(defun number-to-list (nr)
  (map 'list #'digit-char-p (prin1-to-string nr)))

(defun nine-digits-p (multiplicand multiplier )
  (= (length (equationlist multiplicand multiplier 
                                     (* multiplicand multiplier))) 9))

(defun equationlist (multiplicand multiplier product)
  (append (number-to-list multiplicand) (number-to-list multiplier)
      (number-to-list product)))

(defun pandigital (multiplicand multiplier)
  (equal (sort (equationlist multiplicand multiplier
                 (* multiplicand multiplier)) #'<)
     '(1 2 3 4 5 6 7 8 9)))

(defun pandigital-list ()
  (loop
       for i from 1 to 2000 collect
       (loop for j from 2 to 2000
       when (and (nine-digits-p i j) (pandigital i j)) collect (* i j))))


(defun euler-32 ()
  (reduce #'+ (reduce #'union (pandigital-list))))

虽然这给了我正确的解决方案,但我的问题在于函数“pandigital-list”。它不是只收集泛数字数字,而是返回一个填充有“NIL”和少数正确数字的列表。

如何更改此函数以仅返回我感兴趣的数字?

4

1 回答 1

3

问题是,只要内部没有收集任何其他东西,它就会loop返回。nil(记住:在 Common Lisp 中,一切都有价值。)

一种解决方案是pandigital-list像这样重新定义:

(defun pandigital-list ()
   (loop for i from 1 to 2000
         for sublist = (loop for j from 2 to 2000
                             when (and (nine-digits-p i j)
                                       (pandigital i j))
                             collect (* i j))
             when sublist collect sublist))
于 2013-05-11T12:03:12.933 回答