Kevin Gessner

Brain Teaser

PHP solution to this brain teaser – it only took a few minutes.

In:

$array = array('a', 'b', 'c', 'c', 'd','e', 'e',
'e', 'e', 'e', 'f', 'e', 'f', 'e',
'f', 'a', 'a', 'a', 'f', 'f', 'f');

Out:

abccdee<span>eee</span>fefefaa<span>a</span>ff<span>f</span>

My Solution:

$curr = '';
$count = 0;
foreach($array AS $letter) {
	if($curr != $letter) {
		if($count > 2) // more than two dupes
			print '</span>';
		$count = 0;
		$curr = $letter;
	}
	if($count == 2) print '<span>';
	$count++;
	print $letter . ' ';
}

-- Kevin Gessner
September 17, 2008

This is part of Nihilartikel, my collected writings.
Back to the home page