Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:16
Show Gist options
  • Save RussellAndrewEdson/3d36d30f9bc30c9adec4 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/3d36d30f9bc30c9adec4 to your computer and use it in GitHub Desktop.
Rule 4 for the MIU System.
# Returns true if we can apply Rule 4 to the given string.
# (Rule 4: If "UU" appears anywhere in our string, we can drop it.)
def can_apply_rule4?(str)
!(str.match(/UU/).nil?)
end
# Returns an array of indices for the given string where Rule 4 can be applied.
def rule4_indices(str)
# We find all of the places where we have 2 or more U's.
matches_for_U = str.to_enum(:scan, /U{2,}/).map { Regexp.last_match }
# Again, we can have matches like "UUUUU" where there are multiple "UU"s that
# we can choose from (eg. 4 of them here, starting from indices 0, 1, 2, 3.)
# To get the full set of indices, we find the number of ways to get "UU" in
# the larger "UUU..." string and return that many indices, starting from 0.
indices = matches_for_U.map do |match|
match_length = match[0].length
number_of_UUs = match_length - "UU".length + 1
(0...number_of_UUs).map { |i| i + match.begin(0) }.to_a
end
indices.flatten
end
# Applies Rule 4: Given the string and an index (that can be found
# using the rule4_indices() method), we drop the 2 characters at that index.
def apply_rule4(str, index)
changed_str = str.dup
changed_str[index...(index + "UU".length)] = ""
changed_str
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment