Skip to content

Instantly share code, notes, and snippets.

@duckythescientist
Last active October 7, 2015 20:30
Show Gist options
  • Save duckythescientist/11c0c27438493c3f8a75 to your computer and use it in GitHub Desktop.
Save duckythescientist/11c0c27438493c3f8a75 to your computer and use it in GitHub Desktop.
Generate the /r/shittyprogramming min number script
#!/usr/bin/env python2
import string
'''mingenerator.py
A really quick and dirty answer to :
https://www.reddit.com/r/shittyprogramming/comments/3npktf/finding_the_smallest_number_out_of_4_numbers_with/
Author: duckythescientist
'''
maxdepth = 1337 # Careful, takes over 5 minutes and produces a 2.5GB output file
# maxdepth = 4 # a sane number for testing
# This varname part is a horrid mess because of kluged "memoization"
# among other things....
varname_vars = None
def varname(n):
global varname_vars
return varname_vars[n]
def make_varname(n):
'''Return a unique variable name for each n
For some reason, I could only figure out how to write this recursively
'''
if n < 26:
return string.ascii_lowercase[n]
else:
return make_varname((n // 26) - 1) + string.ascii_lowercase[n%26]
varname_vars = [make_varname(i) for i in range(maxdepth+60)]
restricted = "auto else long switch break enum register typedef case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double".split()
for word in restricted:
try:
varname_vars.remove(word)
except ValueError:
pass
'''
print varname(0)
print varname(1)
print varname(51)
print varname(52)
print varname(2*52-1)
print varname(2*52)
print varname(2*52+1)
print varname(53*52-1)
print varname(53*52)
print varname(53*52+1)
'''
# hardcode the start
min2 = '''
int min2(int a, int b) {
if (a < b) {
return a;
}
else {
return b;
}
}
'''
# print len(varname_vars)
# hardcoded output file
with open("badmin.c", "w") as f:
f.write(min2)
for depth in range(3, maxdepth+1):
print "working... ", depth
f.write("int min%d(int "%(depth))
f.write(", int ".join(varname(n) for n in range(depth)) + ") {\n\n")
for n in range(depth):
if n == 0:
f.write("\tif (")
elif n == depth-1:
f.write("\telse if(") # Todo: fix the problem of no returns if all vars are equal
else:
f.write("\telse if(")
f.write(varname(n) + " < min%d("%(depth-1))
f.write(",".join(varname(i) for i in range(depth) if i != n))
f.write(")) {\n\n")
f.write("\t\treturn " + varname(n) + ";\n\n")
f.write("\t}\n\n")
f.write("}\n\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment