I have some data…
let points = [(718, 620), (4596, 1280), (410, 333), (4597, 993),
(410, 337), (4597, 996), (428, 337), (4597, 1000), (431, 335), (4599, 1044)]
… that follows the pattern
[(pointStartOne.x, pointStartOne.y), (pointEndOne.x, pointEndOne.y),
(pointStartTwo.x, pointStartTwo.x) // ...
I need to structure it to
typealias PointPair = [(start: Point, end: Point)]
struct Point {
let x: Int
let y: Int
}
Here is my code:
var result: PointPair = []
while i < points.count{
result.append((Point(x: points[i].0, y: points[i].1), Point(x: points[i+1].0, y: points[i+1].1)))
i+=2
}
I think maybe it is nice situation to use functional programming reduce
Here is code ituitive:
let result = zip((points.enumerated().filter({ (offset: Int, element: (Int, Int)) -> Bool in
return offset%2==0
})), (points.enumerated().filter({ (offset: Int, element: (Int, Int)) -> Bool in
return offset%2==1
}))).reduce(PointPair(), { (result: PointPair, arg) -> PointPair in
let (one, other) = arg
let (offset, point) = one
let (offsetTwo, otherPoint) = other
return result + [(Point(x: point.0,y: point.1), Point(x: otherPoint.0,y: otherPoint.1))]
})
It is messy. Trying to use functional programming conveniently and elegantly.
Here is the improved code:
result = points.enumerated().reduce(into: PointPair(), {(temp, arg) in
let (offset, point) = arg
if offset % 2 == 0{
temp += [(Point(x: point.0, y: point.1), Point(x: 0, y: 0) )]
}
else if let last = temp.last {
temp[temp.count - 1] = (last.0, Point(x: point.0, y: point.1))
}
})