简体   繁体   English

改善Ruby函数的性能排列

[英]Improve Ruby function performance permutations

I'm attempting to solve a problem with a 10 second timeout limit (if the function runs longer than 10 seconds, the code is deemed 'incorrect'). 我正在尝试解决10秒超时限制的问题(如果函数运行时间超过10秒,则代码被视为“错误”)。 The problem is given an integer (n), how many unique possible combinations of the numbers 1 and 2 can be made where the sum is n? 问题是给定一个整数(n),在总和为n的情况下,可以对数字1和2进行多少个唯一的可能组合?

ex: n = 3, combos include [1, 1, 1] [1, 2] [2, 1] 例如:n = 3,连击包括[1,1,1] [1,2] [2,1]

My code is "correct" but runs too slow for the compiler and is marked incorrect. 我的代码“正确”,但对于编译器而言运行太慢,并被标记为错误。 How can I make my code more efficient and why is it "slow"? 如何使我的代码更高效,为什么它“慢”? Also, it should be noted that n will NEVER exceed 1000. 另外,应注意,n永远不会超过1000。

require 'benchmark'

def stairs(n)
    possible_combos = []
    ((n/2)..n).each do |i|
        [1,2].repeated_permutation(i) do |combo|
            if combo.inject {|sum, num| sum + num } == n 
                possible_combos << combo 
            end
        end
    end
    puts possible_combos.uniq.length
end

puts Benchmark.measure {stairs(10)}

#=> 0.000000   0.000000   0.000000 (  0.003864)

puts Benchmark.measure {stairs(20)}

#=> 5.720000   0.040000   5.760000 (  5.762111)

There are a couple of inefficiencies. 效率低下。 The most glaring one is that you build out the total set of all permutations then prune that. 最明显的是您将所有排列的总和建立起来,然后进行修剪。 After that you also only take unique elements adding another order n operation. 之后,您还只需要添加唯一的元素即可添加另一个order n操作。 I would instead try to build the output right the first time. 相反,我会尝试在第一时间建立输出。 Perhaps use the fact you know the number is even or odd. 也许使用您知道数字是偶数还是奇数的事实。 You also know that any two ones could be squished together to make a 2. Can you think of something clever using that? 您还知道,可以将任意两个压在一起以组成一个2。您能想到使用它的巧妙方法吗? Additionally, you shouldn't have to recompute things for each n in your each block. 另外,您不必为每个块中的每个n重新计算事物。 You should be able to cache your results and reuse them 您应该能够缓存结果并重用它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM