Skip to content

Instantly share code, notes, and snippets.

@codelynx
Created July 17, 2022 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codelynx/b5ec8a01a7c8806ff0b8782ac5375229 to your computer and use it in GitHub Desktop.
Save codelynx/b5ec8a01a7c8806ff0b8782ac5375229 to your computer and use it in GitHub Desktop.
encoding and decoding equatable elements from Array.
//
// Array+RunLength.swift
// ZKit
//
// The MIT License (MIT)
//
// Copyright (c) 2020 Electricwoods LLC, Kaz Yoshikawa.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Make Run Length Encoding
//
// There are some cases where you like to compact number of sequnced same items over and over again.
// This piece of code usues run length encoding to compact them, and decode them to bring back to
// the original sequence of items.
//
// Usage:
// let numbers = [1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 5, 5, 5]
// let runs = numbers.makeRunLength() // [(element: 1, count: 3), (element: 2, count: 4), (element: 3, count: 1), (element: 4, count: 1), (element: 5, count: 4)]
// let duplicated = Array(runs: runs) // [1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 5, 5, 5]
extension Array where Element: Equatable {
func makeRunLength() -> [(element: Element, count: Int)] {
var runs = [(element: Element, count: Index)]()
var run: (element: Element, count: Index)?
for (index, value) in self.enumerated() {
if run?.element == value {
run?.count += 1
}
else {
if let run = run {
runs.append(run)
}
run = (element: value, count: 1)
}
}
if let run = run {
runs.append(run)
}
return runs
}
init(runs: [(element: Element, count: Int)]) {
var elements = Array()
for run in runs {
elements += Array(repeating: run.element, count: run.count)
}
self = elements
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment