Numberwang/Implementations

From Esolang
Jump to navigation Jump to search

Implementations for Numberwang

Python

def droot(n):
	if n == 0:
		return 0
	elif n < 0:
		return droot(0-n)
	else:
		return 1+((n-1)%9)
def get_prog():
	c = input("Insert program\n")
	ds = []
	de = []
	sa = ""
	ea = 0
	dec = False
	for i in range(len(c)):
		if c[i] == "!":
			ds.append(int(sa))
			de.append(ea)
			sa = ""
			ea = 0
		elif c[i].isdigit():
			sa += c[i]
			if dec:
				ea -= 1
		elif c[i]==".":
			dec = True
		elif not(c[i].isspace()):
			return("invalid")
	return [ds, de]
def get_tape():
	c = input("Insert tape\n")
	d = []
	for i in range(len(c)):
		if c[i] == "0":
			d.append(0)
		elif c[i] == "1":
			d.append(1)
		elif not(c[i].isspace()):
			return("invalid")
	return d
def interpolate(progs,proge,indexs,indexe):
	pw = 10**-indexe
	sm = indexs % pw
	k = indexs // pw
	s1 = (pw - sm)*progs[k]
	s2 = sm*progs[k+1]
	e1 = indexe + proge[k]
	e2 = indexe + proge[k+1]
	e = min(e1, e2)
	s = s1*10**(e1-e) + s2*10**(e2-e)
	return [s, e]
def execute(progs,proge,step=-1,tape=[0],pointer=0):
	indexs = 0
	indexe = 0
	while indexs < len(progs)*10**-indexe:
		step += 1
		if indexe == 0:
			c = droot(droot(indexs) + droot(progs[indexs]) + droot(step))
			#droot(a+b+c) = droot(droot(a)+droot(b)+droot(c)), and droot(s*10**e) = droot(s)
		else:
			c = droot(droot(indexs) + droot(interpolate(progs,proge,indexs,indexe)[0]) + droot(step))
		c %= 4
		rnd = True
		if c == 0:
			pointer -= 1
			if pointer == -1:
				pointer = 0
				tape.insert(0,0)
		elif c == 1:
			pointer += 1
			if pointer == len(tape):
				tape.append(0)
		elif c == 2:
			if tape[pointer]:
				if indexe == 0:
					indexe = proge[indexs]
					indexs = progs[indexs]
				else:
					tmp = interpolate(progs,proge,indexs,indexe)
					indexs = tmp[0]
					indexe = tmp[1]
				L = len(progs)
				pw = 10**-indexe
				indexs = indexs//pw % L * pw + indexs % pw #this only holds true if indexe <= 0
				rnd = False
		else:
			tape[pointer] ^= 1
			print("iiiiiit's NUMBERWANG!")
			try:
				q = execute((12,44,92,10,498,2,2,2),(0,-1,0,0,-1,0,0,0),step,tape,pointer)
			except RecursionError:
				print("Infinite recursion!\nLast tape was:\n" + str(tape))
				exit()
			step = q[0]
			tape = q[1]
			pointer = q[2]
		if rnd:
			if indexe != 0:
				indexs //= 10**-indexe
				indexs += 1
				indexe = 0
			indexs += 1
		rnd = True
	return [step,tape,pointer]
prog = get_prog()
while prog == "invalid":
	print("Invalid program!\n")
	prog = get_prog()
progs = prog[0]
proge = prog[1]
tape = get_tape()
while tape == "invalid":
	print("Invalid tape!\n")
	tape = get_tape()
print(execute(progs,proge,-1,tape)[1])