July
7th, 2008
Solving Dustin Diaz’ programming brain teaser
Dustin Diaz posted a programming brain teaser on his blog. I decided to take a shot at it and came up with this. The solution took me just under 20 minutes.
Output:
abccdee<span>eee</span>fefefaa<span>a</span>ff<span>f</span>
Code:
var arr = ["a", "b", "c", "c", "d","e", "e", "e", "e",
"e", "f", "e", "f", "e", "f", "a", "a", "a", "f", "f", "f"];
var out = ""; // output string
var i; // counter
var prev1 = "-1"; // random unique
var prev2 = "-2"; // random unique
var dups = 0; // duplicate counter
var pdups = 0; // previous duplicate counter value
for(i=0; i<arr.length; i++){
thisChar = arr[i]; // current char
if(thisChar == prev2 && thisChar == prev1){ // dups++ on 2 or more
dups++;
}else
if(thisChar == prev1){ // if this char is same as previous char then dups++
dups++;
}else{ // otherwise reset dups
dups = 0;
}
if(dups == 2){ // if this char is the 3rd dup then start a span
out += "<span>";
}else
if(pdups >= 2 && thisChar != prev1){ // if not matching and exiting span
out += "</span>";
}
out += thisChar; // append this char to output string
if(i == (arr.length-1) && dups > 0){ // close as needed at end of string
out += "</span>";
}
// prepare for next iteration
prev2 = prev1;
prev1 = thisChar;
pdups = dups;
}
Some interesting solutions from the comments on Dustin’s blog.

July 8th, 2008 at 11:24 am
My JS solution for this problem…
var arr = ['a', 'b', 'c', 'c', 'd','e', 'e', 'e', 'e', 'e', 'f', 'e', 'f', 'e', 'f', 'a', 'a', 'a', 'f', 'f', 'f'];
var last = ”;
var second_last = ”;
var opened = false;
var res = “”;
for(var i in arr) {
if(arr[i] == last && last == second_last && opened == false) {
res += “”;
opened = true;
}
if(opened && arr[i] != last) {
res += “”;
opened = false;
}
second_last = last;
last = arr[i];
res += arr[i];
}
if(opened) res += “”;
alert(res);
July 8th, 2008 at 4:14 pm
Nice…similar but slightly shorter than mine. I added a few interesting solutions to the end of the blog post.