Skip to content

Instantly share code, notes, and snippets.

@IhwanID
Created January 30, 2021 15:49
Show Gist options
  • Save IhwanID/3e957ad75c44fe09a1706935925407b2 to your computer and use it in GitHub Desktop.
Save IhwanID/3e957ad75c44fe09a1706935925407b2 to your computer and use it in GitHub Desktop.
Get Most Common Element in Array
var colorArray = ["blue", "white", "yellow", "red","blue", "white", "yellow", "red","blue", "white", "yellow", "red","blue", "white", "yellow", "red","blue", "white", "yellow", "red","yellow", "red","yellow", "red","yellow", "red", "red"]
func getMostColor(input: [String]) -> String{
var topColor: String = ""
var colorDict: [String:Int] = [:]
for color in input{
colorDict[color, default:0]+=1
}
let highestValues = colorDict.values.max()
for (color, count) in colorDict{
if colorDict[color] == highestValues{
topColor = color
}
}
return topColor
}
getMostColor(input: colorArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment