Programming Brain Teaser
I've titled this post as a "Programming" brain teaser because ideally you could solve it in any language. For the sake of the exercise, I'm going to show sample code in JavaScript, but feel free to use your language of choice. But first and foremost, the reason I'm writing about this is because I ran into a logic problem last week which I thought I would be able to solve in two seconds. Sadly it wasn't the case so I'd like to share that same problem (in obfuscated form) with you, the readers. I know what you're thinking. You're at work, and you've got a few minutes to whip up a simple answer. Cool then, go for it. Be sure to share your answer with the rest of us by linking to it offsite, but do not share code in the comments directly as others will most likely want to solve it themselves.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
});
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
In English: 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.
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

