Tagged as programming

26 Aug 2008
8 Jul 2008

A minor morsel

I haven't posted in ages, so I might as well use this to break radio silence. It's a solution to this little programming brain teaser from Dustin Diaz. I don't think it's as much of a puzzle as he seemed think, given by the responses in the comments and how long it took me, but regardless:

var listA = ['a', 'b', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e', 'f', 'e', 'f', 'e', 'f', 'a', 'a', 'a', 'f', 'f', 'f'];
var listB = [];

var count = 0;

listA.forEach(function(val,key,arr){
    var matchPrev = (val == arr[key - 1]);
    var matchNext = (val == arr[key + 1]);

    count = matchPrev ? count+1 : 0;

    if (count == 2) {
        val = '<span>' + val;
    }
    if (count >= 2 && !matchNext) {
        val += '</span>';
    }

    listB.push(val);
});

console.log(listB.join(' '));

As some of the commenters' solutions show, it can be done in a one-line regular expression, but I was sticking to the "rules" implicit in the original post.

0 comments

5 Apr 2008
19 Mar 2008
17 Jan 2008
13 Jan 2008
9 Jan 2008
6 Jan 2008
29 Dec 2007
28 Aug 2007
26 Jun 2007
15 Jun 2007
14 Jun 2007
12 Jun 2007
24 Jan 2007
15 Jan 2007
12 Dec 2006
8 Dec 2006
6 Dec 2006
3 Dec 2006
23 Nov 2006
22 Nov 2006
12 Nov 2006
9 Nov 2006
28 Sep 2006
5 Sep 2006
8 Mar 2006
15 Nov 2005
8 Sep 2005
29 Aug 2005
25 Aug 2005
22 Aug 2005

Where am I?

This site belongs to Matthew J. Tarbit esquire. A tired old web developer holed-up in a hideaway somewhere in the depths of Leeds, England.

Along with being a home for my ramblings and linkings, it's also a resting place for the bones of a shared blog by the name of Pixelised, now long departed.

If you feel the need, you may add my outpourings to the deluge that is your already overflowing info drip feed.

Or why not rest a while and dig through my entries like a corpulent pig in search of all that is truffle-icious.