Making Your Class for-eachable in Java

I don’t like the way Java’s for-each equivalent looks. Maybe it’s just me. I actually prefer the C# version. But that’s not the purpose of this post. It’s aimed more or less at showing a sample use of interfaces and demonstrating their power. This is one of those nice topics which make me do some more research after I’m done with it. In this case, I started researching more about Collections and their core interfaces.

So you’re familiar with Java’s for loop and you probably saw the for-each one as well. Here’s an example:

Note the use of Java 7′s diamond operator. If you’ve ever wondered how this thing works, then carry on reading.  First, let’s see the most basic example of how to make our own data structure usable in this for-each loop. So say you have your own class, Structure, which holds an array of Strings and want to make it iterable in a for-each statement. What’s to be done? Well, just make the damn thing iterable! Implement the Iterable and Iterator interfaces in Structure!

And now let’s use this thing:

You can probably guess the output. Can you now guess what would happen if we added another for-each loop with our Structure object just under our existing one? Let’s have a look at a hint. The for-each loop above will be compiled the same as this one:

Even uglier and quite error-prone.

Basically, on every iteration, the iterator is checked for elements using hasNext(). If there are more elements besides the current one, then access the next element with next(). Let’s be more general. On every iteration, the result of hasNext() is tested to see whether the code in the loop will be executed. You can then access one element of the iterator using next(). Which of them? Well, whichever you want is a way of answering that. It all comes down to your implementation. You can start iterating from the last element or you can have additional rules for what you return. Note that you may not implement remove() if you don’t want.

So the class above will be useful only in one for-each loop. In the second loop of my code, hasNext() will return false from the early beginning, so the loop will be exited immediately. This is in fact not a major code flaw, but the principle behind an iterator. Check this quick answer&question on Stackoverflow to see why.

You can obviously still implement your own reset() method if you want, or change the logic in your hasNext() method such that it reinitializes the index once it’s about to return false. ;)

Resources:

Collections on Java Tutorials

for-each loop on Java Tutorials

Links Fixed

I had problems with the bottom “Older Entries” and “Newer Entries” links, in the sense that the URL was malformed. So, for example, instead of http://worldofmoca.com/index.php/page/2/ it looked like http://worldofmoca.com/index.php/Index.php/page/2/. Notice the two “index.php” in the second link.

What I did was to follow Dobert’s solution from here. However, the post was written 3 years ago and things changed a bit in WordPress. Luckily, the fix was very similar.

clean_url() is now deprecated, but, as it is mentioned in the previous link, you can (and should) use esc_url() instead. And that’s exactly what I did: pasted Donbert’s snippet in the same file (wp-includes/formatting.php) in the body of esc_url().

And Gawd, even 30 seconds of looking in a PHP file can be painful.

Project Euler: Problem 357 Intro Approach

This problem is a very beautiful one, “my type of problem” I might say (number theory FTW). I did not have much time to think about it and I actually hope I will not dedicate to it, since I have other important responsibilities at the moment. However, I invested a bit to conclude the following.

So text is here: problem 357.

Now let’s see what we can quickly find out from the text. First, for every n we’re checking, n+1 has to be prime. This is because for d = 1 or d = n we will have 1 + n/1 or n + n/n = n+1.Therefore, one approach would be to look at all prime numbers p and check p-1 for the property in our problem.

This means that n has to be even, which reduces our initial 100 million numbers to 50 million. Adding that we only have to check numbers which are 1 less than a prime further reduces this. Now let’s see if we can add other restrictions to our numbers. If n was divisible by a power of two greater than 1 (such as 4, 8 etc.), then our number wouldn’t respect the property. Can you see why?

Let’s say our number is of the form n = 4k, where k > 0. This means that both 2 and 4 are divisors of our number. For d = 2, we will have 2 + n/2. But because n is divisible by 4, then n/2 will be divisible by 2, which means n/2 is even and 2 + n/2 is even as well. This obviously cannot be prime. Therefore, n is of the form n = 2k, where k is an odd number.

And my deductions stopped here for the moment. This problem screams for creativity, good data structures/algorithms knowledge and number theory. A prime sieve for the first 100 million numbers is clearly not a good approach. In fact, I really cannot think of a brute force idea which might be anywhere near the solution of the problem and I seriously doubt there is any good one, but I am looking forward to thinking more about this. :D Again, a very beautiful -and challenging- problem!

My Thoughts On Haskell

I had to choose between Haskell and Prolog this year at university and it was a tricky one, since I had no idea about these two languages. I eventually followed my advisor’s advice. Also, I was reading about Scala back then and I thought that choosing Haskell and learning functional programming could get me closer to what the industry wants and needs. I don’t really care about the industry in general, but I really had no idea about the two languages and I needed arguments for choosing one over the other.

My first impression was that Haskell was very primitive. What else can anyone think when he starts learning a language which has no loop constructs and forces you to use recursion instead? I wasn’t afraid of recursion, but come on, NO LOOPS?! Also, when you hear the words “lazy evaluation” and have no immediate explanation of them, an untrained mind will definitely conclude that Haskell is painfully slow.

Truth is that Haskell is actually quite fast. A lot faster than I expected. Check these benchmarks. Also check this article. And, to my surprise, other languages I use -Python 3 and C#- were not foreign to lazy evaluation.

As I programmed more in Haskell and got to know the language and functional programming a bit better, I found it is very elegant and a lot smarter than I initially expected. Since I discovered lambas in C# half a year ago, I totally fell in love with them. Haskell obviously supports them. Annoyingly, Java does not (yet). Then there’s type inference and list comprehensions. Then the general increase in productivity when I code in Haskell is amazing. And the fact that it looks very mathematical at times makes it a real pleasure to use. Above all, the face of my Java-based friends when I show them a Haskell one-liner: priceless.

Today was one of the “Haskell Revision Days” and I took advantage of this to write my general impressions on the language. Revising for this exam is actually a pleasure, as you can probably tell. I set up a Bitbucket repository a while ago where I still practice the exercises offered by our lecturer and where I post my solutions to previous exam questions.

Resources

Lazy Evaluation in Haskell: on haskell.org and wikibooks.

Lazy Evaluation in C#:  Pedram Rezaei’s Ramblings

Really nice article which outlines why Haskell is awesome: 37 reasons to love Haskell

On the speed of Haskell: The speed of Haskell

PS: A nice article on Why learning Haskell/Python makes you a worse programmer. A bit old and outdated, but I somewhat agree to the “Demotivation” part haha.

Switched to “Exam Mode”

I have precisely 5 weeks left until my first exam, which is at the Mathematics module. Aiming at a “perfect score” (100%) at this one and at the Haskell exam as well. This obviously requires a lot of revision and practice, so I decided I should temporarily stop the work on side projects (Project Euler included here :( ) and concentrate on the 7 exams I have. I am not particularly interested in having good marks. I am actually interested in challenging myself and stretching my concentration and dedication to their current limits and beyond. This will eventually lead to good marks anyway, so double win. :D

I worked until late last night on my chess trainer and I managed to display the board on the screen based on the internal structures I have. I will not push my changes to github before I clean up the messy code. I think once I have a move engine which allows the player only legal moves and some graphics here and there, then I will request the help of fellow students & the open source community. :) This will happen after the 1st of June, when I have my last exam.

I have also been thinking about a different project for quite a while. My idea was to make a program which implements a part of PlanetHunters’ functionality. To be more precise, I want to be able to (1) load their data file for a particular star, (2) plot that data and (3), based on an algorithm, automatically detect a potential transit. I find three big advantages in developing this. First, it will make me do some research on detecting extrasolar planets. :) I already mentioned on this blog that I love astronomy (not as much as particle physics though ;D ). Then, it will improve my GUI designing skills. Lastly, it will make me give AI one more chance -did I mention there was a period when, for no obvious reason, I totally hated AI?-. You see, what I want to do is teach my program how to recognize transits not only using the “detection” algorithm, but by learning from the data I feed in.

Other details? Thinking of doing it in C++ with Qt. It’s been a while since I last did some proper work in C++ and I quite miss the language, especially pointers and references. Not joking. Also, it might be a good idea to give CERN’s root framework a go.

Anyway, must concentrate on exams first. ;)

My Biggest Team Project So Far

This year at uni we had a programming module which was based exclusively on team work. And they did a pretty good job when they designed the module, since the marking scheme forced us to concentrate on organisation and time management rather than just on code. In fact, only 10% of the mark was awarded on what we programmed. A massive 40% was for the report we had to submit at the end of the development, then 10% on the presentation/demonstration of our program, 10% on the prototype which he had to show halfway through the development, 10% on individual weekly logs, 10% on a test report and 10% on our initial specification. The experience I gained from this module was invaluable and I am convinced that I will use many of our organizational decisions in my future projects.

The subject was something like this: develop a game based on Settlers of Catan, in Java. We also had to use Subversion and all teams were made of 4 or 5 students of similar programming abilities. I had 84% last year at our Java module, so I guess we were quite strong.

I was very lucky to be part of an amazing team. We all were equally involved in developing the game, very supportive with each other and very well organized. We had absolutely no personal conflicts and this helped a lot. One major problem we identified at the beginning was that most of the times we couldn’t meet to discuss about our plans. I was working at least two days a week and all other team members had similar restrictive schedules, so development and communication were very hard for at least two days a week. We tried to solve this by creating as many communication channels as possible and by using resources which would keep every team member up to date with the development, even after a couple of days of absence. We used a Facebook Group for most of our communication and decisions, then a wiki page where we described more complex algorithms or general data structures and a java.net project page, where we kept track of what needed to be done, who was doing what etc. using their issue tracker. This way, everybody was aware at all times about the issues we had, what we had implemented and what needed to be implemented.

Surprisingly for a first team project, everything worked according to our initial plans. We decided in week 1 what we wanted to do, and at the end of week 10 absolutely everything was implemented. This was probably a result of good organization and time management. What also helped us was that by week 4 we were well ahead of our plans, which left us some extra time to concentrate on other modules. Year 2 was very difficult, so the extra time we found was really useful.

My favourite moment was at the beginning of week 9: a little over a week before the deadline, we decided to stop the development of new features and concentrate on the existing code. We had to solve a couple of bugs and improve the existing features of the game. Why I liked this moment? Because I believe we took a very smart and wise decision. Although we enjoyed working on the game, we also had other important deadlines coming and forcing ourselves to work on something which was already doing what we wanted wasn’t really worth it. Why get an excellent mark in a module and perform bad in the others when you can get good or very good marks in all of them? And this is exactly what happened: I got 82.5% and 100% at two very important programming assignments. Not that I care that much about marks, but many do. Many employers do. And I won’t much chances for getting into a PhD program without very good marks. Can’t argue with that.

So, verdict: 80%, very happy with the mark and with the experience. Definitely considering working with my team mates on future projects. Most important lesson learned? Communication. Good communication can not only lead to good organization, but create strong ties between the team members. You will learn immediately that you can trust the team and it will help to identify early some potential weaknesses of the team. :)

PS: I still prefer Mercurial and Git over Subversion.

Open Source Chess Trainer

On Sunday I started the development of my own Chess Trainer. I was looking for a program which could help me improve my playing, but I wasn’t very successful. I needed to be able to mark squares, add comments, tag moves/positions and so on. The good thing about the programming world is that if something doesn’t do what you want, then you can implement the thing yourself. Well, maybe most of the times.

I did some pretty good progress for the time I dedicated to it. At the moment you can set up the default board. This includes colouring the squares appropriately and placing the pieces on their initial squares. Everything tested.

My program is not going to have its own engine. Maybe I won’t use any existing engine at all. The idea of it is to support your thinking and improve strategy. It’s done in Java and it’s probably going to use Swing for the GUI. Feel free to contribute if you want. I will hopefully find time to think about some coding conventions and such and place them in a file in the repo. This way we’ll keep things as neat as possible. :D

Here’s my repo: link. Adjudju is my organization, btw. :D

My Final Year Project: Simulation of Shor’s Algorithm

A couple of weeks ago I decided what project I wanted to do in my final year. The decision was important for me not only because this project will contribute 20% or so to my degree mark. The reason I chose it has its roots at the end of my first year of university and, to some extent, in a superficial interest towards physics I have had until roughly a year ago*.

To make the story shorter, let’s concentrate on the first year of University. I was given the chance to choose a module outside of Computer Science. Little doubts I had regarding what that would be when I saw Astronomy & Particle Physics as one of the options. I didn’t know much about Particle Physics back then, but I loved astronomy at that time – and I still love it now.

Although I was passionate about this new opportunity, I concentrated more on the main programming modules I took. There were times when I thought I would fail Astronomy & Particle Physics, however I managed to do quite well, if you take into account the very superficial preparation I had for that exam. 55%, quite disappointing, but it didn’t stop here. Now follows arguably a life-changing decision.

Shortly after I finished my exams, I wanted to know how much I missed from concentrating on the other modules. And boy, it was a lot! I soon ordered arguably the best introductory book in the field of Particle Physics, that is “Quarks, Leptons and the Big Bang” by Allday. STRONGLY RECOMMENDED! From here, I kept going and going.

I became so obsessed about Particle Physics that I missed morning lectures because I was too busy reading about the subject until very late in the night/very early in the morning. But as I read more and more, I started to have a very strange feeling. Never in the last 5-6 years of my life I was so confused about what I wanted to do. I liked Computer Science quite a lot and I didn’t want to give it up. However, I kept finding Particle Physics/Quantum Mechanics increasingly fascinating. Luckily, there was a way to study both: Quantum Computing. I didn’t think twice when I found that one of the lecturers in the CS Department was interested in Quantum Computing (and used to teach this module to Masters students a year before) so I had a talk with him and now we’re gonna collaborate for the next year! :D

I listened to my supervisor’s advice about the project I could do. I wanted to (1) make something which could make me learn more about Quantum Computng and (2) make my work available in the academic environment (to be used in lectures). “Simulation of Shor’s Algorithm” was the verdict.

I don’t know much about how I am going to do it. In fact, I do have a plan, but thinking about how to put things together is a bit confusing at the moment. I am very confident with Java, the language I will code the program in, so programming-wise I won’t have problems. The only potentially difficult part will be thoroughly understanding the mathematics behind Quantum Mechanics/Quantum Computing. However, I believe that my mathematical background is strong enough to make my research as smooth as possible. I have already started studying vector spaces a couple of weeks ago and everything goes very well. :) And I also have the support of a great supervisor!

What’s to be learned from this story of mine? Always look back at things you did. Seriously, you never know when and how this decision could change your life.

*That interest is not superficial anymore ;)