Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func timingDicts() {
- let keyTimeValues: [TimeInterval: Float] = [
- 0.4: 0.0,
- 0.45: 1.0,
- 0.475: 1.0,
- 0.5: 1.0,
- 0.525: 1.0,
- 0.55: 0.0,
- 0.575: 1.0,
- 0.6: 1.0,
- 0.65: 1.0,
- 0.7: 0.0
- ]
- /// The challenge:
- /// The keys represent animation key times, the values represent values. Some key times repeat the same value of the previous keytime.
- /// How would you reduce the above dictionary in such way that the values do not repeat themselves
- /// more than once?
- /// For example, this group:
- /// 0.45: 1.0,
- /// 0.475: 1.0,
- /// 0.5: 1.0,
- /// 0.525: 1.0,
- ///
- /// The keytime 0.475 and 0.5 don't change the value and are, therefore, redundant in key frame animations.
- ///
- /// Expected outcome:
- let expectedOutcome: [TimeInterval: Float] = [
- 0.4: 0.0,
- 0.45: 1.0,
- 0.525: 1.0,
- 0.55: 0.0,
- 0.575: 1.0,
- 0.65: 1.0,
- 0.7: 0.0
- ]
- //I don't like the triple "iterations":
- // - sorted on keys
- // - `reduce(into:_:)`
- // - reconstruct the Dictionary, with `reduce(into:_:)` or `Dictionary(uniqueKeysWithValues:)`
- // But I guess it's better for comparison than retrieve each time what is the "previous value", and before that one at each iteration
- let outputTupled = keyTimeValues.sorted { $0.key < $1.key }
- .reduce(into: [(TimeInterval, Float)]()) { partialResult, current in
- guard partialResult.count > 1 else {
- partialResult.append(current)
- return
- }
- let previous = partialResult[partialResult.count - 1]
- let beforeLast = partialResult[partialResult.count - 2]
- if current.value == previous.1, previous.1 == beforeLast.1 {
- partialResult[partialResult.count - 1] = current
- } else {
- partialResult.append(current)
- }
- }
- let output = outputTupled.reduce(into: [TimeInterval: Float]()) { $0[$1.0] = $1.1 }
- printDict(dict: output)
- printDict(dict: expectedOutcome)
- print(output == expectedOutcome)
- let output2 = Dictionary(uniqueKeysWithValues: outputTupled) //Is there some optimization here, might be better than `reduce(into:_:)`
- printDict(dict: output2)
- printDict(dict: expectedOutcome)
- print(output2 == expectedOutcome)
- //To print in "order", easier to debug what went wrong, since the print doesn't guarantee the order if we want to compare
- func printDict(dict: [TimeInterval: Float]) {
- var printContent = Array(dict.keys).sorted { $0 < $1 }.map { "\t\($0): \(dict[$0]!)" }.joined(separator: ",\n")
- print("[\n\(printContent)\n]")
- }
- }
- timingDicts()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement