Python 3,稍后会得分
from collections import defaultdict
from functools import lru_cache
import sys
NUMERIC_OUTPUT = True
@lru_cache(maxsize=1024)
def to_befunge_num(n):
# Convert number to Befunge number, using base 9 encoding (non-optimal,
# but something simple is good for now)
assert isinstance(n, int) and n >= 0
if n == 0:
return "0"
digits = []
while n:
digits.append(n%9)
n //= 9
output = [str(digits.pop())]
while digits:
output.append("9*")
d = digits.pop()
if d:
output.append(str(d))
output.append("+")
output = "".join(output)
if output.startswith("19*"):
return "9" + output[3:]
return output
def translate(program_str):
if program_str.count("(") != program_str.count(")"):
exit("Error: number of opening and closing parentheses do not match")
program = program_str.splitlines()
row_len = max(len(row) for row in program)
program = [row.ljust(row_len) for row in program]
num_stacks = len(program)
loop_offset = 3
stack_len_offset = program_str.count("(")*2 + loop_offset
stack_offset = stack_len_offset + 1
output = [[1, ["v"]], [1, [">"]]] # (len, [strings]) for each row
max_len = 1 # Maximum row length so far
HEADER_ROW = 0
MAIN_ROW = 1
FOOTER_ROW = 2
# Then stack lengths, then loop rows, then stacks
# Match closing parens with opening parens
loop_map = {} # {column: (loop num, stack number to check, is_start)}
loop_stack = []
loop_num = 0
for col in range(row_len):
col_str = "".join(program[stack][col] for stack in range(num_stacks))
if col_str.count("(") + col_str.count(")") >= 2:
exit("Error: more than one parenthesis in a column")
if "(" in col_str:
stack_num = col_str.index("(")
loop_map[col] = (loop_num, stack_num, True)
loop_stack.append((loop_num, stack_num, False))
loop_num += 1
elif ")" in col_str:
if loop_stack:
loop_map[col] = loop_stack.pop()
else:
exit("Error: mismatched parentheses")
def pad_max(row):
nonlocal max_len, output
while len(output) - 1 < row:
output.append([0, []])
if output[row][0] < max_len:
output[row][1].append(" "*(max_len - output[row][0]))
output[row][0] = max_len
def write(string, row):
nonlocal max_len, output
output[row][1].append(string)
output[row][0] += len(string)
max_len = max(output[row][0], max_len)
def stack_len(stack, put=False):
return (to_befunge_num(stack) + # x
str(stack_len_offset) + # y
"gp"[put])
def get(stack, offset=0):
assert offset in [0, 1] # 1 needed for 2-arity ops
# Check stack length
write(stack_len(stack) + "1-"*(offset == 1) + ":0`", MAIN_ROW)
pad_max(HEADER_ROW)
pad_max(MAIN_ROW)
pad_max(FOOTER_ROW)
write(">" + to_befunge_num(stack + stack_offset) + "g", HEADER_ROW)
write("|", MAIN_ROW)
write(">$0", FOOTER_ROW)
pad_max(HEADER_ROW)
pad_max(MAIN_ROW)
pad_max(FOOTER_ROW)
write("v", HEADER_ROW)
write(">", MAIN_ROW)
write("^", FOOTER_ROW)
def put(stack, value=""):
put_inst = (value +
stack_len(stack) +
to_befunge_num(stack + stack_offset) +
"p")
post_insts.append(put_inst)
def pop(stack):
put(stack, "0")
def inc_stack_len(stack):
post_insts.append(stack_len(stack) + "1+")
post_insts.append(stack_len(stack, put=True))
def dec_stack_len(stack):
post_insts.append(stack_len(stack) + ":0`-") # Ensure nonnegativity
post_insts.append(stack_len(stack, put=True))
# Technically not necessary to initialise stack lengths per spec, but it makes it
# more portable and easier to test against other Befunge interpreters
for stack in range(num_stacks):
write("0" + stack_len(stack, put=True), MAIN_ROW)
for col in range(row_len):
post_insts_all = []
loop_start = False
loop_end = False
if col in loop_map:
if loop_map[col][2]:
loop_start = True
else:
loop_end = True
if loop_start:
loop_row = loop_offset + 2*loop_map[col][0]
get(loop_map[col][1])
elif loop_end:
get(loop_map[col][1])
write("!", MAIN_ROW)
for stack in range(num_stacks-1, -1, -1):
char = program[stack][col]
post_insts = [] # Executed after the gets in reverse order, i.e. last added first
if char in " ()":
continue
# Pre-inc, post-dec
elif char.isdigit():
inc_stack_len(stack)
put(stack, char)
elif char == "?":
inc_stack_len(stack)
put(stack, "&")
elif char == "!":
get(stack)
post_insts.append(".91+," if NUMERIC_OUTPUT else ",")
pop(stack)
dec_stack_len(stack)
elif char == "#":
pop(stack)
dec_stack_len(stack)
elif char in "+-":
get(stack, 1)
get(stack)
post_insts.append(char)
pop(stack) # This one first in case of ! or 1!
post_insts.append(stack_len(stack) + ":1`-:1\\`+") # Ensure >= 1
post_insts.append(stack_len(stack, put=True))
put(stack)
elif char in "^v":
offset = -1 if char == "^" else 1
get((stack + offset) % num_stacks)
inc_stack_len(stack)
put(stack)
else:
exit("Error: invalid character " + char)
post_insts_all.append(post_insts)
while post_insts_all:
write("".join(post_insts_all.pop()), MAIN_ROW)
if loop_start or loop_end:
loop_row = loop_offset + 2*loop_map[col][0]
pad_max(HEADER_ROW)
pad_max(MAIN_ROW)
pad_max(loop_row)
pad_max(loop_row + 1)
write(">v", HEADER_ROW)
write("|>", MAIN_ROW)
if loop_start:
write(" ^", loop_row)
write(">", loop_row + 1)
else:
write("<", loop_row)
write(" ^", loop_row + 1)
write("@", MAIN_ROW)
return "\n".join("".join(row) for row_len, row in output)
if __name__ == '__main__':
if len(sys.argv) < 3:
exit("Usage: py -3 prefunge.py <input filename> <output filename>")
with open(sys.argv[1]) as infile:
with open(sys.argv[2], "w") as outfile:
outfile.write(translate(infile.read()))
运行像py -3 prefunge.py <input filename> <output filename>
。
对我来说这是很慢的一周,所以我终于无聊了,无法解决这个六个月大的问题。我会问为什么没有其他人尝试过,但是我仍然感觉到调试带来的痛苦(据我所知,可能仍然存在bug)。
这个问题没有提供Befunge-93解释器,因此我使用了这个,与规范稍有不同。两个主要区别是:
输出程序的核心布局是这样的:
v [header row]
> [main row]
[footer row]
---
|
| rows for loops (2 per loop)
|
---
[stack length row]
---
|
| rows for stack space (1 per voice)
|
---
堆栈空间在程序外部,因此换行符是前面的Enter-spamming注释。
核心思想是为每个语音分配一行作为其堆栈。为了维护这些堆栈,我们还有一个特殊的堆栈长度行,其中每个堆栈的长度沿该行记录在一个单元格中。该程序然后是很多g
ets和p
uts,例如,用于打印的过程是:
- 在获取单元格
y = stack_row[stack], x = stack_length[stack]
- 执行
.91+,
,即打印为整数,然后打印换行符
- 将上面坐标处的单元格替换为0(以模拟弹出)
- 减量
stack_length[stack]
为了执行列的同时评估,在写入任何单元之前(例如,对于打印示例,在第一步和第二步之间可能会有更多指令),读取所有必需的单元并将它们的值保留在堆栈上。
`
大于,用于确保堆栈长度永远不会为负,并在堆栈为空时将其推为0。这是清晰可见的分支的来源,但是我有一个想法,将删除该分支,这应该从第一行和第三行中删除大量空白。
对于循环,由于Prelude循环可以双向跳转,因此在这样的配置中,每个循环使用两行:
>v >v
(cond) |> (program) (cond) !|>
^ <
> ^
目前,这些循环占了字节的大部分,但是可以通过将它们放入带有的代码箱中来轻松地找到它们p
,我对转换器能够正常工作感到满意之后,我打算这样做。
这是的一些示例输出?(1-^!)
,即打印n-1
到0
:
v >6gv>v >6gv >6gv >6gv >6gv >6gv >v
>005p05g1+05p&05g6p05g:0`| >|>05g1+05p105g6p05g1-:0`| >05g:0`| >-005g6p05g:1`-:1\`+05p05g6p05g:0`| >05g1+05p05g6p05g:0`| >.91+,005g6p05g:0`-05p05g:0`| >!|>@
>$0^ >$0^ >$0^ >$0^ >$0^ >$0^
^ <
> ^
输入平方:
v >8gv >8gv >v >6gv >8gv >8gv >7gv >7gv >8gv >v >7gv
>005p015p025p25g1+25p&25g8p25g:0`| >25g:0`| >05g1+05p05g6p|>05g:0`| >15g1+15p15g7p25g1+25p125g8p25g1-:0`| >25g:0`| >15g1-:0`| >15g:0`| >+015g7p15g:1`-:1\`+15p15g7p-025g8p25g:1`-:1\`+25p25g8p25g:0`| >!|>15g:0`| >.91+,015g7p15g:0`-15p@
>$0^ >$0^ >$0^ >$0^ >$0^ >$0^ >$0^ >$0^ >$0^
^ <
> ^
除法(建议少量输入):
v >91+gv>v >94+gv >95+gv >95+gv >93+gv >93+gv >93+gv >93+gv >v >93+gv >93+gv >v >92+gv >v >92+gv >92+gv >91+gv >93+gv >91+gv >92+gv >92+gv >91+gv >91+gv >92+gv >v >91+gv >91+gv >91+gv >v >95+gv >95+gv >95+gv
>009p019p029p039p049p09g1+09p109g91+p29g1+29p&29g93+p39g1+39p&39g94+p09g:0`| >|>39g:0`| >009g91+p09g:0`-09p29g1+29p29g93+p49g1+49p149g95+p49g1-:0`| >49g:0`| >29g1-:0`| >29g:0`| >-029g93+p29g:1`-:1\`+29p29g93+p+049g95+p49g:1`-:1\`+49p49g95+p29g:0`| >29g:0`| >19g1+19p19g92+p|>29g:0`| >09g1+09p109g91+p19g1+19p19g92+p29g1+29p029g93+p29g:0`| >!|>19g:0`| >029g93+p29g:0`-29p|>19g:0`| >09g1+09p09g91+p019g92+p19g:0`-19p19g:0`| >019g92+p19g:0`-19p29g1+29p29g93+p09g:0`| >009g91+p09g:0`-09p19g1+19p19g92+p29g:0`| >19g1+19p19g92+p09g:0`| >19g1+19p19g92+p19g1-:0`| >19g:0`| >09g1-:0`| >09g:0`| >-009g91+p09g:1`-:1\`+09p09g91+p+019g92+p19g:1`-:1\`+19p19g92+p029g93+p29g:0`-29p19g:0`| >!|>09g1+09p109g91+p09g1-:0`| >09g:0`| >+009g91+p09g:1`-:1\`+09p09g91+p09g:0`| >!|>49g1+49p149g95+p49g1-:0`| >49g:0`| >-049g95+p49g:1`-:1\`+49p49g95+p49g:0`| >.91+,049g95+p49g:0`-49p@
>$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^ >$0 ^
^ <
> ^
^ <
> ^
^ <
> ^
还有一堆浮现在脑海中,像更换其他次要的优化的07p07g
有:07p
,但我考虑在这个时间一步:)