Skip to content

Instantly share code, notes, and snippets.

@jakubpetrik
Last active February 5, 2021 09:01
Show Gist options
  • Save jakubpetrik/09eae429cb75981c0909 to your computer and use it in GitHub Desktop.
Save jakubpetrik/09eae429cb75981c0909 to your computer and use it in GitHub Desktop.
Run-length encoding in Swift.
/**
http://rosettacode.org/wiki/Run-length_encoding
Given a string containing uppercase characters (A-Z),
compress repeated 'runs' of the same character by storing the length of that run,
and provide a function to reverse the compression.
The output can be anything, as long as you can recreate the input with it.
*/
import Foundation
// "WWWBWW" -> [(3, W), (1, B), (2, W)]
func encode(input: String) -> [(Int, Character)] {
return input.characters.reduce([(Int, Character)]()) {
if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r; }
return $0 + [(1, $1)]
}
}
// [(3, W), (1, B), (2, W)] -> "WWWBWW"
func decode(encoded: [(Int, Character)]) -> String {
return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment