def consecutive_slice(arr):
yield arr
mx = len(arr) + 1
for size in xrange(2, mx):
for i in xrange(mx - size):
yield(arr[:i] + [''.join(arr[i:i+size])] + arr[i+size:])
def adj(ar)
result = [ar]
2.upto ar.size do |j|
0.upto ar.size-j do |i|
result << [*ar[0, i], ar[i,j].join.to_i, *ar[i+j..-1]]
end
end
result
end
试验
^{pr2}$
编辑
如果你想让它与Ruby1.8.7兼容(上面是1.9+)
def adj(ar)
result = [ar]
2.upto ar.size do |j|
0.upto ar.size-j do |i|
result << [ar[0, i], ar[i,j].join.to_i, ar[i+j..-1]].flatten
end
end
result
end
a = (1..5).to_a
adj a
#=> same result
下面是一个Python版本(编辑了以使其更简洁;多亏了FMc的建议):
使用示例:
^{pr2}$试验
^{pr2}$编辑
如果你想让它与Ruby1.8.7兼容(上面是1.9+)
我改进了之前的代码。
会给你:
^{pr2}$相关问题 更多 >
编程相关推荐