Created
June 2, 2011 10:02
-
-
Save benfoxall/1004198 to your computer and use it in GitHub Desktop.
21 (Card Game) solution
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
// a couple of FPish array enhancements | |
// gives a new array with value pushed on it | |
Array.prototype.$push = function(v){ | |
var a = this.slice(); | |
a.push(v); | |
return a; | |
} | |
// gives the array without selected indexes | |
Array.prototype.$remove = function(inds){ | |
var a = []; | |
for(var i = 0; i < this.length; i++){ | |
var keep = true; | |
for(var k in inds){ | |
if(inds[k] == i){ | |
keep = false; | |
break; | |
} | |
} | |
keep && a.push(this[i]); | |
} | |
return a; | |
} | |
var operators = '+ - / *'.split(' '); | |
// All the ways that the cards can be combined | |
solutions = function(cards, cb){ | |
if(cards.length == 1){ | |
cb(cards[0]); | |
} | |
for(var i = 0; i < cards.length; i++){ | |
for(var j = i + 1; j < cards.length; j++){ | |
var rest = cards.$remove([i,j]); | |
for(var o = 0; o < operators.length; o++){ | |
var applied = ['(', cards[i], operators[o], cards[j], ')'].join(' '); | |
solutions(rest.$push(applied), cb); | |
} | |
} | |
} | |
} | |
var select_ids = ['a','b','c','d']; | |
var check = function(){ | |
var cards = []; | |
for (var i=0; i < select_ids.length; i++) { | |
cards[i] = parseInt(document.getElementById(select_ids[i]).value,0); | |
} | |
document.getElementById('results').innerHTML = ''; | |
solutions(cards, function(solution){ | |
//check if the solution reaches 21 | |
if(eval(solution) === 21) { | |
document.getElementById('results').innerHTML += ('<li>' + solution + '</li>'); | |
} | |
}); | |
if(!document.getElementById('results').innerHTML.length){ | |
document.getElementById('results').innerHTML = '<li>No solutions found</li>'; | |
} | |
} | |
for (var i=0; i < select_ids.length; i++) { | |
document.getElementById(select_ids[i]).onchange = check; | |
}; | |
check(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment