Hi,
Note: This is not school homework, I have made an attempt, but wasn't sure if that was a reasonable approach, or if there is a better way to do it.
Overview
I have an array of numbers
I would like to group them into an array of arrays in the following way:
[[numbers[0], numbers[1], numbers[2],
[numbers[1], numbers[2], numbers[3],
...
...
[numbers[x], numbers[x+1], numbers[x+2],
[numbers[x+1], [numbers[x+2],
[numbers[x+2]]
Example:
If numbers = [23, 42, 19, 7, 150, 8, 20, 41]
Output would be as follows:
[[23, 42, 19], [42, 19, 7], [19, 7, 150], [7, 150, 8], [150, 8, 20], [8, 20, 41], [20, 41], [41]]
My implementation
let numbers = [23, 42, 19, 7, 150, 8, 20, 41]
let count = numbers.count
var groups = [[Int]]()
for index in 0 ..< count {
var group = [Int]()
group.append(numbers[index])
if index + 1 < count {
group.append(numbers[index + 1])
if index + 2 < count {
group.append(numbers[index + 2])
}
}
groups.append(group)
}
print(groups)
Questions:
- Is there a better way to achieve this?
- I thought my implementation was verbose and was hoping that there was a better way or is my approach reasonable?