Last active
April 21, 2020 08:48
-
-
Save amfathi/9e76b7a5274e301a6d3294236cc62e24 to your computer and use it in GitHub Desktop.
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 | |
| extension Array where Element == Int { | |
| /// Returns a decoded version of a delta encoded array | |
| public func deltaDecoded() -> [Element] { | |
| let filteredArray = filterArray(self) | |
| var cummulativeSum = 0 | |
| var decodedValues = [Element]() | |
| for value in filteredArray { | |
| cummulativeSum += value | |
| decodedValues.append(cummulativeSum) | |
| } | |
| return decodedValues | |
| } | |
| private func filterArray(_ array: [Int]) -> [Int] { | |
| var filtered = [Int]() | |
| var index = 0 | |
| while index < array.count { | |
| if array[index] == -128 { | |
| if index < array.count - 1, array[index + 1] == -128 { | |
| filtered.append(-128) | |
| index += 1 | |
| } | |
| } else { | |
| filtered.append(array[index]) | |
| } | |
| index += 1 | |
| } | |
| return filtered | |
| } | |
| } | |
| let result = [25626, -128, 131, -128, -1390, -100, -128, -24251, 84, -98, -128, 7275].deltaDecoded() | |
| print(result) | |
| // [25626, 25757, 24367, 24267, 16, 100, 2, 7277] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment