Created
June 16, 2014 10:52
-
-
Save jamesramsay/157a91e13cf9a40b5943 to your computer and use it in GitHub Desktop.
Cassowary.js example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PROBLEM: Small brewery produces ale and beer | |
# Production is limited by scarce resources: corn, hops, barley malt. | |
# Recipes for ale and beer require differenty proportions of resources | |
# | |
# Ale (barrel) | |
# - 5lb corn | |
# - 4oz hops | |
# - 35lb malt | |
# - $13 profit | |
# | |
# Beer (barrel) | |
# - 15lb corn | |
# - 4oz hops | |
# - 20lb malt | |
# - $23 profit | |
# | |
# Limited resources | |
# - 480lb corn | |
# - 160oz hops | |
# - 1190lb malt | |
# | |
# What is the optimum quantity to brew? | |
c = require 'cassowary' | |
_ = require 'underscore' | |
problem = | |
resources: | |
corn: 480 | |
hops: 160 | |
malt: 1190 | |
products: | |
ale: | |
corn: 5 | |
hops: 4 | |
malt: 35 | |
profit: 13 | |
beer: | |
corn: 15 | |
hops: 4 | |
malt: 20 | |
profit: 23 | |
solver = new c.SimplexSolver() | |
resources = {} | |
products = {} | |
for p in _.keys problem.products | |
products[p] = new c.Variable {name: p} | |
solver.addConstraint(new c.Inequality products[p], c.GEQ, 0) | |
# Objective: Profit | |
profit = new c.ObjectiveVariable {name: 'profit'} | |
productProfit = _.map _(products).keys(), (p) -> | |
new c.Expression products[p], -1 * problem.products[p].profit | |
solver.addConstraint(new c.Equation profit, | |
_.reduce productProfit, ((ex, e) -> ex.plus e), new c.Expression) | |
for resource in _.keys problem.resources | |
r = resources[resource] = new c.Variable {name: resource} | |
resourceLimits = _.map _(products).keys(), (p) -> | |
new c.Expression products[p], problem.products[p][resource] | |
solver.addConstraint(new c.Equation r, | |
_.reduce resourceLimits, ((ex, e) -> ex.plus e), new c.Expression) | |
solver.addConstraint(new c.Inequality r, c.LEQ, problem.resources[resource]) | |
.addConstraint(new c.Inequality r, c.GEQ, 0) | |
# Solve | |
solver.optimize(profit) | |
solver.resolve() | |
console.log "Profit: $#{13 * products.ale.value.toFixed(0) + | |
23 * products.beer.value.toFixed(0)}" | |
console.log "Ale: #{products.ale.value.toFixed(0)} barrels" | |
console.log "Beer: #{products.beer.value.toFixed(0)} barrels" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment