repl.it
@21natzil/

BF-optimizer

Python

Optimize BF code

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import re

plus_match = re.compile(r"(\++)"), '+'
minus_match = re.compile(r"(-+)"), '-'
lshift_match = re.compile(r"(<+)"), '<'
rshift_match = re.compile(r"(>+)"), '>'

def find_multiple(num: int):
  return sorted([
    (i, num // i) for i in range(2, num) if not num % i
  ], key=lambda x: sum(x))


def optimize_multiples(code: str):
  for regex, token in (plus_match, minus_match, lshift_match, rshift_match):
    for match in regex.finditer(code):
      length = len(match[0])
      multiple = find_multiple(
        length
      )
      if multiple and sum(multiple[0]) + 6 < length:
        code = code[:match.start(0)] + "{}[>{}<-]>".format(token * multiple[0][0], token * multiple[0][1]) + code[match.end(0):]
  return code