索引数组到范围数组 [英] Array of indexes to array of ranges
本文介绍了索引数组到范围数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ruby 中的范围非常酷.我最终得到这样的数组:
Ranges in ruby are pretty cool. I end up with arrays such as this:
geneRanges = [(234..25), (500..510), (1640..1653)]
随后必须删除其中的一些内容.为此,我:
And subsequently have to remove bits of them. For that I:
genePositions = geneRanges.collect {|range| range.entries }.flatten
=> [500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653]
他们被操纵了,所以一些数字被排除在外,其他的可能会被添加.我可能会这样:
They get manipulated, so some numbers get excluded, and others may be added. I may end up with this:
[505, 506, 507, 600, 601, 602, 603, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653, 1654]
如何将其转换回紧凑的范围数组?好像应该存在反函数吧?我希望它返回这样的东西:
How can I convert this back into a compact array of ranges? It seems that the inverse function should exist? I would expect it to return something like this:
[(505..507), (600..603), (1643..1654)]
谢谢!
推荐答案
(新的和改进的.在冰箱中保持新鲜长达两周!):
(New and improved. Stays fresh in your refrigerator for up to two weeks!):
a = [1, 2, 3, 10, 11, 20, 20, 4]
ranges = a.sort.uniq.inject([]) do |spans, n|
if spans.empty? || spans.last.last != n - 1
spans + [n..n]
else
spans[0..-2] + [spans.last.first..n]
end
end
p ranges # [1..4, 10..11, 20..20]
这篇关于索引数组到范围数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文