Wednesday 7 May 2014

Project 2 - Factorial

This project won't be much difficult than the last one, but it's still a fun one.

My source code.

So, factorial of a number, some of you might be wondering what that is. The factorial is written like this 3!, 5!, 1234! and it multiplies a series of descending natural numbers from the given number.

For example:
  • 4! = 1 x 2 x 3 x 4 = 24 
  • 7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5040 
  • 0! = 1
As you can see the factorial function rises very quickly.

There are two possible approaches to writing a factorial function, iterative and recursive. Iterative generally means a loop of some kind, and recursion which is a powerful tool in programming, but somewhat tricky to understand, happens when a function calls itself.

Iterative version:
The iterative part will consist of a simple for loop and a variable in which we will save the result. The only tricky part is the declaration of both. The first thing we must realize that we're operating with multiplying so that means that we have to be careful with zeros. So we set our sum = 1 and the for loop to for(int i = 1; i <= factorial; i++). The only thing that is left if the body of the for loop. In there we will multiply the sum with the current i.

Written out for factorial of 4 this looks like:
  • sum = 1; i = 1; sum becomes 1
  • sum = 1; i = 2; sum becomes 2
  • sum = 2; i = 3; sum becomes 6
  • sum = 6; i = 4; sum becomes 24 
  • The loop ends and 24 is the correct result
Recursive version:
Here be dragons. Just kidding, recursion is not that scary (in this case). Well because recursion is when a function calls itself, we'll obviously need a function. We know that we have two cases in which 1 is the result - 0! and 1!. And we can write the an if statement that handles this. Now comes the else part, where the good stuff happens. Here I'd like to bring up an analogy for recursion that our teacher mentioned. Imagine you're being called by your buddy. You're talking, having fun, and then suddenly your mother calls you and you put your buddy on hold. Then your mom talks to you, asks you showered, eaten anything etc. A minute later your boss calls and you put your mom on hold, because you don't want to lose your job. Then you talk to your boss for a while about some reports and then finally he hangs up. Then you're back at your mom, and you say goodbye to her, and you're back at the start with your buddy. This is when recursion clicked for me (of course it helps to do some exercises). So if our number isn't 1 or 0, we should do the following: multiply the number, and let's call the function again with the number subtracted by 1 (this is your buddy calling), and then we do this until we subtracted the number to 1 (this is when the boss hangs up and you go back the chain).

Let's write this out with the same example of 4!:
  • we call the function; factorial(4)
  • we check is it 1 or 0; No; now we do 4 * factorial(3)
  • 3 is not 1 or 0, we do 3 * factorial(2)
  • 2 is not 1 or 0, we do 2 * factorial(1)
  • 1 IS 1 or 0; we return 1
  • now we go back up the chain
  • 2 * factorial(1) returns 2
  • 3 * factorial(2) returns 6
  • 4 * factorial(3) returns 24 and this is the result
I hope you liked it and please feel free to leave any comments. Thanks for reading.

Tuesday 6 May 2014

Project 1 - Reversing a string

We start of with an easy one, reversing a string. Even to a newbie programmer this shouldn't seem such a daunting task, but I'll still go through my thought process.

Obviously, nowadays reversing a string is as simple as calling a reverse() method and you're done. But where's the fun in that?

So, what I'll need is some way to extract single characters from a string. Luckily Java provides us with a charAt(int idx) method that returns a character at the specified index. Then I need a way to go through a whole string, and that's why God invented a for loop. Now I automatically started writing for(int i = 0; i < ...), but I saw that isn't going to work. I need to start at the end of the string, so I can append these characters to an empty string. For a beginner it's important to visualize this, so a piece of paper and a pencil is the greatest gift you can give yourself when starting to learn programming. Now we can rewrite the for loop and set the starting index on the strings length, but we must be careful. If we forget to subtract 1 from the length we get the glorious ArrayIndexOutOfBoundsException. Continuing with our for loop, we set the condition so that the loop goes on until its bigger or equal to 0. If we removed the 'equal to' part we can't append the last character. And the counter is set to i--, because we're descending down the string. Figuring this for loop was the meats of this project.

Now, String '+' vs. StringBuilder append()

This doesn't impact the solution of the project that much, but I figured it's still worth a mention. You can concatenate a String in two ways:

  • using built in '+' operator like this: string = string + newString;
  •  or using StringBuilder class: string.append(newString); 
In the end, both achieve the same result. Then why even bother choosing, you might ask? Everything has it's pros and cons, and so do these two methods. Using the StringBuilder is faster when you're appending to a string in a loop, because compilers aren't very good at concatenating strings in a loop, and they don't optimize the process very well. StringBuilder class is used where efficiency is needed, but we must be careful that we don't reduce the readability of the code.

String vs StringBuilder debate

Now we just slap a nice static method around our for loop, with a single String argument, and we're done. My code solution is not the only one possible, and probably not the best, so please feel free to leave comments if you have any comments or suggestions.

First post and hello

Hi.

My name is Rok, and this is my first blog. I decided to practice my programming using a blog, on which I can write about the latest projects I decided to take on. My language of choice is currently Java, because I'm most comfortable writing in it. I dabble with C because of university course, and with Python out of personal curiosity.

The "projects" I would be working on are based on the Mega Project List . I don't intend to implement all of them, but I will do my best to crack some of the hard ones. There is also a great subreddit called Daily Programmer , where users can submit programming tasks for other users to solve and then comment with their solutions. I solved a couple of the easy tasks, and they were really fun.

Then comes git. I read every day about it, I look around repos on GitHub and I think this would be a great start for me to start using it.

I always liked diving in to the deep end of the pool, and figuring a way out. Well Google is my friend, and we made it out of many sticky situations and I think I'm ready for this blog.

Thanks for reading :)