Skip to content

Instantly share code, notes, and snippets.

@bdsaglam
Created March 29, 2020 08:56
Show Gist options
  • Select an option

  • Save bdsaglam/b41294540756768f26dca70d058f8e1e to your computer and use it in GitHub Desktop.

Select an option

Save bdsaglam/b41294540756768f26dca70d058f8e1e to your computer and use it in GitHub Desktop.
Swift array argmax and argmin
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