Grouping consecutive numbers in an array
来源:互联网 发布:网络直播平台监管 编辑:程序博客网 时间:2024/05/21 19:34
I need to add consecutive numbers to a new array and, if it is not a consecutive number, add only that value to a new array:
old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]
I want to get this result:
new_array = [ [1,2,3], [5], [7,8,9] [20,21] [23], [29]]
it is possible to do this in a very compact way:
arr = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]arr.inject([]) { |a,e| (a[-1] && e == a[-1][-1] + 1) ? a[-1] << e : a << [e]; a }# [[1, 2, 3], [5], [7, 8, 9], [20, 21], [23], [29]]
Alternatively, starting with the first element to get rid of the
a[-1]
condition (needed for the case whena[-1]
would benil
becausea
is empty):arr[1..-1].inject([[arr[0]]]) { |a,e| e == a[-1][-1] + 1 ? a[-1] << e : a << [e]; a }
0 0
- Grouping consecutive numbers in an array
- Find consecutive elements in an array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Leetcode_Array_Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- leetcode_Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- leetcode 448Find All Numbers Disappeared in an Array (array)
- LeetCode-Array-448. Find All Numbers Disappeared in an Array
- eclipse中编译好的jsp文件在哪里
- 玩苹果为什么要越狱?
- SSDT HOOK的恢复
- 友情推荐:《失业的程序员》终极花絮
- JavaScript中select、js对象、js数组复合操作
- Grouping consecutive numbers in an array
- python实现阶乘阶乘--reduce函数
- c++获取文件夹路径(不是文件哦。。。)及程序当前路径
- js中window.opener和window.parent的用法
- windows下Android(安卓)开发环境搭建 图文教程
- 【Python】Pyhton中函数的下划线命名规则www.zhihu.com/question/19754941
- 烟花
- Python下使用串口控制蓝牙模块------高级语言与底层应用的碰撞
- ActionScript3.0利用鼠标指针控制影片剪辑的播放停止