我有以下代码来列出给定字符串的所有可能排列。但是由于我笨拙的列表(ruby 数组)操作和对函数式编程的了解有限,我不得不使用 flatten 来获取结果数组。这几乎是一个黑客。如何重构代码并避免使用(滥用)展平?
class String
def remove_char_at(i)
if i==0
self[1..-1]
else
self[0..i-1] + self[i+1..-1]
end
end
end
def permute(str,prefix="")
if str.size==0
prefix
else
str.chars.each_with_index.map do |s,i|
permute(str.remove_char_at(i),prefix+s)
end.flatten
end
end
最佳答案
您可以在 SICP 的第一章中找到有关函数式编程的有趣内容
def permute2(str,prefix="")
if str.size==0
[prefix] #revise for concatenate with memo
else
str.chars.each_with_index.inject([]) do |memo, ary|
s = ary[0]
i = ary[1]
memo += permute2(str.remove_char_at(i),prefix+s) #memoize
end
end
end
关于ruby - 如何微调 map 功能并避免使用展平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11819515/