Skip to main content
6 of 7
made variable name more expressive

Building a list - why is this code inefficient?

I'm attempting this code challenge.

Here's my code modified to handle one simple example test case:

string = "bcdefghij"

result = []

permutations = string.split('').permutation.to_a

string.size.times do
  permutations.each {|p| result << p.sort.join}
  permutations.map! {|p| p[1..-1]}
end

puts result.uniq.sort

It produces the correct result but it's way too slow. I've played around with benchmarking and it looks like the slowest part of the code is this line:

permutations.each {|p| result << p.sort.join}

Can I speed this code up somehow? Or am I thinking about the original problem all wrong?


RESULT

Thanks to Nat's answer below I came up with this:

string = "bcdefghij".split('')

result = []
(1..(string.size)).each {|i| result += string.combination(i).to_a}
puts result.map{|r| r.join}.sort

Benchmarks

Before: 6.480000 0.310000 6.790000 ( 6.794669)

After: 0.000000 0.000000 0.000000 ( 0.003087)