Programming Brain Teaser
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: