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

Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *

*

De volgende HTML tags en attributen zijn toegestaan: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>