enrii.blog

A passionate programmer’s findings in the world of internet.

Programming Brain Teaser

July 9th, 2008

I joined the fun to work on a programming brain teaser by Dustin Diaz (read the original post for details). The general rule is as follows:

Group together all duplicate items that occur anytime beyond twice by wrapping them with a tag, naturally "bookending" them.

Here's my solution in PHP:

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

$count = 0;
$prev = '';
foreach ($arr as $item) {
	if ($prev == $item) $count ++;
	if ($count == 2 && $prev == $item) echo '<strong>';
	if ($count >= 2 && $prev != $item) echo '</strong>';
	echo $item;
	if ($prev != $item) $count = 0;
	$prev = $item;
}
if ($count >= 2) echo '</strong>';

Give your comments, if any.

Update: After pointed out by gbyeow in the comment, I agree that it could be optimized. I was too overwhelmed by achieving the result that I forgot to optimize after I completed the code.

The optimized version:

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

$count = 0;
$prev = '';
foreach ($arr as $item) {
	if ($prev == $item) {
		$count ++;
		if ($count == 2) echo '<strong>';
	}
	if ($prev != $item) {
		if ($count >= 2) echo '</strong>';
		$count = 0;
	}
	echo $item;
	$prev = $item;
}
if ($count >= 2) echo '</strong>';

If my article helped you solved your problem, consider buy me a beer!

Share this article: del.icio.us | digg it

Related posts:

3 Responses


gbyeow says:

Well, I would save myself some if statements and comparisons. Does the same thing. It doesn’t make the code any more concise or easier to read:

foreach ($arr as $item) {
	if ($prev == $item) {
		$count ++;
		if ($count == 2) echo '<strong>';
	} else {
		if ($count >= 2) echo '</strong>';
		$count = 0;
	}
	echo $item;
	$prev = $item;
}

EngLee says:

I agree with you. But, hey, you were only optimizing my code. Your are like simplifying mathematics formulas.

I’m sure you will get something different if you were to work from the question.

Anyway, it’s always better to optimize codings, which I didn’t do. I only tried to make it work.


Terry Riegel says:

Your code leaves extraneous [strong][/strong] tags when there are only 2 letters. It would leave something like

abcc[strong][/strong]dee[strong]eee[/strong]…

I used square brackets as I am not sure the regular brackets would make it into the comment