Created
March 25, 2019 16:21
-
-
Save malkoG/c48caff7085c4a6de89f8ce04a8d8249 to your computer and use it in GitHub Desktop.
noj.am/2733
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
n=int(input()) | |
for i in range(n): | |
pointer = 0 | |
byte_array = [0] * 32768 | |
left_stack = [-1] * 128000 | |
right_stack = [-1] * 128000 | |
validation_stack = [] | |
command = "" | |
command_length = 0 | |
while True: | |
try: | |
line = input() | |
except: | |
break | |
if line == "end": | |
break | |
for ch in line: | |
if ch not in "<>+-.[]%": | |
continue | |
if ch == "%": | |
break | |
command_length += 1 | |
command += ch | |
left_brackets_count = command.count('[') | |
left_stack = [-1] * left_brackets_count | |
right_stack = [-1] * left_brackets_count | |
validation_stack = [] | |
frequency = 0 | |
scanning_index = 0 | |
positions_hashmap = {} | |
valid = True | |
for ch in command: | |
if ch == "[": | |
validation_stack.append((scanning_index, frequency,)) | |
frequency += 1 | |
elif ch == "]": | |
if len(validation_stack) == 0: | |
valid = False | |
break | |
left, stack_index = validation_stack.pop() | |
right = scanning_index | |
positions_hashmap[str(left)] = stack_index | |
positions_hashmap[str(right)] = stack_index | |
left_stack[stack_index] = right | |
right_stack[stack_index] = left | |
scanning_index += 1 | |
print("PROGRAM #{}:".format(i + 1)) | |
if not valid or len(validation_stack) > 0: | |
print("COMPILE ERROR") | |
continue | |
scanning_index = 0 | |
command_size = len(command) | |
result = "" | |
while scanning_index < command_size: | |
ch = command[scanning_index] | |
if ch == ">": | |
pointer += 1 | |
pointer %= 32768 | |
elif ch == "<": | |
pointer += 32767 | |
pointer %= 32768 | |
elif ch == "+": | |
byte_array[pointer] += 1 | |
byte_array[pointer] %= 256 | |
elif ch == "-": | |
byte_array[pointer] += 255 | |
byte_array[pointer] %= 256 | |
elif ch == ".": | |
result += chr(byte_array[pointer]) | |
elif ch == "[": | |
stack_index = positions_hashmap[str(scanning_index)] | |
if byte_array[pointer] == 0: | |
scanning_index=left_stack[stack_index] | |
elif ch == "]": | |
stack_index = positions_hashmap[str(scanning_index)] | |
if byte_array[pointer] != 0: | |
scanning_index=right_stack[stack_index] | |
scanning_index += 1 | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment