Skip to content

Instantly share code, notes, and snippets.

@igorvanloo
Created May 2, 2023 13:53
Show Gist options
  • Save igorvanloo/89d8976989d91ebc99e06820b9ca40a4 to your computer and use it in GitHub Desktop.
Save igorvanloo/89d8976989d91ebc99e06820b9ca40a4 to your computer and use it in GitHub Desktop.
Test if a number is constructable from a set of numbers through arithmetic operations
class P:
def __init__(self, value, mask, left, right, operation):
self.value = value
self.mask = mask
self.left = left
self.right = right
self.operation = operation
if self.left == None and self.right == None:
self.expression = str(value)
else:
self.expression = "(" + self.left.expression + self.operation + self.right.expression + ")"
def generateExpressions(g, A):
values = [(x, "0"*i + "1") for i, x in enumerate(A)]
E = [P(x, "1" + "0"*i, None, None, None) for i, x in enumerate(A)]
Q = [P(x, "1" + "0"*i, None, None, None) for i, x in enumerate(A)]
goal = []
while Q != []:
a = Q.pop(0)
if a.value == g:
print(a.expression)
goal.append(a)
for b in E:
if bin(int(a.mask, 2) & int(b.mask, 2))[2:] == "0": #We have not used a number twice
newmask = bin(int(a.mask, 2) | int(b.mask, 2))[2:]
#Addition
c = P(a.value + b.value, newmask, a, b, "+")
if (c.value, c.mask) not in values:
values.append((c.value, c.mask))
Q.append(c)
E.append(c)
#Subtraction
if a.value - b.value > 0:
c = P(a.value - b.value, newmask, a, b, "-")
if (c.value, c.mask) not in values:
values.append((c.value, c.mask))
Q.append(c)
E.append(c)
#Multiplication
c = P(a.value * b.value, newmask, a, b, "*")
if (c.value, c.mask) not in values:
values.append((c.value, c.mask))
Q.append(c)
E.append(c)
#Division
if a.value % b.value == 0:
c = P(a.value // b.value, newmask, a, b, "/")
if (c.value, c.mask) not in values:
values.append((c.value, c.mask))
Q.append(c)
E.append(c)
if goal == []:
return 0
v = []
for x in goal:
total = 0
for i, y in enumerate(x.mask[::-1]):
if y == "1":
total += A[i]
v.append(total)
return min(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment