cbmeeks
cbmeeks

Reputation: 11420

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

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!

Upvotes: 1

Views: 360

Answers (2)

Russell Hueske
Russell Hueske

Reputation: 151

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

Upvotes: 0

sawa
sawa

Reputation: 168101

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]]

Upvotes: 4

Related Questions