Skip to content

Instantly share code, notes, and snippets.

@CarlosBonetti
Last active April 11, 2016 13:30
Show Gist options
  • Select an option

  • Save CarlosBonetti/1383b92e43226b2e3833 to your computer and use it in GitHub Desktop.

Select an option

Save CarlosBonetti/1383b92e43226b2e3833 to your computer and use it in GitHub Desktop.
Regex Match by Brute Force
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
// ALWAYS put the test regex inside /^()$/.
// Example: /^(REGEX HERE)$/
var expr = new RegExp(/^((aa)*(c|b)((bb)|(bc)|(bb(cb)*))*|(aa)*a(cb)?((bb)|(bc)|(bb(cb)*))*)$/);
var alpha = ['a', 'b', 'c'];
var maxSize = 5;
var sentences = [];
sentences[0] = [''];
sentences[1] = alpha.slice(0); // clone array
var k = 1;
while(k < maxSize) {
sentences[k+1] = [];
for(var i in sentences[k]) { // sentences of size k
for(var j in alpha) {
sentences[k+1].push(sentences[k][i] + alpha[j]);
}
}
k++;
}
for(var i in sentences) {
document.body.innerHTML += '<b>Size: '+i+'</b><br>';
for(var j in sentences[i]) {
var sentence = sentences[i][j];
if (sentence.match(expr)) {
document.body.innerHTML += '<font color="green">'+sentence+'</font> --- '+count(sentence, alpha)+'<br>';
} else {
document.body.innerHTML += '<font color="red">'+sentence+'</font> --- '+count(sentence, alpha)+'<br>';
}
}
}
function countLetter(sentence, char) {
var c = 0;
for(var i in sentence) {
if (sentence[i] == char) {
c++;
}
}
return c;
}
function count(sentence, alpha) {
var r = "";
for(var i in alpha) {
var c = alpha[i];
var total = countLetter(sentence, c);
r += "#" + c + " = " + total + " | ";
}
return r;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment