【问题标题】:Create lists with any two elements from a longer list DrRacket使用较长列表 DrRacket 中的任意两个元素创建列表
【发布时间】:2013-08-06 13:53:03
【问题描述】:

如何通过组合较长列表中的任意两个元素(例如 4 个元素)来生成序列列表?

例如,我想根据'(1 2 3 4)得到'(1 2)'(1 3)'(1 4)'(2 3)'(2 4)'(3 4)

【问题讨论】:

    标签: list scheme racket combinations elements


    【解决方案1】:

    问题要求提供给定列表的 组合 的 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))
    

    【讨论】:

    • 这是一个非常好的答案,但我很惊讶没有在球拍中找到它,因为它在 Python (itertools) 和 Clojure (math.combinatorics) 中都存在
    • 同意。 Racket 应该有一个标准的组合模块,使用流
    • 你在想我在想什么吗? ;-)
    • 我希望我有空闲时间:)
    【解决方案2】:

    这是您指定的解决方案(一个函数,一个参数)。对于像'(next rest ...) 这样的输入,解决方案会计算next 的结果,然后在rest ... 上递归 - 使用append 将这两个部分结合起来。

    (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))
    

    【讨论】:

      【解决方案3】:

      我认为您想要按照this answer 的所有排列。

      使用他的排列函数定义,您可以执行以下操作:

      (permutations 2 '(1 2 3 4))
      

      【讨论】:

      • 在这种情况下,解决方案需要组合,而不是输入列表的排列。与链接答案中描述的情况完全相反
      • 没错。我总是把那些倒退。让我们看看我是否可以修复这个例子......或者你也欢迎:-)
      • 非常好。我认为我理解它所花费的时间比你修复它所花费的时间要长。
      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2020-07-04
      • 1970-01-01
      相关资源
      最近更新 更多