索引数组到范围数组
ruby 中的范围非常酷。 我最终得到这样的数组:
geneRanges = [(234..25), (500..510), (1640..1653)]
随后必须删除其中的一些部分。为此,我:
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]
它们被操纵了,因此一些数字被排除,而其他数字可能被添加。我可能会得到这样的结果:
[505, 506, 507, 600, 601, 602, 603, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653, 1654]
如何将其转换回紧凑的范围数组?看来反函数应该存在?我希望它返回这样的内容:
[(505..507), (600..603), (1643..1654)]
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
(新的和改进的。在冰箱中可保持新鲜长达两周!):
(New and improved. Stays fresh in your refrigerator for up to two weeks!):
功能性的、不太可读的解决方案:
也是一个不错的解决方案:
Functional, not-very-readable solution:
And a nice one:
这是 Wayne Conrads 算法的直接婴儿床,经过一些小调整,使其适用于其他类型的范围,例如字母顺序
,执行的结果是
This is a straight crib of Wayne Conrads algorithm with a small tweak to make it work for other kinds of ranges, e.g. alphabetic
And the results of executing this are
这是一个答案(改编自此代码),其速度是其他代码的两倍多发布在这里。此外,只有这个答案和@Steve的答案 处理非整数数组。
以下是基准测试结果:
所有基准测试代码都经过修改以删除
sort.uniq
以进行公平比较。Here's an answer (adapted from this code) that is more than twice as fast as the other code posted here. Further, only this answer and the one by @Steve handle arrays of non-integers.
Here are the benchmark results:
All benchmarked code was adapted to remove
sort.uniq
for a fair comparison.我从来没有在 Ruby 语言中见过任何可以做到这一点的代码,但这里有一些代码可以帮助您自己完成此操作:
http://snippets.dzone.com/posts/show/4677
I've never seen anything in the Ruby language that does that, but here is some code that might help you do it yourself:
http://snippets.dzone.com/posts/show/4677
对于未排序的数组,您可以对其进行预排序:
and for not sorted arrays you can presort it: