I’ve started a monthly-ish coding quiz on my little Canberra Java Devs Fresh Bytecode Newsletter. But other people might be interested in the odd puzzle they can do in a lunchtime, so I’ll post them here under the Quiz category.
We’ll start with something simple, perhaps a quick and dirty bracket matcher?
Give a series lines containing both well formed brackets (where each opening bracket has a matching closing bracket) and malformed brackets (where there are more opening than closing or the closing appears before the opening, etc), tell me which ones are valid and invalid. So…
( ) is valid
( ) ) is invalid
( ( ) ( ) ) is valid
) ( ) ( is invalid
( ( ( ) ) ( ( ) ) ) is valid
and so on.. it can get quite sneaky, quite quickly, so be warned.
Gold stars for creative solutions (don’t just think performance).
I can think of two or three simple approaches right away that might be faster or slower than one another. Wonder if you could even do it with a regexp? The options are endless. Why don’t you choose an implementation strategy that stretches you. Recursion? Regexp? Unusual data structure? Parser?
Of course, you’ll need some sample data to start with, so here’s a 1000 lines worth of known good brackets to get you started. Or why not just fork my github repo for a Maven project with a blank solution and sample data that’s ready to go.
If you do get keen and implement something, you can post a link to your Github/Bitbucket/Pastebin in the comments if you like.
Most importantly, have fun!