我怎么整数组在Ruby阵列,这样我就可以融为一体$ P $数组PSS?

我怎么整数组在Ruby阵列,这样我就可以融为一体$ P $数组PSS?

问题描述:

假设我有一个整数数组中的红宝石2.1 + 如:

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]

我想这样做的是COM $ P $数组PSS,使我得到这样的:

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.

此外,顺序很重要。

**编辑*

对不起,我没有提到单个元素,我不关心计数。因此, [2,1] ... [1,1],[6,1] ... 不关心我。

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.

其实,我真的只在有4个或更多重复的整数组感兴趣,但我不想混淆问题。因此, [3,2] 可保留为 3,3 ,但 [3,4 ] 将被用来代替 3,3,3,3 ,但这不是问题的重要话题。

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.

谢谢!

有关红宝石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]]