Wednesday, March 3, 2010

Programming Brain Teaser

My Normal Approach is Useless Here
We have started to learn ExtJS and use it in production with this very nice tutorial.
It's strict to the point and very easy to follow. You can try it yourself, 30 minutes per day are perfect :)
Ext JS rocks!

Meanwhile I've just got an interesting "task" from Ciprian and I couldn't go further with tutorials until I've done it :D.
What's your resolvation? Post the link with your solution on the comments. I will post mine too :)

Don't cheat yourself!

The problem is simple

First, you have an array. It looks like this:

The array

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

Be sure to use the array above in your example. You can iterate through an array easily with a batch function like forEach.

using forEach

arr.forEach(funciton(item, index, ar) {
// do stuff here

or using for

for(var index = 0; index<arr.length;index++ {
//do stuff here

In the end, we’d like to have an output that looks like the following:

The final output

a b c c d e e <span>e e e</span> f e f e f a a <span>a</span> f f <span>f</span>

You can use basic string concatenation while looping through the items to build your final output. Be sure to test and compare your output results with the actual results. And last but not least, the rule.

So the rule is this

Group together all duplicate items that occur anytime beyond twice by wrapping them with a tag, naturally “bookending” them.
Simple, right? No, really. Tease your brain for a few minutes, you can fix that bug after lunch. :p

This problem was first published here.
Enjoy your brain!
Blog powered up by Blogger