# 算法 用 Ruby 完成了同事的一个算法问题

qingxp9 · 2015年09月11日 · 最后由 love93hate 回复于 2018年08月27日 · 8302 次阅读

``````s="abcde"
t= Array.new(s.length) { Array.new(2) }

#生成二维数组
for i in 0...(s.length)
#处理数字
if s[i].to_i.to_s == s[i]
t[i][0]=s[i]
else
t[i][0]=s[i].upcase
t[i][1]=s[i].downcase
end
end

q=t[0].product
for i in 1...s.length
q=q.product(t[i])
end

q.each do |g|
puts g.join
end
``````

``````require 'pp'

def all_combi str
combi = ['']
# Split into upper and lower cases
chars = str.each_char.map { |c| c =~ /[[:alpha:]]/ ? [c.upcase, c.downcase] : [c]}
# Combine them
chars.each do |chs|
combi = combi.flat_map do |s|
chs.map { |ch| s + ch }
end
end
combi
end

combi = all_combi 'ru123by!'
pp combi
puts combi == combi.uniq
``````

``````for i in 1...s.length
q=q.product(t[i])
end
``````

``````(1..s.size).each do |i|
``````

``````t[1..-1].each do |ti|
``````

``````q.each do |g|
puts g.join
end
``````

``````result = q.map(&:join)
puts result
``````
``````def all_combi_origin str
combi = ['']
# Split into upper and lower cases
chars = str.each_char.map { |c| c =~ /[[:alpha:]]/ ? [c.upcase, c.downcase] : [c]}
# Combine them
chars.each do |chs|
combi = combi.product(chs)
end
combi.map(&:join)
end
``````

``````Benchmark.bm(20) do |x|
x.report('all_combi')        { 50_000.times { all_combi 'ru123by!' } }
x.report('all_combi_origin') { 50_000.times { all_combi_origin 'ru123by!' } }
x.report('all_combi_4楼')    { 50_000.times { all_combi_4楼 'ru123by!' } }
end

#                           user     system      total        real
#all_combi              1.540000   0.000000   1.540000 (  1.587790)
#all_combi_origin       2.780000   0.010000   2.790000 (  2.894336)
#all_combi_4楼          1.400000   0.000000   1.400000 (  1.443631)
``````
``````password = "abc123"

first, *rest = password.each_char.map do |char|
if char =~ /[[:alpha:]]/
[char.downcase, char.upcase]
else
[char]
end
end

result = first.product(*rest).map(&:join)
``````

@msg7086 @lolychee @hemslo

#5 楼 @hemslo :doge: 太下流了