Skip to content

Instantly share code, notes, and snippets.

@evanthebouncy
Last active September 1, 2022 11:24
Show Gist options
  • Save evanthebouncy/25114aaf0be20df21468735aa7103bef to your computer and use it in GitHub Desktop.
Save evanthebouncy/25114aaf0be20df21468735aa7103bef to your computer and use it in GitHub Desktop.
rectangle programming task
import random
# some globals
W = 6
inside = True
outside = False
def interpret(program, inputt):
T, D, L, R = program
i, j = inputt
return i >= T and i <= D and j >= L and j <= R
def is_correct(program, spec):
for inputt, output in spec:
if interpret(program, inputt) != output:
return False
return True
# visualize a program and a spec
def visualize_spec(prog_str, spec):
# use matplotlib to draw a WxW grid, put the rectangle and spec points on it
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots()
ax.set_xlim(0, W)
ax.set_ylim(0, W)
# flip y axis
ax.set_ylim(ax.get_ylim()[::-1])
ax.set_aspect('equal')
ax.set_title("Program: " + prog_str)
# set a different title
T, D, L, R = eval(prog_str)
rect = patches.Rectangle((L, T), R-L+1, D-T+1, linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
for (coord, val) in spec:
if val:
ax.scatter(coord[1]+0.5, coord[0]+0.5, c='b')
else:
ax.scatter(coord[1]+0.5, coord[0]+0.5, c='r')
plt.show()
plt.clf()
if __name__ == '__main__':
# the rectangle in our figure
rectangle = [1,3,1,4]
# the mushrooms and grass in our figure
shroom1, shroom2 = (0,4), (4,1)
grass1, grass2 = (1,1), (3,3)
assert interpret(rectangle, grass1) == inside
assert interpret(rectangle, grass2) == inside
assert interpret(rectangle, shroom1) == outside
assert interpret(rectangle, shroom2) == outside
print ("working as intended !")
spec = [(shroom1, outside), (shroom2, outside), (grass1, inside), (grass2, inside)]
shroom_inside1, shroom_inside2 = interpret(rectangle, shroom1), interpret(rectangle, shroom2)
grass_inside1, grass_inside2 = interpret(rectangle, grass1), interpret(rectangle, grass2)
print (shroom_inside1, shroom_inside2, grass_inside1, grass_inside2)
shroom3 = (2,2)
grass3 = (4,3)
shroom4 = (5,4)
spec2 = [(shroom3, outside), (grass3, inside), (shroom4, outside)]
# let's try to make a rectangle that satisfy this new spec
rect2 = [1,3,1,4]
print (is_correct(rectangle, spec2)) # didn't work
rect3 = [3,4,1,3]
print (is_correct(rect3, spec2)) # worked okay
visualize_spec("[1,3,1,4]", spec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment