Created
March 17, 2014 21:44
-
-
Save JesterMan/9609032 to your computer and use it in GitHub Desktop.
braces
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
<head></head> | |
<body> | |
<script> | |
var expressions = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]", '][' ]; | |
function expTest(){ | |
var brackTest = function(x, z){ | |
for (var k = 1 +z; k < testInput.length; k++) { | |
if (testInput[k] == x){ | |
k--; | |
testInput.splice(z,1); | |
testInput.splice(k,1); | |
k--; | |
formatScore--; | |
j=-1; | |
return | |
} | |
else if (testInput[k] =='{'){ | |
k-- | |
brackTest('}', k+1); | |
} | |
else if (testInput[k]=='['){ | |
k-- | |
brackTest(']', k+1); | |
} | |
else if (testInput[k]=='('){ | |
k-- | |
brackTest(')', k+1); | |
} | |
else { | |
testInput.splice(k,1); | |
return | |
} | |
}; | |
}; | |
for (var i =0; i < expressions.length; i++) { | |
var formatScore = expressions[i].length/2; | |
var testInput = expressions[i].split(''); | |
// formatScore will be used to test if the braces are correctly formatted, in the case of a poorly formatted array - i.e. ([)]) - formatScore will be needed | |
if (testInput.length%2 == 1){ | |
console.log('0'+'\n'); | |
// test the length, if it's not even it can't be properly formatted | |
} else { | |
// run a test that identifies the opening brace, and runs brackTest on the remaining characters to identify the correctly closing bracket. If no opening brace is found, the array is poorly formatted | |
for (var j=0; j < testInput.length; j++){ | |
if (testInput[j] =='{'){ | |
brackTest('}', j); | |
}else if (testInput[j]=='['){ | |
brackTest(']', j); | |
}else if (testInput[j]=='('){ | |
brackTest(')', j); | |
} | |
// condintions for testing valid or invalid arrays | |
if ((testInput.length==0)||(j==testInput.length-1)){ | |
if (formatScore==0){ | |
console.log('1'+'\n'); | |
}else{ | |
console.log('0'+'\n'); | |
} | |
} | |
} | |
}; | |
}; | |
}; | |
expTest(); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment