loading...

re: Daily Challenge #220 - What Dominates Your Array? VIEW POST

FULL DISCUSSION
 

Swift solution :

func dominator(_ arr: [Int]) -> Int {
    arr.reduce(into: (dominator: -1,record: 0)) { (occur, currentNumber) in
        let numberOfTime = arr.filter { $0 == currentNumber }.count
        if numberOfTime > arr.count / 2 && numberOfTime > occur.1 {
            occur.dominator = currentNumber
            occur.record = numberOfTime
        }
    }.dominator
}

dominator([3,4,3,2,3,1,3,3]) // 3
dominator([1,1,1,2,2,2]) // -1
dominator([1,1,1,2,2,2,2]) // 2

And hardcore version :

func dominator(_ arr: [Int]) -> Int {
    (arr.reduce(into: [(Int,Int)]()) { (result, i) in
        result.append((i, arr.filter({ i == $0 }).count ))
    }
    .sorted { $0.1 > $1.1 }
    .first { $0.1 > arr.count / 2 })?.0 ?? -1
}
code of conduct - report abuse