Skip to content

Instantly share code, notes, and snippets.

@csferng

csferng/24.py Secret

Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csferng/cfc18104d9adfa25224f to your computer and use it in GitHub Desktop.
Save csferng/cfc18104d9adfa25224f to your computer and use it in GitHub Desktop.
import itertools
import subprocess
import sys
def readLine(f):
s = f.readline()
sys.stderr.write("Get: "+s)
return s
def writeLine(f, s):
print >> f, s
print >> sys.stderr, "Send:", s
def readQ(f):
s = readLine(f)
while not f.closed and not s.startswith('Question'):
s = readLine(f)
q = eval(s[s.index('['):].strip())
return q
OP = ['+', '-', '*', '/', '**', '//']
SIGN = [1, -1]
BASE_SEQ = ["(((%f%s%f)%s%f)%s%f)", "((%f%s(%f%s%f))%s%f)", "(%f%s((%f%s%f)%s%f))", "(%f%s(%f%s(%f%s%f)))", "((%f%s%f)%s(%f%s%f))"]
SEQ = []
def init():
for negs in itertools.product(SIGN, repeat=7):
for ops in itertools.product(OP, repeat=3):
for seq in BASE_SEQ:
otmp = ops[:]
ntmp = negs[:]
ss = []
i = 0
while i < len(seq):
if seq[i] == '(':
if ntmp[0] == -1: ss.append('-')
ntmp = ntmp[1:]
ss.append('(')
i += 1
elif seq[i:i+2] == '%f':
if ntmp[0] == -1: ss.append('-')
ntmp = ntmp[1:]
ss.append('%f')
i += 2
elif seq[i:i+2] == '%s':
ss.append(otmp[0])
otmp = otmp[1:]
i += 2
else:
ss.append(seq[i])
i += 1
SEQ.append(''.join(ss))
def solve(nums):
# print >> sys.stderr, "\tSearching", nums
a0, a1, a2, a3 = nums
for seq in SEQ:
r = seq % (a0, a1, a2, a3)
try:
v = eval(r)
except:
continue
if v == 24:
print >> sys.stderr, 'Hit', r
return seq.replace('f','d') % (a0, a1, a2, a3)
if v == -24:
print >> sys.stderr, 'Hit', '-'+r
return '-'+seq.replace('f','d') % (a0, a1, a2, a3)
return None
def doQA(outfile, infile):
nums = sorted(map(float,readQ(infile)))
last = []
ok = False
for prm in itertools.permutations(nums):
if prm == last:
continue
last = prm
ans = solve(prm)
# print >> sys.stderr, "\tFound:", ans
if ans is not None:
writeLine(outfile, ans)
ok = True
break
if not ok:
print >> sys.stderr, "No solution found. Please input: "
writeLine(outfile, "24"*10)
def main():
init()
print >> sys.stderr, len(SEQ)
# doQA(sys.stdout, sys.stdin)
# doQA(sys.stdout, sys.stdin)
# doQA(sys.stdout, sys.stdin)
# sys.exit()
p = subprocess.Popen(['nc', '210.65.89.59', '2424'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
rnd = 0
while rnd < 24:
rnd += 1
doQA(p.stdin, p.stdout)
# print readQ(p.stdout)
# writeLine(p.stdin, raw_input().strip())
readLine(p.stdout)
readLine(p.stdout)
readLine(p.stdout)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment