Skip to content

Instantly share code, notes, and snippets.

@fxn
Last active December 19, 2020 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxn/931c1f4f32f5f92c61e9006769703372 to your computer and use it in GitHub Desktop.
Save fxn/931c1f4f32f5f92c61e9006769703372 to your computer and use it in GitHub Desktop.
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