Last active
August 27, 2019 01:49
-
-
Save drewag/7d493480e10675e7cfaa5514b1aa029e to your computer and use it in GitHub Desktop.
Compare Triplets Algorithms
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 | |
typealias Algorithm = (name: String, execute: ([Int],[Int]) -> [Int]) | |
let algorithms: [Algorithm] = [ | |
(name: "Drewag", { a, b in | |
return zip(a,b) | |
.map{( | |
$0 > $1 ? 1 : 0, | |
$1 > $0 ? 1 : 0 | |
)} | |
.reduce(into: [0,0], { | |
$0[0] += $1.0 | |
$0[1] += $1.1 | |
}) | |
}), | |
(name: "Drewag Lazy", { a, b in | |
return zip(a,b) | |
.map{( | |
$0 > $1 ? 1 : 0, | |
$1 > $0 ? 1 : 0 | |
)} | |
.reduce(into: [0,0], { | |
$0[0] += $1.0 | |
$0[1] += $1.1 | |
}) | |
}), | |
(name: "Yappdeveloper", { a, b in | |
let combo = Array(zip(a,b)) | |
return [combo.map { $0 > $1 }.filter{$0}.count , combo.map { $0 < $1 }.filter{$0}.count] | |
}), | |
(name: "Imperative", { a, b in | |
var score = (a: 0, b: 0) | |
for i in 0 ..< min(a.count, b.count) { | |
if a[i] > b[i] { | |
score.a += 1 | |
} | |
if b[i] > a[i] { | |
score.b += 1 | |
} | |
} | |
return [score.a, score.b] | |
}), | |
] | |
print("Array Size," + algorithms.map({"\($0.name)"}).joined(separator: ",")) | |
var a = [Int]() | |
var b = [Int]() | |
for arraySize in stride(from: 100, through: 1000, by: 100) { | |
while a.count < arraySize { | |
let next = Int.random(in: 1 ... 10) | |
a.append(next) | |
b.append(next) | |
} | |
var times = [String]() | |
for (_, algorithm) in algorithms { | |
let start = Date() | |
for _ in 0 ..< 1000 { | |
algorithm(a, b) | |
} | |
times.append(String(format: "%0.3f", Date().timeIntervalSince(start))) | |
} | |
print("\(arraySize)," + times.joined(separator: ",")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: