Created
March 29, 2020 08:56
-
-
Save bdsaglam/b41294540756768f26dca70d058f8e1e to your computer and use it in GitHub Desktop.
Swift array argmax and argmin
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
| extension Array where Element: Comparable { | |
| func argmax() -> Index? { | |
| return indices.max(by: { self[$0] < self[$1] }) | |
| } | |
| func argmin() -> Index? { | |
| return indices.min(by: { self[$0] < self[$1] }) | |
| } | |
| } | |
| extension Array { | |
| func argmax(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows-> Index? { | |
| return try indices.max { (i, j) throws -> Bool in | |
| try areInIncreasingOrder(self[i], self[j]) | |
| } | |
| } | |
| func argmin(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows-> Index? { | |
| return try indices.min { (i, j) throws -> Bool in | |
| try areInIncreasingOrder(self[i], self[j]) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment