Skip to content

Instantly share code, notes, and snippets.

@tlwr
Last active January 29, 2021 13:23
Show Gist options
  • Select an option

  • Save tlwr/6c5c90f1a9060274e9379db51d7a6d78 to your computer and use it in GitHub Desktop.

Select an option

Save tlwr/6c5c90f1a9060274e9379db51d7a6d78 to your computer and use it in GitHub Desktop.

Revisions

  1. tlwr revised this gist Jan 29, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion compress_strings.rb
    Original file line number Diff line number Diff line change
    @@ -14,5 +14,5 @@
    # => "a3bc3"
    "aaabccc"
    .scan(/(?<ct>(?<c>.)\k<c>{1,})|((?<d>.)\k<d>{0})/)
    .map { |dups, dup, single| dups.nil? ? single : "#{dup}#{dups.length}"}
    .map { |dups, dup, single| dups.nil? ? single : "#{dup}#{dups.length}" }
    .join
  2. tlwr created this gist Jan 29, 2021.
    18 changes: 18 additions & 0 deletions compress_strings.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    #!/usr/bin/env ruby

    # if a character is followed by itself 1 or more times it is considered a duplicate
    #
    # the regular expression /(?<ct>(?<c>.)\k<c>{1,})|((?<d>.)\k<d>{0})/
    # * capture group c captures a character
    # * capture group ct captures the total string of duplicately matched charactesr
    # * capture group d matches a character on its own
    #
    # scan therefore produces the following
    # => [["aaa", "a", nil], [nil, nil, "b"], ["ccc", "c", nil]]
    #
    # which we can then combine into a compressed string using map
    # => "a3bc3"
    "aaabccc"
    .scan(/(?<ct>(?<c>.)\k<c>{1,})|((?<d>.)\k<d>{0})/)
    .map { |dups, dup, single| dups.nil? ? single : "#{dup}#{dups.length}"}
    .join