我在努力解决距离提取
每次单击“尝试”,我都会看到
Test Results:
✘ Expected: "-6,-3-1,3-5,7-11,14,15,17-20", instead got: [-6, -3..1, 3..5, 7..11, 14, 15, 17..20]那么,-3-1和-3..1有什么不同呢?那是窃听器吗?这是我写Ruby的第一天,所以我无法判断这是我的代码
def solution(list)
result = []
arr = []
list.each.with_index{
|x,index|
arr.push(x)
if index == list.length-1
result.push(arr)
break
end
if list[index + 1] - x != 1
result.push(arr)
arr = []
end
}
final = []
result.each{
|x|
if x.length >= 3
final.push(Range.new(x[0],x[-1]))
else
final.concat(x)
end
}
final
end
puts solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]).inspect
# returns "-6,-3-1,3-5,7-11,14,15,17-20"发布于 2017-04-23 17:41:08
"-6,-3-1,3-5,7-11,14,15,17-20"是一个字符串,[-6, -3..1, 3..5, 7..11, 14, 15, 17..20]是一个范围和整数数组。
可以替换solution方法的最后一行,以强制数组采用所需的格式:
final.map do |x|
if x.is_a? Range
[x.min, x.max].join("-")
else
x.to_s
end
end.join(",")发布于 2017-04-23 18:59:12
多亏了slice_when,您可以编写一个更短、更简单的Ruby解决方案:
def solution(list)
list.slice_when { |x, y| y > x + 1 }.flat_map do |neighbors|
if neighbors.size > 2
"#{neighbors.first}-#{neighbors.last}"
else
neighbors
end
end.join(',')
end发布于 2017-04-24 07:22:22
这里还有另外两种方法。
array = [-6, -3, -2, -1, 0, 3, 5, 7, 8, 9, 14, 15, 17]Enumerable#chunk_while #1使用
而 (Rubyv2.3中的新版本)是什么时候 (Rubyv2.2中的新版本)的另一面,@Eric在他的回答中使用了这一点。
array.chunk_while { |x,y| y == x+1 }.map { |a|
a.size == 1 ? a.first.to_s : "#{ a.first }-#{ a.last }" }.join(",")
#=> "-6,-3-0,3,5,7-9,14-15,17"请注意,
array.chunk_while { |a,b| b == a+1 }.to_a
#=> [[-6], [-3, -2, -1, 0], [3], [5], [7, 8, 9], [14, 15], [17]]#2步骤通过数组
first, *rest = array
rest.each_with_object([[first]]) { |n, arr|
(n == arr.last.last+1) ? (arr.last << n) : (arr << [n]) }.
map { |a| (a.size == 1)? a.first.to_s : "#{ a.first }-#{ a.last }" }.join(",")
#=> "-6,-3-0,3,5,7-9,14-15,17"https://stackoverflow.com/questions/43574166
复制相似问题