Counting Consecutive Runs of Symbols

A run consists of adjacent equal symbols. Tracking its length can summarize a sequence while preserving changes in order.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace three runs
  2. Flush the last observation
  3. Trace a singleton run between repeating values
  4. Keep the match relation and length unit explicit

Trace three runs

For A, A, B, A, the output is (A, 2), (B, 1), (A, 1). A total count of A would merge both A runs. Adjacent pair comparisons provide the signal marking a new run.

Flush the last observation

Changing from A to B emits the preceding A run. The last run has no next symbol to trigger emission. Finish it after the loop and handle an empty input separately. Loop accumulators describe why the last retained run is still part of the result.[1]

Trace a singleton run between repeating values

The stream A A B A A A yields runs (A,2), (B,1) and (A,3). A frequency map instead produces five A symbols and one B and loses where the switch happened. On reading a different symbol, emit the previous run and start its successor at length one. Flush the final run when the stream ends. Test one record and empty input to distinguish real singleton and uninitialized state. See grouping by key.

Keep the match relation and length unit explicit

For text, counting bytes, code points or displayed grapheme clusters can give different runs. For state logs, two status codes may be equivalent after normalization. When compressing, an encoded run also needs a way to distinguish a literal symbol from a length field. Storing pairs is a clear intermediate representation and makes it easy to check that the sum of run lengths equals input size. See character positions in Unicode.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩