Created
March 21, 2019 19:47
-
-
Save Mrteller/db5577b2c1fb2a94633d2698245c6ac1 to your computer and use it in GitHub Desktop.
Min, Max, Enclosing rectangle on array of XY pairs of data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func minsOf(pairs: [(Int, Int)]) -> (Int, Int) { | |
return pairs.reduce((Int.max, Int.max)) { | |
(($0.0 < $1.0) ? $0.0 : $1.0, (($0.1 < $1.1) ? $0.1 : $1.1)) | |
} | |
} | |
func maxsOf(pairs: [(Int, Int)]) -> (Int, Int) { | |
return pairs.reduce((Int.min, Int.min)) { | |
(($0.0 > $1.0) ? $0.0 : $1.0, (($0.1 > $1.1) ? $0.1 : $1.1)) | |
} | |
} | |
func midsOf(pairs: [(Int, Int)]) -> (Int, Int) { | |
let mins = minsOf(pairs: pairs) | |
let maxs = maxsOf(pairs: pairs) | |
return (((maxs.0 - mins.0) / 2), ((maxs.1 - mins.1) / 2)) | |
} | |
func rectOfGraph(pairs: [(Int, Int)]) -> CGRect { | |
let maxs = pairs.reduce((Int.min, Int.min)) { | |
(($0.0 > $1.0) ? $0.0 : $1.0, (($0.1 > $1.1) ? $0.1 : $1.1)) | |
} | |
let mins = pairs.reduce((Int.max, Int.max)) { | |
(($0.0 < $1.0) ? $0.0 : $1.0, (($0.1 < $1.1) ? $0.1 : $1.1)) | |
} | |
return CGRect(x: mins.0, y: mins.1, width: maxs.0 - mins.0, height: maxs.1 - mins.1) | |
} | |
func rectOfGraph(pairs: [(Double, Double)]) -> CGRect { | |
let maxs = pairs.reduce((-Double.greatestFiniteMagnitude, -Double.greatestFiniteMagnitude)) { | |
(($0.0 > $1.0) ? $0.0 : $1.0, (($0.1 > $1.1) ? $0.1 : $1.1)) | |
} | |
let mins = pairs.reduce((Double.greatestFiniteMagnitude, Double.greatestFiniteMagnitude)) { | |
(($0.0 < $1.0) ? $0.0 : $1.0, (($0.1 < $1.1) ? $0.1 : $1.1)) | |
} | |
return CGRect(x: mins.0, y: mins.1, width: maxs.0 - mins.0, height: maxs.1 - mins.1) | |
} | |
let arrayOfPairs = [(1, 2), (2, 7), (3, 8), (10, -1)] | |
print("Minimum (x,y) \(minsOf(pairs: arrayOfPairs))") | |
print("Maximum (x,y) \(maxsOf(pairs: arrayOfPairs))") | |
print("Middle (center) (x,y) \(midsOf(pairs: arrayOfPairs))") | |
print("Enclosing rectangle (x,y, width, height) \(rectOfGraph(pairs: arrayOfPairs))") | |
//prints: | |
//Minimum (x,y) (1, -1) | |
//Maximum (x,y) (10, 8) | |
//Middle (center) (x,y) (4, 4) | |
//Enclosing rectangle (x,y, width, height) (1.0, -1.0, 9.0, 9.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment