Created
May 23, 2017 11:25
-
-
Save witekbobrowski/ebed45c7c9634bbfe4e20174c23594ae to your computer and use it in GitHub Desktop.
HackerRank - Cracking the Coding Interview - Sorting: Comparator : Swift solution suggestion
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
import Foundation | |
class Player: Comparable { | |
var name: String | |
var score: Int | |
init(name: String, score: Int) { | |
self.name = name | |
self.score = score | |
} | |
static func < (lhs: Player, rhs: Player) -> Bool { | |
if lhs.score != rhs.score { | |
return lhs.score < rhs.score | |
} else { | |
return lhs.name < rhs.name | |
} | |
} | |
static func > (lhs: Player, rhs: Player) -> Bool { | |
if lhs.score != rhs.score { | |
return lhs.score > rhs.score | |
} else { | |
return lhs.name > rhs.name | |
} | |
} | |
static func == (lhs: Player, rhs: Player) -> Bool { | |
return lhs.score == rhs.score && lhs.name == rhs.name | |
} | |
} | |
var array: [Player] = [] | |
for _ in 0..<Int(readLine()!)! { | |
let info = readLine()!.components(separatedBy: " ").map { $0 } | |
array.append(Player(name: info[0], score: Int(info[1])!) | |
} | |
array.sorted(by: { $0 > $1 }).forEach( {print("\($0.name) \($0.score)")} ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment