如何在不使用太多内存的情况下在Ruby中查找字符串数组的所有排列?

时间:2022-05-31 21:21:56
line = gets
L=line.split(" ")

searchMap=L.permutation.map(&:join)
S =  gets

searchMap.each do |item|
    if S.include? item
        puts S.index(item)
        end
end

If L is very large then I get `join': failed to allocate from permutation from each.

如果L非常大,那么我得到`join':无法从每个的排列中分配。

2 个解决方案

#1


2  

What you're doing now is creating an enumerator which will yield one permutation at a time, not consuming much memory, then with the .map(&:join) you're putting everything that comes out of this enumerator into one gigantic array searchMap.

你现在正在做的是创建一个枚举器,它将一次产生一个排列,不会消耗太多内存,然后使用.map(&:join)将这个枚举器中的所有内容放入一个巨大的数组searchMap中。

Instead of that you should pull one permutation from the enumerator at a time and do your trick on that, instead of iterating over the gigantic array with searchMap.each:

而不是你应该一次从枚举器中提取一个排列并对其进行处理,而不是使用searchMap.each迭代巨大的数组:

line = gets
L=line.split(" ")

S =  gets

L.permutation do |item|
    if S.include? item.join
        puts S.index(item.join)
    end
end

#2


1  

You can calculate each permutation without computing others, check out this question "Finding n-th permutation without computing others" and you will find the answer in C.

你可以计算每个排列不计算人,看看这个问题,“发现第n个排列不计算人”,你会发现在C.答案

#1


2  

What you're doing now is creating an enumerator which will yield one permutation at a time, not consuming much memory, then with the .map(&:join) you're putting everything that comes out of this enumerator into one gigantic array searchMap.

你现在正在做的是创建一个枚举器,它将一次产生一个排列,不会消耗太多内存,然后使用.map(&:join)将这个枚举器中的所有内容放入一个巨大的数组searchMap中。

Instead of that you should pull one permutation from the enumerator at a time and do your trick on that, instead of iterating over the gigantic array with searchMap.each:

而不是你应该一次从枚举器中提取一个排列并对其进行处理,而不是使用searchMap.each迭代巨大的数组:

line = gets
L=line.split(" ")

S =  gets

L.permutation do |item|
    if S.include? item.join
        puts S.index(item.join)
    end
end

#2


1  

You can calculate each permutation without computing others, check out this question "Finding n-th permutation without computing others" and you will find the answer in C.

你可以计算每个排列不计算人,看看这个问题,“发现第n个排列不计算人”,你会发现在C.答案