Last active
December 19, 2020 19:23
-
-
Save fxn/931c1f4f32f5f92c61e9006769703372 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import strutils, tables, nre, strformat | |
proc parseRules(rules: seq[string]): Table[string, string] = | |
for rule in rules: | |
var parts = rule.split(":") | |
result[parts[0]] = parts[1].strip | |
proc buildRegex(idx: string, rules: Table[string, string]): string = | |
let rule = case idx: | |
of "8": "(?:42)+" | |
of "11": "(?<x>42 31 | 42 \\g<x> 31)" | |
else: rules[idx] | |
if (let rm = rule.match(re("\"([a-z])\"")); rm.isSome): | |
rm.get.captures[0] | |
else: | |
replace(&"(?:{rule})", re"\d+", proc(match: string): string = | |
buildRegex(match, rules)) | |
let | |
input = readAll(stdin).split("\n\n") | |
rules = parseRules(input[0].strip.splitLines) | |
messages = input[1].strip.splitLines | |
regex = re("(?x)" & buildRegex("0", rules) & "\\z") | |
var count = 0 | |
for message in messages: | |
if (let rm = message.match(regex); rm.isSome): | |
count.inc | |
echo count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment