Programming Brain Teaser

Dustin Diaz told a programmer’s riddle — impossible to leave these things alone. So I wrote a solution. One thing bugs me: the itch that this could be done much, much easier.

var arr = ['a', 'b', 'c', 'c', 'd','e', 'e',
              'e', 'e', 'e', 'f', 'e', 'f', 'e',
              'f', 'a', 'a', 'a', 'f', 'f', 'f'];
var bingo = false;
// first two are never in a span
var result = arr[0] + ' ' + arr[1];
// old fashioned for to start at 3rd element
for (var i = 2; i < arr.length; i++) {
  // is this the third in a row?
  if ((arr[i] == arr[i-1]) && (arr[i] == arr[i-2])) {
    // start bookending them if that hasn't already been done
    if (!bingo) {
      result += ' <span>';
      bingo = true;
    }
  } else {
    if (bingo) {
      result += '</span>';
      bingo = false;
    }
  }
  result += ' ' + arr[i];
}
 
// close last one?
if (bingo) {
  result += '</span>';
}
 
// remove space after opening span tag
result = result.replace(/<span> /g, '<span>');
alert(result);
This entry was posted in coding. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • recent beluisterd