YAPC::EU 2018 Glasgow Update!

This commit is contained in:
Ingy döt Net 2018-08-17 15:15:24 +01:00
parent 22f33d4004
commit 4e2d22a71d
1170 changed files with 15042 additions and 3047 deletions

View file

@ -23,7 +23,7 @@ extension op
]
}
public program =
public program
[
var anArray1 := (1, 1, 2, 4, 4).
var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17).
@ -34,4 +34,4 @@ public program =
printLine("mode of (",anArray2,") is (",anArray2 mode,")");
printLine("mode of (",anArray3,") is (",anArray3 mode,")");
readChar.
].
]

View file

@ -1,7 +1,4 @@
# Project : Averages/Mode
# Date : 2018/04/11
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]
b = [1, 2, 4, 4, 1]

View file

@ -0,0 +1,27 @@
// Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method.
extension Collection where Element: Hashable {
/// Return a Mode of the function, or nil if none exist.
func mode() -> Element? {
var frequencies = [Element: Int]()
// Standard for loop. Can also use the forEach(_:) or reduce(into:) methods on self.
for element in self {
frequencies[element] = (frequencies[element] ?? 0) + 1
}
// The max(by:) method used here to find one of the elements with the highest associated count.
if let ( mode, _ ) = frequencies.max(by: { $0.value < $1.value }) {
return mode
} else {
return nil
}
}
}
["q", "a", "a", "a", "a", "b", "b", "z", "c", "c", "c"].mode() // returns "a"
[1, 1, 2, 3, 3, 3, 3, 4, 4, 4].mode() // returns 3
let emptyArray: [Int] = []
emptyArray.mode() // returns nil