Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scoring for repeated characters in ruby.
# for http://codegolf.stackexchange.com/q/112827/31957
def repeated_chars(r, can_repeat = false)
-> (s) {
found = {}
repeated = ""
s.chars.each { |c|
found[c] = true if can_repeat
if r === c
if found.has_key? c
repeated += c
else
found[c] = true
end
end
}
repeated
}
end
class Repeater
def initialize(regex, penalty, can_repeat = false)
@regex = regex
@rep = repeated_chars(regex, can_repeat)
@penalty = penalty
end
def [](s)
rs = @rep[s]
[rs, rs.size * @penalty]
end
end
rep_alnum = Repeater.new(/[A-Za-z0-9]/, 3)
rep_punct = Repeater.new(/[\(\[!?.\-,":';\]\)]/, 2)
rep_other = Repeater.new(/[{`~@#$%^&*_+=|\\\/><}]/, 4)
rep_space = Repeater.new(/\s/, 1, true)
rep_exotic = Repeater.new(/[^ -~]/, 1, true)
repeated_map = {
"repeated alnum" => rep_alnum,
"repeated punct" => rep_punct,
"repeated other" => rep_other,
"whitespace characters" => rep_space,
"exotic characters" => rep_exotic
}
max_len = [*repeated_map].map { |e| e[0].size } .max
str = STDIN.read
puts str
score = str.size
puts "length: #{score}"
repeated_map.each { |k, v|
vs, penalty = v[str]
score -= penalty
puts k + ": " + " " * (max_len - k.size) + "-#{penalty} (#{vs})"
}
puts "total score: #{score}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.