How do I group integers in a Ruby array so that I can compress the array?

守給你的承諾、 提交于 2019-12-11 13:34:51

问题


Assuming I have an array of integers in Ruby 2.1+ such as:

[2, 4, 4, 1, 6, 7, 5, 5, 5, 5, 5, 5, 5, 5]

What I would like to do is compress the array so that I get something like:

[2, [4, 2], 1, 6, 7, [5, 8]]

Notice the two internal arrays just contain two elements. The value and the number of times it is repeated.

Also, the order is important.

**EDIT*

Sorry, I didn't mention that for single elements, I'm not concerned with the count. So [2,1]...[1,1],[6,1]... doesn't concern me.

In fact, I'm really only interested in groups that have 4 or more repeating integers but I didn't want to confuse the issue. So [3,2] could be left as 3,3 but [3,4] would be used instead of 3,3,3,3 but this isn't important for the topic of the question.

Thanks!


回答1:


For Ruby 2.2:

[2, 4, 4, 1, 6, 7, 5, 5, 5, 5, 5, 5, 5, 5]
.slice_when(&:!=)
.map{|a| a.length == 1 ? a.first : [a.first, a.length]}
# => [2, [4, 2], 1, 6, 7, [5, 8]]

For older Ruby:

[2, 4, 4, 1, 6, 7, 5, 5, 5, 5, 5, 5, 5, 5]
.chunk{|e| e}
.map{|e, a| a.length == 1 ? e : [e, a.length]}
# => [2, [4, 2], 1, 6, 7, [5, 8]]



回答2:


not as efficient as the others, but oh well.

EDIT: as commented below, this is an example of how not to do this. Ruby has an amazing library of methods built into the Array class, and it should be utilized instead of using indices.

arr = [2, 4, 4, 1, 6, 7, 5, 5, 5, 5, 5, 5, 5, 5]
tempArr = []
newArr = []
for i in 0..(arr.length - 1)
    if arr[i] == arr[i + 1] && arr[i] != arr[i - 1]
        tempArr = [arr[i], 1]
    elsif tempArr[0] == arr[i]
        tempArr[1] += 1
        if arr[i - 1] == arr[i] && arr[i + 1] != tempArr[0]
            newArr.push(tempArr)
        end
    elsif arr[i] != tempArr[0]
        newArr.push(arr[i])
        if tempArr[0] != nil
            tempArr = []
        end
    end
end


来源:https://stackoverflow.com/questions/28242520/how-do-i-group-integers-in-a-ruby-array-so-that-i-can-compress-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!