如何将静态Ruby代码转换为动态Ruby代码

时间:2018-12-15 10:28:53

标签: ruby

以下代码创建一个数组数组。每个数组的大小为5,可能的值范围为0到7。

class Customer
{
    static std::vector<std::unique_ptr<Customer>> customers;
public:
    Customer()
    {
        customers->push_back(this);
    };
    ~Customer()
    {
        auto i = customers.find(this);
        if(i != customers.end())
            customers.erase(i);
    }
}

如果arr = [] 8.times do |n1| 8.times do |n2| 8.times do |n3| 8.times do |n4| 8.times do |n5| arr << [n1, n2, n3, n4, n5] end end end end end arr.size # => 32768 (在8中)和5(嵌套5次)是动态的,那么如何在不更改其功能的情况下将该代码转换为动态代码?例如,如果我必须得到一个大小为6而不是5的数组(如当前示例中所示),那么该代码应如何重写?

1 个答案:

答案 0 :(得分:7)

您似乎正在寻找Array#repeated_permutation

(0..7).to_a.repeated_permutation(5)

让我们检查一下:

(0..7).to_a.repeated_permutation(5).size
#=> 32768
(0..7).to_a.repeated_permutation(5).first(10)
#=> [[0, 0, 0, 0, 0], 
#    [0, 0, 0, 0, 1], 
#    [0, 0, 0, 0, 2], 
#    [0, 0, 0, 0, 3], 
#    [0, 0, 0, 0, 4], 
#    [0, 0, 0, 0, 5], 
#    [0, 0, 0, 0, 6], 
#    [0, 0, 0, 0, 7], 
#    [0, 0, 0, 1, 0], 
#    [0, 0, 0, 1, 1]]

注意:repeated_permutation返回枚举数。