Skip to content

Instantly share code, notes, and snippets.

Last active Dec 19, 2020
What would you like to do?
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):
replace(&"(?:{rule})", re"\d+", proc(match: string): string =
buildRegex(match, rules))
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):
echo count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment