简体   繁体   中英

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'). 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?

ex: n = 3, combos include [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.

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. 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? Additionally, you shouldn't have to recompute things for each n in your each block. You should be able to cache your results and reuse them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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