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







De technische dienst van 't web: bouwt sites (WordPress, html5, jQuery) en Android apps.

