-
-
Save below/28911699b03898b0c8e743e6caee3382 to your computer and use it in GitHub Desktop.
Is there a more efficient way to do this?
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
let scores = [("A", [5,3,5,3,5]), | |
("B", [6,6,6,6,6]), | |
("C", [3,2,4,4,3]), | |
("D", [2,5,3,5,4]), | |
("E", [7,7,7,7,7]), // The highest value is equal to scores.count | |
("F", [1,1,2,1,1]), // Each number can only occur scores.1.count times | |
("G", [4,4,1,2,2]) | |
] | |
// The goal is a "majority sort": The position is determined by the number that occurs the most. | |
// Expected result is ["F", "G", "C", "D", "A", "B", "E"] | |
func simpleSort(scores: [(String, [Int])]) -> [String] { | |
let participants = scores.count | |
func evaluate(score: (String, [Int]), participants: Int) -> [Int] { | |
var evaluation = [Int](repeating: 0, count: participants) | |
for value in score.1 { | |
for i in value - 1 ..< participants { | |
evaluation[i] += 1 | |
} | |
} | |
return evaluation | |
} | |
var evaluatedScores = [(String, [Int], [Int])]() | |
for score in scores { | |
let evaluation = evaluate(score: score, participants: 7) | |
evaluatedScores.append((score.0, score.1, evaluation)) | |
} | |
evaluatedScores.sort { a, b in | |
var index = 0 | |
while a.2[index] == b.2[index], index < a.2.count { | |
index += 1 | |
} | |
return a.2[index] > b.2[index] | |
} | |
return evaluatedScores.map { a in | |
return a.0 | |
} | |
} | |
func directSort(scores: [(String, [Int])]) -> [String] { | |
func indexForScore (score: (String, [Int]), participants: Int) -> Int { | |
let sortedScores = score.1.sorted(by: { a, b in | |
a < b | |
}) | |
var evaluation = [Int](repeating: 0, count: 7) | |
for value in sortedScores { | |
for i in value - 1 ..< 7 { | |
evaluation[i] += 1 | |
if evaluation[i] >= 3 { | |
return i | |
} | |
} | |
} | |
print ("BOOM") | |
return participants | |
} | |
var result = [String](repeating: "", count: scores.count) | |
for score in scores { | |
let index = indexForScore(score: score, participants: scores.count) | |
result[index] = score.0 | |
} | |
return result | |
} | |
simpleSort(scores: scores) | |
directSort(scores: scores) | |
// Result: ["F", "G", "C", "D", "A", "B", "E"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment