Created
January 30, 2021 15:49
-
-
Save IhwanID/3e957ad75c44fe09a1706935925407b2 to your computer and use it in GitHub Desktop.
Get Most Common Element in Array
This file contains 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
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