Skip to content

Instantly share code, notes, and snippets.

@theonlypwner
Created November 3, 2015 18:06
Show Gist options
  • Save theonlypwner/060f9c601d3555aae1da to your computer and use it in GitHub Desktop.
Save theonlypwner/060f9c601d3555aae1da to your computer and use it in GitHub Desktop.
Inefficient Resistor Combination Minimizer
# Inefficient resistor solver
# it's also incomplete
# Licensed under GPL 3
# settings
target = 9960
tolerance = target * 0.005
depth = 3
available_resistors = [
100, 120, 220, 330,
390, 470, 680, 820,
1000, 1200, 2200, 4700,
8200, 10000, 51000, 100000
]
# program
solutions = []
def solve(target, remain, path=None):
# check if it works
if abs(target) < tolerance:
solutions.append([target, remain, path])
return
# too many resistors?
if remain <= 0:
return
# add a resistor
for r in available_resistors:
# series
solve(target - r, remain - 1, [path, r])
# parallel
if r != target:
solve(1. / (1. / target - 1. / r), remain - 1, (path, r))
def format_path(path, last=0):
if path[0] == None:
return path[1]
elif type(path[0]) is list:
return ('%s+%s' if last != 2 else '%s+(%s') % (format_path(path[0], 1), path[1])
elif type(path[0]) is tuple:
return ('%s|%s' if last != 1 else '%s|(%s') % (format_path(path[0], 2), path[1])
# shouldn't happen
return str(path)
# solve!
solve(target, depth)
# sort solutions
def solution_sort(x, y):
# error (minimize)
if abs(x[0]) < abs(y[0]): return -1
if abs(x[0]) > abs(y[0]): return 1
# remain (maximize)
if x[1] > y[1]: return -1
if x[1] < y[1]: return 1
return 0
# reverse order, so best is last in case of overflow
solutions.sort(cmp=lambda x, y: -solution_sort(x,y))
# print solution table
print('target: %s (depth %d)' % (target, depth))
print('')
print('error, solution')
for solution in solutions:
print('%11.4e: %s' % (solution[0], format_path(solution[2])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment