Assume we want to shift an array like it is done in the 2048 game: if we have two equal consecutive elements in array, merge them into twice the value element.
Shift must return a new array, where every pair of consecutive equal elements is replaced with their sum, and pairs should not intersect.
Shifting is performed only once, so we don't need to merge resulting values again.
Notice that if we have 3 consecutive equal elements, we have to sum rightmost ones, so for example, [2, 2, 2]
should become [2, 4]
, not [4, 2]
.
The task is to write shortest function which takes an array and returns a shifted array.
Examples:
[2, 2, 4, 4] -> [4, 8]
[2, 2, 2, 4, 4, 8] -> [2, 4, 8, 8]
[2, 2, 2, 2] -> [4, 4]
I am also very interested in solution using reduce :)
0
or1
? Can the input array be empty? – mbomb007 3 hours ago