Given an array, for example:
[0, 0.5, 0.51, 1.0, 1.5, 1.99, 2.0, 2.1, 2.5, 3.0]
I want to group values into subarrays based on their successive differences (e.g. where abs(x-y) < n
and n = 0.2
), for example:
[[0], [0.5, 0.51], [1.0], [1.5], [1.99, 2.0, 2.1], [2.5], [3.0]].
I would like to do this declaratively - just to better understand how more complex sequence operations can work in a functional context (it seems that most of the "functional Swift" demos / tutorials are pretty simple).
Thanks in advance.
Update:
Here is a single line that seems to be close:
let times = [0, 0.5, 0.99, 1, 1.01, 1.5, 2, 2.5, 2.51, 3, 3.49, 3.5]
let result = times.map { t1 in
return times.filter { fabs($0 - t1) < 0.2 }
}
// [[0.0], [0.5], [0.99, 1.0, 1.01], [0.99, 1.0, 1.01], [0.99, 1.0, 1.01], [1.5], [2.0], [2.5, 2.51], [2.5, 2.51], [3.0], [3.49, 3.5], [3.49, 3.5]]
You just need to get rid of duplicates.