【问题标题】:Cartesian power (cartesian product with self arbitrary times)笛卡尔幂(具有自任意时间的笛卡尔积)
【发布时间】:2014-01-25 05:34:17
【问题描述】:

我需要在我的代码中计算数组与其自身的笛卡尔积不同次数。例如,如果我的数组是[1,2],我需要将这些值填充到三个槽中,结果将是:

[1,1,1]
[1,1,2]
[1,2,1]
[1,2,2]
[2,1,1]
[2,1,2]
[2,2,1]
[2,2,2]

最简单的方法是什么?

【问题讨论】:

    标签: ruby cartesian-product


    【解决方案1】:

    您可能正在寻找带有重复的排列,幸运的是来自标准库的 Ruby 的 Array implements this

    [1,2].repeated_permutation(3).to_a
    # [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]]
    

    【讨论】:

    • 谢谢!我以前没见过这个。
    【解决方案2】:

    您的回答略有不同:

    class Array
      def **(n)
        product( *([self]*(n-1)) )
      end
    end
    
    [1,2]**3
      # => [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2],
      #     [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]] 
    

    【讨论】:

    • 啊,我喜欢这个远远超过.times.map。谢谢。
    【解决方案3】:

    因为我喜欢monkeypatching,所以我把这个放在数组本身上:

    class Array
      def **(n)
        self.product( *(n-1).times.map{ self } )
      end
    end
    

    不过,我不确定是否有更优雅的方式将您自己的 n-1 个副本传递给该方法。

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      相关资源
      最近更新 更多