Created
February 9, 2012 19:16
-
-
Save matomesc/1782186 to your computer and use it in GitHub Desktop.
Vending machine DFA transitions
This file contains hidden or 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
// usage: node vending.js > transitions | |
var coins = [5, 10, 25, 100]; | |
var _sum = 125; | |
var validTransitions = []; | |
coins.forEach(function (c) { check(0, c); }) | |
function check(sum, coin, transitions) { | |
transitions = transitions || []; | |
var newSum = sum + coin; | |
var symbol; | |
switch (coin) { | |
case 5: symbol = 'nickel'; break; | |
case 10: symbol = 'dime'; break; | |
case 25: symbol = 'quarter'; break; | |
case 100: symbol = 'loonie'; break; | |
} | |
if (newSum < _sum) { | |
transitions.push(sum + ' ' + symbol + ' ' + newSum); | |
coins.forEach(function (coin) { | |
check(newSum, coin, copy(transitions)) | |
}); | |
} else if (newSum === _sum) { | |
transitions.push(sum + ' ' + symbol + ' ' + newSum); | |
validTransitions.push(transitions); | |
} | |
} | |
console.error(validTransitions.length); | |
var uniqueTransitions = {}; | |
validTransitions.forEach(function (transitions) { | |
transitions.forEach(function (t) { | |
if (!uniqueTransitions[t]) { | |
uniqueTransitions[t] = 1; | |
} | |
}); | |
}); | |
// output valid states | |
var i = 0; | |
console.log(26); | |
while (i != 130) { console.log(i); i += 5;} | |
// output all transitions | |
console.log(Object.keys(uniqueTransitions).length); | |
Object.keys(uniqueTransitions).forEach(function (t) { | |
console.log(t); | |
}); | |
function copy(array) { | |
var c = [], len = array.length, i = 0; | |
while (i < len) { | |
c.push(array[i]); | |
i += 1; | |
} | |
return c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment