Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active April 15, 2024 19:27
Show Gist options
  • Save CodeByAidan/758c9a0f34a2cd9c27f4fad153910823 to your computer and use it in GitHub Desktop.
Save CodeByAidan/758c9a0f34a2cd9c27f4fad153910823 to your computer and use it in GitHub Desktop.
String to BrainF**k in 2 different versions! Python execution recorded with https://rextester.com/, BrainF**k execution/steps recorded with https://minond.xyz/brainfuck/
def StrToBrf(v: str) -> str:
result = []
current = 0
for ch in v:
target = ord(ch)
diff = target - current
if diff > 0:
result.append('+' * diff)
elif diff < 0:
result.append('-' * abs(diff))
result.append('.')
current = target
return ''.join(result)
print(StrToBrf('String to Brainfuck')) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++.--.---------.+++++.-------.-----------------------------------------------------------------------.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----.-------------------------------------------------------------------------------.++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++.-----------------.++++++++.+++++.--------.+++++++++++++++.------------------.++++++++.
"""
RESULTS:
~~~~~~~~~~~
PYTHON EXECUTION:
-----------------
- Absolute running time: 0.16 sec
- cpu time: 0.03 sec
- memory peak: 8 Mb
- absolute service time: 0.25 sec
BF OUTPUT/EXECUTION:
--------------------
- 559 bytes
- 557 steps
"""
def cdc(i: int) -> int:
t = i % 10
if t > 5:
i += 10
return i - t
def StrToBrf(v: str) -> str:
s = ['+' * 10 + '[']
t = []
for ch in v:
i_ord: int = ord(ch)
i_cdc: int = cdc(ord(ch))
i_max: int = 256 - i_ord
s.append('>' + ('-' * i_max if i_max < 128 else '+' * (i_cdc // 10)))
t.append('>' + ('+' if i_ord - i_cdc > 0 else '-') * abs(i_ord - i_cdc))
s.append('<' * len(v) + '-]' + ''.join(t) + (len(v) - 1) * '<' + '[.>]')
return ''.join(s)
print(StrToBrf('String to Brainfuck')) # ++++++++++[>++++++++>++++++++++++>+++++++++++>++++++++++>+++++++++++>++++++++++>+++>++++++++++++>+++++++++++>+++>+++++++>+++++++++++>++++++++++>++++++++++>+++++++++++>++++++++++>++++++++++++>++++++++++>+++++++++++<<<<<<<<<<<<<<<<<<<-]>+++>---->++++>+++++>>+++>++>---->+>++>---->++++>--->+++++>>++>--->->---<<<<<<<<<<<<<<<<<<[.>]
"""
RESULTS:
~~~~~~~~~~~
PYTHON EXECUTION:
-----------------
- Absolute running time: 0.16 sec
- cpu time: 0.03 sec
- memory peak: 8 Mb
- absolute service time: 0.29 sec
BF OUTPUT/EXECUTION:
--------------------
- 329 bytes
- 2388 steps
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment