Affichage des articles dont le libellé est programming. Afficher tous les articles
Affichage des articles dont le libellé est programming. Afficher tous les articles

samedi 6 septembre 2014

How did fortran (and modern programming languages) come into existence

Excerpt from stanford C++ course (cs106b)

In the early days of computing, programs were written in machine language, which consists of the primitive instructions that can be executed directly by the machine. 
Machine-language programs are difficult to understand, mostly because the structure of machine language reflects the design of the hardware rather than the needs of programmers. In the mid-1950s, a group of programmers under the direction of John Backus at IBM had an idea that profoundly changed the nature of computing. Would it be possible, they wondered, to write programs that resembled the mathematical formulas they were trying to compute and have the computer itself translate those formulas into machine language? In 1955, this team produced the initial version of Fortran (whose name is an abbreviation of formula translation), which was the first example of a higher- level programming language. 

I guess that this bright idea was what brought the modern programming languages into existence. After all, it's possible to express any mathematical formula with an instruction or two in any programming language. Programming requires logical thinking, which is something mathematicians are good at. It might not be always the case, but I think a good mathematician can be a good programmer. However, a good programmer is not necessarily good in mathematics.

lundi 21 mai 2012

one of a million reasons to love programming

From the introduction to the excellent free book Programming ground up,

I love programming. I enjoy the challenge to not only make a working program, but to do so with style. Programming is like poetry. It conveys a message, not only to the computer, but to those who modify and use your program. With a program, you build your own world with your own rules. You create your world according to your conception of both the problem and the solution. Masterful programmers create worlds with programs that are clear and succinct, much like a poem or essay.

vendredi 6 avril 2012

Swapping numbers in java, pass-by-value VS pass-by-reference

I never thought about it, but I just discovered it is not possible to write a method to swap numbers in Java since Java is strictly pass-by-value, not pass by reference.
public void swapNumbers(int x, int y)
{
    int temp = x;
     x = y;
     y = temp;
}
If we call this function to try to swap numbers, the numbers won't be changed.
There is an example of swapping numbers in this link: http://www.roseindia.net/java/beginners/swapping.shtml, but it's confusing for beginners.

public class Swapping{
  static void swap(int i,int j){
  int temp=i;
  i=j;
  j=temp;
  System.out.println("After swapping i = " + i + " j = " + j);
  }
  public static void main(String[] args){
  int i=1;
  int j=2;
 
  System.out.prinln("Before swapping i="+i+" j="+j);
  
swap(i,j);
 
  
}
}


This example doesn't mention that after we call the method swap, the numbers will return to their original values after this call.
The same operation is really simple in C++ which allows us to pass values by reference

void swapNumbers(double& a, double& b)
{
    double temp = a;
    a = b;
    b = temp;
}
 
Now, when we call this function, a and b will be swapped.*

double number1(5.5), number2(7.0)
swapNumbers(number1, number2);
cout << "First number : << number1 << endl;
cout << " Second number :" << number2 << endl;

The output will be
First number : 7.0
Second number 5.5;

A reference is merely an alias, another name for the same variable. Hence, making operations on a variable will also change the variable value.

real life example for passing argument by reference in java

I read this in one of the comments for this answer in SO http://stackoverflow.com/a/40523/612920

My attempt at a good way to visualize object passing: Imagine a balloon.
Calling a function is like tieing a second string to the balloon and handing the line to the function.
parameter = new Balloon(); will cut that string and create a new balloon (but this has no effect on the original balloon).
parameter.pop(); will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.

mercredi 4 avril 2012

Everyone should learn Vi / VIm

I always wanted to learn vi. It seems that once you get to know it well, you can be a lot more productive.
The problem is you got to invest some time to learn all the shortcuts that will help you to be productive and practice them often to get used to them. A good start is the vimtutor which is an interactive learning resource that can be started by typing vimtutor in the shell. Once you finish the tutorial, you can find a ton of resources on the internet. Personally, I'm starting with vim tips http://vim.wikia.com/wiki/Vim_Tips_Wiki. There is a lot of good tips, like autocompletion feature which can be done using Ctrl+N for next word and Ctrl+p for previous word.
If I can be as good in vi as this guy http://stackoverflow.com/a/1220118/612920 , I'm sure I'll be at least 10 times faster. If you decide as well to start learning vim, I'm sure you are making a good decision.

vendredi 20 janvier 2012

Getting started with TDD - Test Driven Development

Update: Here is the GitHub repository containing a FlashBuilder project containing the final test:
Flex-HashMap

I am just familiar with some basic concepts of unit testing. I didn't have the chance to work in a professional environment that would allow me to write unit tests for complicated business code, so all I've tried is really simple examples like the famous addition example. In this article, I'm trying to get a little bit more in depth by using TDD (Test Driven Development).
Test Driven Development can be defined as reversing the traditional development life-cycle upside down. Instead of writing the tests after our code is ready to be tested, the first thing we do is to write tests even before we have any code to test. The code is written for the sole purpose of making tests pass. So the development life-cycle is as follows:
- add a test
- make sure that the test fails
- write the simplest code to make the test pass
- refractor
- do it again
as simple as that. The benefits for using TDD come from the fact that we are repeating very short development life-cycles, and as a result we end up having a high quality and error prone code. I'm implementing the unit tests for a HashMap class implemented in AS3 By Eric J. Feminella. You can find the final code here :
Eric J. Feminella HashMap Implementation. Though, I will be making some changes to it later, I'll put the final code on github.
Of course, in TDD, we have to begin by writing the tests, so before implementing that class, we need to implement a test class:

package tn.zuro.tests.collections
{
    public class HashMapTest
    {        
        private var map:IMap;

        [Before]
        public function setUp():void
        {
            map = new HashMap();
        }
        [After]
        public function tearDown():void
        {
        }
    }
}

Here is our first failing test. A test that doesn't compile can be considered as a failing test. Our test won't compile here since the compiler won't recognize neither IMap or HashMap as we have not implemented them yet. Now let's write some code to make this test pass or at least compile.

package tn.zuro.collections
{
    public interface IMap
    {
    }
}

package tn.zuro.collections
{
    public interface HashMap
    {
    }
}
Now our code will compile, but it still fails: we haven't implemented any runnable methods yet. Let's start by adding some basic methods. The HashMap in our case will use flash.utils.Dictionary since it allows us to implement key/value pairs. we could start by implementing a test method for the method put:
[Test]
public function testPut():void
{
    map.put("d", "value A");
    map.put("e", "value B");
    map.put("f", "value C");
    map.put("u", "value X");
    map.put("v", "value Y");
    map.put("w", "value Z");
}
Now if we run the test, it will fail, the method is not implemented. We go back to IMap, and we add the put method declaration:
function put(key:*, value:*) : void;

Now we need to implement the simplest possible code to make the test pass:
public function put(key:*, value:*) : void
{
    _map[key] = value;
}
Finally, we have a test that passes without problems. Our first iteration is complete, now we have to repeat. We will test the size method next, so that we can add some assertions to our code:
[Test]
public function testSize():void
{
    assertEquals(map.size(), 6);
    map.put("d", "value D");
    assertEquals(map.size(), 7);
    map.put("a", "value K");
    assertEquals(map.size(), 7);
}
We can also add some code to the setUp method, so that we have some key/value pairs in our hashmap to play with.
private var map:IMap;
[Before]
public function setUp():void
{
    map = new HashMap();
    map.put("a", "value A");
    map.put("b", "value B");
    map.put("c", "value C");
    map.put("x", "value X");
    map.put("y", "value Y");
    map.put("z", "value Z");
}
The test fails again, since the method size doesn't exist, yet. Thus, we declare it in the interface and implement it in the HashMap class:
function size() : int;
        
public function size() : int
{
    var length:int = 0;
    for ( var key:* in _map )
    {
        length++;
    }
    return length;
}
The loop
for (var key:* in _map)
allows us to iterate over the keys of the dictionary, to iterate over the values, we can use a for each loop. Now our test passes again, and we can see the results of our assertions. In the method testSize, we have the following assertions:
assertEquals(map.size(), 6);
which should return true since we have put 6 values in the setUp method. We are also sure that the put method works the way it should be.
assertEquals(map.size(), 7);
returns true for the same reasons
and then:
    map.put("a", "value K");
    assertEquals(map.size(), 7);
    this returns true as well, because we used the same key again, so we have
_map["a"] = "value K";
which updates the value associated with the key "a".
   
Let's repeat one more time to make sure we got the process right, and to understand how useful tests can be.
I'm going to add a test for the clear method which will remove all the elements from the dictionary. The clear method will use another method which will remove a key/value pair from the dictionary. We should start by adding a testRemove method to have a failing test, make the test pass, and repeat again. We skipped the refractoring step here, cause the code is too simple and does not require any refractoring. Then we repeat again. Then we write a test for the clear method.
[Test]
public function testRemove():void
{
    map.remove("a");
    assertEquals(map.size(), 5);
}
        
[Test]
public function testClear():void
{
    map.clear();
    assertEquals(map.size(), 0);
}
IMap.as
function remove(key:*) : void;
function clear() : void;
HashMap.as
public function remove(key:*) : void
{
    _map[ key ] = undefined;
    delete _map[ key ];
}
        
public function clear() : void
{
    for ( var key:* in _map )
    {
        remove( key );
    }
}
Now that all the code of the two iterations is in place, everything should be working smoothly, right? Well, not quite. The test method testClear is going to fail. This means that there is a problem with the clear function. The problem comes from the first instruction in the remove function. 
_map[key] = undefined;
I managed to find the problem after I asked a question in StackOverflow: Flex dictionary question. If we didn't test this code thouroghly, it's possible we wouldn't notice this error. And using TDD, we noticed it very early in the development lifecycle, so that it could be corrected very early, and now we have less bugs to worry about. The remove function should look like this:
public function remove(key:*) : void
{
    delete _map[ key ];
}
And this time, the tests pass. I guess that's all what's TDD is about. It's not complicated. It just takes a little time to get used to it, and once we know it good enough, it can speed up development significantly.

dimanche 18 décembre 2011

Getting started with the javadoc

If you are using eclipse, working with javadoc is pretty easy. It's not that complicated using the command line either, personally I'm an addict to the command line, but I didn't bother too much with generating the javadoc using it since I tried already and I failed miserably. I had a problem when trying to set the classpath, since there was a lot of dependencies to include. I should have written an ant script, but I was too lazy. All programmers are :). So, I just chose the easy way for once, selecting project > generate javadoc... You have then to go through the usual straightforward process, choosing some options and then next, next.

java heap space configuration


And don't forget to configure the JVM heap space, especially when you have a big project with a lot of comments in it. This way, the javadoc will be generated a lot faster, and you won't be at the risk of having an error with heap space.
My advice is, don't forget to document well you code. A good code is a self documenting code. Compare:

int x;
String y;

and

int hitPoints;
String playerName

A lot better, isn't it?
And if you have a self documenting code like the last one, when you put comments to explain it, if you are not going to add some value to the explanation, it's better to leave it as it is.



/** calcualte the number of the likes */ 
public int calculateNumberOfLikes()

That's what I would call a waste of time. Who'd do that anyway, well, more people than you think, not all people have learnt to program the way programming should really be.




/** This function calculates the number of the likes of a friend.
 * 
 * This function calls an FQL query which determines the pages a friend likes,
 * and calculates the number of times he liked an item in that page
 *
 * @author someone 
 */ 
public int calculateNumberOfLikes()

This is just a little example to show the forms a javadoc comment has. The first sentece is a summary of what the function does. Then a more detailed description, then some javadoc-specific tags about the purpose of the function, we can add html tags to this description in order to format it the way we want. There is a lot of tags to know about, which can give us a lot of information about a function, a class or a variable. So, it's good to have the habit of well documenting our code, cause we are not the only ones that work in our code, and we can make others win a lot of time by making it easier for them to understand our code. And in case of a solo programmer working on his hobby project, you'll eventually end up coming back to the code you wrote after some months, and then, there is no telling how much of your code you will remember and how much time you will waste because of a poor documented code.

mercredi 26 octobre 2011

AI contest

If you are interested in game programming and AI, you might want to take a look at the AI ants challenge. It is a challenge sponsored by google, and this is the presentation of the contest by the official website :
The AI Challenge is all about creating artificial intelligence, whether you are a beginning programmer or an expert. 
All you have to do is pick your favourite programming language. There is already about 20 of the most popular languages, and the contest organizers are willing to add another ones if they receive requests on the forum. Once you know what programming language you are going to use, you can download the tools that will help you in your quest, and then download the starter kit for that language. The game engine is written in python, so you'll need to install python on your computer. Don't worry if you don't know any python at all, you don't need to. As for the installation of python, it's pretty straightforward. If you are on a Linux machine, it should be installed already. If you are on windows, you can download a windows installer which will do the work for you, or you can use cygwin.

You should participate regardless of your level. You could get a good rank in the leader board, which will look good on your resume, but even if you don't, it was a good learning opportunity, and you'll have some prerequisites for future contests.

Good luck everyone!

vendredi 14 octobre 2011

Thoughts about programming

IMHO, programming is not just about writing code, correcting bugs, learning a couple of programming languages, or knowing how to do some tricks with them. Programming is about solving problems, or even better, it's about the approach taken to solve a problem. Sometimes there is only one way to do things. But most of the time, there are many ways. What makes the difference between an average programmer and a good one is that the latter will always find a better way to solve the problem.

It's not that the first one is not able to find that solution, it's just that when he found the first solution that came to his mind, he didn't take the time to think further about the problem, he didn't ask himself the questions you should ask yourself: Is this the only way to do it? Isn't there a better way? Why don't I try to solve this problem in more elegant way. You have to challenge yourself, try to be better than yourself.

That's what makes the difference. There are average programmers who remain average either because they don't want to go that extra mile and try to find that better solution, or because someone taught them in the beginning some way to think, which was not the best way and they didn't have the chance to learn another way. As for the rest, those who aspire to become always better, stop writing code for a second, take the time to think deeply, try to read some code written by professional people and ask yourself why did they do it this way not that way. And as long as you are passionate about programming and you keep learning new things, you'll end up being the one finding the best solution.