Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Created November 26, 2015 05:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijoshsmith/0fc11e5fb91382d410ff to your computer and use it in GitHub Desktop.
Save ijoshsmith/0fc11e5fb91382d410ff to your computer and use it in GitHub Desktop.
Swift array compression programming puzzle
import Foundation
/**
Returns a compacted array, with repeated values coalesced.
Example: [a, a, b, c, c, c] yields [(a, 2), (b, 1), (c, 3)]
*/
func compressArray<T: Comparable>(input: [T]) -> [(T, Int)] {
// TODO - implement this function
return []
}
/**
Returns the original, expanded form of a compressed array.
Example: [(a, 2), (b, 1), (c, 3)] yields [a, a, b, c, c, c]
*/
func decompressArray<T>(input: [(T, Int)]) -> [T] {
// TODO - implement this function
return []
}
let uncompressedInts = [
8, 8, 8,
2, 2, 2, 2, 2, 2, 2, 2, 2,
8,
3,
5, 5, 5, 5,
0, 0, 0, 0, 0, 0, 0,
9]
let expectedCompressedArray = [
(8, 3),
(2, 9),
(8, 1),
(3, 1),
(5, 4),
(0, 7),
(9, 1)]
let compressedArray = compressArray(uncompressedInts)
let isCompressionCorrect = compressedArray.elementsEqual(expectedCompressedArray) {
$0.0 == $1.0 && $0.1 == $1.1
}
if isCompressionCorrect {
print("Compression success!")
} else {
print("Compression failure: \(compressedArray)")
}
let decompressedArray = decompressArray(compressedArray)
let isDecompressionCorrect = decompressedArray == uncompressedInts
if isDecompressionCorrect {
print("Decompression success!")
} else {
print("Decompression failure: \(decompressedArray)")
}
@ijoshsmith
Copy link
Author

Your functions work properly when the program's output is:
Compression success!
Decompression success!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment