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:
abccdeeeeefefefaaafff
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"; }else if(pdups >= 2 && thisChar != prev1){ // if not matching and exiting span out += ""; } out += thisChar; // append this char to output string if(i == (arr.length-1) && dups > 0){ // close as needed at end of string out += ""; } // prepare for next iteration prev2 = prev1; prev1 = thisChar; pdups = dups; }
Some interesting solutions from the comments on Dustin’s blog.
and living in Sunnyvale, CA.
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.