#sagar
def combi str
size = str.size
arr = (0..size).flat_map { |i| (i+1..size).map { |j| str[i...j] } }
#=> ["a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd","d"]
(1..size).flat_map { |k|
arr.combination(k).select { |a| a.inject(:+) == str }
}.sort
end
#navid
def sequence(n)
[true, false].repeated_permutation(n).to_a
end
def breakdown4(string)
guide = sequence(string.length-1)
arr = []
guide.each do |i|
s = string.dup
counter = 0
i.each do |j|
if j
s.insert(counter+1, " ")
#p counter
counter += 2
else
counter += 1
end
end
arr.push(s)
end
arr
end
#tom
def powerset(arr)
a = [[]]
for i in 0...arr.size do
len = a.size; j = 0;
while j < len
a << (a[j] + [arr[i]])
j+=1
end
end
a
end
def breakdown(string)
indexes_lists = powerset((1..string.length-1).to_a)
indexes_lists.map(&:reverse).map do |indexes_list|
result = string.dup
indexes_list.each { |i| result.insert(i, " ")}
result
end
end
#stefan
def stefan1 s
[s[0]].product(*s[1..-1].chars.flat_map { |c| [[' ', ''], [c]] }).map(&:join)
end
def stefan2 s
s[1..-1].chars.reduce([s[0]]) { |m, c| m.product([' ', ''], [c]) }.map(&:join)
end
def stefan3 s
[''].product(*([[' ', '']] * s.size.pred)).map { |j| s.gsub('') { j.shift } }
end
require 'fruity'
str = 'abcd'
compare do
sagar { s = str.dup; combi(s).map {|st| st.join ' '} }
navid { s = str.dup; breakdown4(s).sort}
tom { s = str.dup; breakdown(s).sort }
stefan_1 { s = str.dup; stefan1(s).sort }
stefan_2 { s = str.dup; stefan2(s).sort }
stefan_3 { s = str.dup; stefan2(s).sort }
end
#Running each test 32 times. Test will take about 1 second.
#tom is similar to navid
#navid is similar to stefan_1
#stefan_1 is similar to stefan_3
#stefan_3 is similar to stefan_2
#stefan_2 is faster than sagar by 17x ± 1.0