3

長いリストから任意の 2 つの要素を組み合わせて、たとえば 4 つの要素を使用してシリアル リストを生成するにはどうすればよいですか?

たとえば'(1 2)'(1 3)'(1 4)'(2 3)'(2 4)、および'(3 4)に基づいて取得したい'(1 2 3 4)

4

3 に答える 3

3

質問は、特定のリストの組み合わせの 2 サイズのリストを求めます。n サイズの組み合わせを生成する、より一般的な手順で実装できます。

(define (combinations size elements)
  (cond [(zero? size)
         '(())]
        [(empty? elements)
         empty]
        [else
         (append (map (curry cons (first elements))
                      (combinations (sub1 size) (rest elements)))
                 (combinations size (rest elements)))]))

次のように指定すると、期待どおりに機能しますsize=2

(combinations 2 '(1 2 3 4))
=> '((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))
于 2013-08-05T21:12:48.777 に答える
2

これは、指定したとおりのソリューションです(1つの関数、1つの引数)。'(next rest ...)ソリューションのような入力の場合、結果を計算してnextから再帰しますrest ...- を使用appendして 2 つの部分を結合します。

(define (combine elts)
  (if (null? elts)
      '()
       (let ((next (car elts))
             (rest (cdr elts)))
         (append (map (lambda (other) (list next other)) rest)
                 (combine rest)))))
> (combine '(1 2 3 4))
((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))
于 2013-08-06T02:44:14.190 に答える