PHP Developer / Blog

July
7th, 2008

Solving Dustin Diaz’ programming brain teaser

Digg this article · Save to del.icio.us · Stumble it!

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.

2 Responses to “Solving Dustin Diaz’ programming brain teaser”

  1. Binny V A Says:

    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);

  2. jaisen Says:

    Nice…similar but slightly shorter than mine. I added a few interesting solutions to the end of the blog post.

Leave a Reply

Captcha
Enter the letters you see above.


About this site:
This is my (Jaisen Mathai) personal site for potential employers who want to see my resume or portfolio. My ideal job would be to work as a PHP developer on a large scale consumer website. My experience is in using PHP, MySQL, Ajax and JSON. I really enjoy creative brainstorming...taking a problem apart and narrowing 100 solutions down to the best one.

Thanks for stopping by. Be sure to drop me a line.