Last active
December 18, 2015 23:58
-
-
Save cmhobbs/5864821 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Consecutive | |
attr_reader :string, :totals | |
def initialize(string) | |
@string = string | |
@totals = count_characters | |
end | |
def max_consecutive_characters | |
matches | |
end | |
private | |
# Produce an array of tuples containing the consecutive characters in | |
# a string and its character, removing duplicates. Assume @string to | |
# be aaffffddddaa in this example: | |
# | |
# consecutive_characters | |
# => [ ["aa", "a"], ["dddd", "d"], ["ffff", "f"] ] | |
def consecutive_characters | |
string.scan(/((.)\2+)/).uniq | |
end | |
# Mangle the array of tuples from consecutive_characters to include a | |
# total. Using the previous example: | |
# | |
# count_characters | |
# => [ ["a", 2], ["d", 4], ["f", 4] | |
def count_characters | |
consecutive_characters.map { |tuple| [tuple.last, tuple.first.chars.count] } | |
end | |
# Do the real work. Grab all the counts and find the highest value, then | |
# produce an array of all characters matching that count. | |
def matches | |
highest_count = totals.map(&:last).max | |
totals.each.map { |character, count| character if count == highest_count }.compact.sort | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not as pretty as I'd like. I'd like to clean things up enough so that it's a little more intention revealing. I also don't like the looks of lines 10-12