Last active
March 29, 2022 12:07
-
-
Save Irsanarisandy/0132de0020bfde7d4e7fad8bd22a3a88 to your computer and use it in GitHub Desktop.
This file contains 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
def translate_brainf___(brainf___, trim_string=False, user_input=""): | |
compiled = "" | |
memory = [0] | |
pointer = 0 | |
cur_index = 0 | |
loop_indexes = [] | |
input_index = 0 | |
while cur_index != len(brainf___): | |
if brainf___[cur_index] == '>': | |
pointer += 1 | |
if pointer == len(memory): | |
memory.append(0) | |
elif brainf___[cur_index] == '<': | |
pointer -= 1 | |
if pointer < 0: | |
memory.insert(0, 0) | |
pointer = 0 | |
elif brainf___[cur_index] == '+': | |
memory[pointer] += 1 | |
elif brainf___[cur_index] == '-': | |
memory[pointer] -= 1 | |
elif brainf___[cur_index] == '.': | |
compiled += chr(memory[pointer]) | |
elif brainf___[cur_index] == ',': | |
if user_input != "" and input_index < len(user_input): | |
memory[pointer] = ord(user_input[input_index]) | |
if memory[pointer] > 255: | |
raise ValueError(f"all input characters must not have code greater than 255") | |
input_index += 1 | |
elif brainf___[cur_index] == '[': | |
if memory[pointer] == 0: | |
temp_pair = 1 | |
temp_index = cur_index | |
while temp_pair != 0: | |
temp_left_ind = brainf___.find('[', temp_index+1) | |
temp_right_ind = brainf___.find(']', temp_index+1) | |
if temp_right_ind == -1: | |
raise ValueError(f"missing ending for start loop ('[') at position {cur_index}") | |
if temp_left_ind != -1 and temp_left_ind < temp_right_ind: | |
temp_index = temp_left_ind | |
temp_pair += 1 | |
else: | |
temp_index = temp_right_ind | |
temp_pair -= 1 | |
cur_index = temp_index | |
else: | |
loop_indexes.append(cur_index) | |
elif brainf___[cur_index] == ']': | |
if len(loop_indexes) == 0: | |
raise ValueError(f"extra end loop (']') at position {cur_index}") | |
if memory[pointer] == 0: | |
loop_indexes.pop() | |
else: | |
cur_index = loop_indexes[-1] | |
if memory[pointer] < 0 or memory[pointer] > 255: | |
memory[pointer] %= 256 | |
cur_index += 1 | |
if trim_string: | |
return compiled.strip() | |
return compiled |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment