Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:16
Show Gist options
  • Save RussellAndrewEdson/2e41a83ea8a097371705 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/2e41a83ea8a097371705 to your computer and use it in GitHub Desktop.
Rule 3 for the MIU System.
# Returns true if we can apply Rule 3 to the given string.
# (Rule 3: If our string contains an instance of "III", we can replace
# that instance with "U".)
def can_apply_rule3?(str)
!(str.match(/III/).nil?)
end
# Returns an array of indices for the given string where Rule 3 can be applied.
def rule3_indices(str)
# First, we find all of the places where we have 3 or more I's.
matches_for_I = str.to_enum(:scan, /I{3,}/).map { Regexp.last_match }
# Now notice that we could have a match like "IIIII", where we actually
# have multiple ways to get the string "III" from this (eg. 3 ways here,
# starting from indices 0, 1 and 2.)
#
# We apply this idea to get the full set of indices. We determine the
# number of ways to find "III" in the given string of I's, and return
# that many indices (starting from 0) for each one.
indices = matches_for_I.map do |match|
match_length = match[0].length
number_of_IIIs = match_length - "III".length + 1
(0...number_of_IIIs).map { |i| i + match.begin(0) }.to_a
end
indices.flatten
end
# Applies Rule 3: Given the string and an index (that can be found
# using the rule3_indices() method), we replace the 3 characters at
# that index with a single U.
def apply_rule3(str, index)
changed_str = str.dup
changed_str[index...(index + "III".length)] = "U"
changed_str
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment