Created
November 22, 2016 01:50
-
-
Save primaryobjects/9b063eab1db6c403c87dd61c5a24d00d to your computer and use it in GitHub Desktop.
[2016-11-21] Challenge #293 [Easy] Defusing the bomb
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
# | |
# [2016-11-21] Challenge #293 [Easy] Defusing the bomb | |
# To disarm the bomb you have to cut some wires. These wires are either white, black, purple, red, green or orange. | |
# https://www.reddit.com/r/dailyprogrammer/comments/5e4mde/20161121_challenge_293_easy_defusing_the_bomb/ | |
# Demo at http://jsbin.com/fufohasawi/edit?js,console | |
# | |
# by Kory Becker | |
# http://primaryobjects.com | |
# | |
function bitTest(num, bit){ | |
return ((num>>bit) % 2 != 0) | |
} | |
function bitSet(num, bit){ | |
return num | 1<<bit; | |
} | |
function isDisarmed(input, rules) { | |
var result = { disarm: true }; | |
for (var i=0; i<input.length; i++) { | |
var wire = input[i]; | |
var rule = rules[wire]; | |
var isPos = rule.p > 0; | |
var ruleVal = rule.p || rule.n; | |
if (ruleVal) { | |
if (i + 1 < input.length) { | |
var nextWire = input[i + 1]; | |
var wireCut = bitTest(ruleVal, nextWire); | |
if ((isPos && !wireCut) || (!isPos && wireCut)) { | |
result = { disarm: false, wire: names[wire], next: names[nextWire] }; | |
break; | |
} | |
} | |
else if (isPos) { | |
result = { disarm: false, wire: wire }; | |
break; | |
} | |
} | |
} | |
return result; | |
} | |
// | |
// Bit array order: white, black, purple, red, green, orange. | |
// 5 4 3 2 1 0 | |
var names = ['orange', 'green', 'red', 'purple', 'black', 'white']; | |
var rules = [ | |
{ p: 20, n: 0 }, | |
{ p: 33, n: 0 }, | |
{ p: 2, n: 0 }, | |
{ p: 0, n: 43 }, | |
{ p: 0, n: 35 }, | |
{ p: 0, n: 48 } | |
] | |
var input1 = [5, 2, 1, 5]; | |
var input2 = [5, 0, 1, 5]; | |
function driver(input) { | |
var result = isDisarmed(input, rules); | |
if (result.disarm) { | |
console.log('Bomb defused'); | |
} | |
else { | |
console.log('Boom'); | |
console.log(result); | |
} | |
} | |
driver(input1); | |
driver(input2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment