Recursive Functions, Factorials and Fibonacci Numbers.

Google “recursive functions”. Odds are that you’ll stumble upon a tutorial that explains this wondrous concept using the worst examples available.
Take this little snippet that I wrote by myself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
function factorial($x)
{
    if(!is_numeric($x) || $x<1) return 1;
    return factorial($x-1)*$x;
}
 
function fibonacci($x)
{
    if(!is_numeric($x) || $x<0) return 0;
    else if($x==1) return 1;
    return fibonacci($x-1) + fibonacci($x-2);
}
 
$a = 6;
$b = factorial(a); // factorial(6) = 720
$c = fibonacci(a); // fibonacci(6) = 8
 
echo "Factorial: $b<br/>\n";
echo "Fibonacci: $c<br/>\n";
 
>

The problem with these two examples is that by being recursive they use up far too many resources than if they had not been recursive.
The following code omits the use of recursive functions.

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function factorial($x)
{
    if(!is_numeric($x) || $x<1) return 1;
    $y = 1;
    do {
        $y *= $x;
        $x--;
    } while($x>1);
    return $y;
}
 
function fibonacci($x)
{
    if(!is_numeric($x) || $x<1) return 0;
    $y = 1;
    $x2 = 1;
    do {
        $x1 = $x2;
        $x2 = $y;
        $y = $x1 + $x2;
        $x--;
    } while($x>1);
    return $y;
}

These two non-recursive functions would arguably utilise less memory and cpu cycles than the recursive ones.

But when is it a good idea to use recursive functions? Take a recursive copy function, for example. The easiest way to create this function is to make it recursively call itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
function cp_r($src, $dst)
{
    if(file_exists($dst)) return;
    if(is_dir($src))
    {s
        mkdir($dst);
        $files = scandir($src);
        foreach($files as $file)
        {
            if($file != '.' || $file != '..')
                cp_r("$src/$file", "$dst/$file");
        }
    }
    else if(file_exists($src))
        copy($src, $dst);
}
 
cp_r("/home/user/my_old_dir", "/home/user/my_new_dir");
 
?>

Compare the previous implementation to the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
function cp_r($src, $dst)
{
	$files = array("");
	do {
		$file = array_pop($files);
		if(is_dir($src.$file))
		{
			mkdir($dst.$file);
			$tmp = scandir($src.$file);
			foreach($tmp as $val)
				array_push($files, $file.'/'.$val);
		}
		else if(file_exists($src.$file))
			copy($src.$file, $dst.$file);
	} while(!empty($files));
}
 
cp_r("C:\\usr\\src", "C:\\usr\\dst");
 
?>

Resources used by these two functions will theoretically be the same. As such, both implementations are equally valid.

My main issue with the tutorials is that their examples teach people who are new to this concept something which they undoubtedly will understand as unneeded. Using recursive functions to calculate factorials or Fibonacci numbers has too many downsides to be used as an example of recursive functions. Please use proper examples.

Posted in Uncategorized | Leave a comment

Hot Air.

Since I stopped working on my last project, a project I intend to finish, I needed to do something that I considered more fun. I thought, that a simple side-scrolling engine made by me in a hurry was something I could actually do. How I was wrong. The final version looked something like this:

A small chunk of the first test-level.

The little blue thing was supposed to be the character. You can move it, but he will always stay in the top-left part of the screen. The map itself is scrollable, but I haven’t figured out how to smooth-scroll yet. I find it much more fun if I solve such problems myself rather than look it up online. The reason why there’s only ~90 fps is because I slow the program down every time at the end of the main loop. (Sleep(10)) If I remove the delay, I get ~350 fps, but I guess I could get more out of it if I use GL or something. I should look into surface compression and optimisation with SDL.

This is the first time I tried to create polymorphic classes, but without really planing ahead I ended up with some really obfuscated code divided into several semi-polymorphic classes with about 1 method each. A few weeks ago I checked out some code by a group that can apparently program, which was CryENGINE 3 SDK by Crytek. So what I decided to do was to scrap most of what I made until now and try again, this time sitting down to plan everything through. I had to download MSVS2010 in order to test out the CryENGINE thingy, so I might as well use it before the trial runs out. Static code analysis does sound nice.

#include <dirent.h>, I will miss you. :’(

Posted in C++, HotAir | Leave a comment

A Summer Wasted.

I spent my entire summer designing an indexed color image format. It supports up to 4,294,967,296 (232) unique colours. Now, you might be thinking that it’s a stupid idea, and it probably is, but I find it useful because it is able to hold multiple palette, so I can swap palettes in-game for every image. This actually works, at least with SDL using SDL_HWSURFACE flag, with no visible frame-drops. Of course, I haven’t yet tested this in any game, only with 8 16×16 sprites, which, of course, are fast. Another thing that I can do is to have special colours that I unprofessionally dubbed “virtual” colours (there’s probably a better term for these). These must be using with a single foreground colour, which promptly changes all virtual colours to it’s respective shade of the foreground colour. Also, all palettes have support for the alpha channel.

Now, in order to hold these sprites, I wrote a little library (read: 6 functions & 8 structs) that would load both the palettes and bitmaps. I wrote it in C. And that’s where the problems kick in. TDS (the archive’s file extention) is made out of several parts. First, there’s the header, followed by some metadata; full file name, author name and description, which are encoded in UTF-8. This is followed by a list of objects inside the file, with an address to more information about the object. The bitmap objects, with the addresses of palettes, which are not objects.

Anyway, after 3 months of work. I created 3 different utilities for editing these files. None of them work properly, so I got bored and stopped working on the whole project.

I was going to use this for a small snake/tron game (tron with snake elements) that I was making, which was supposed to be my first properly made game, with actual graphics (as opposed to Atari 2600 style graphics).

I might probably finish it in the future, but at the moment it’s school time, and other projects that are actually fun.

Posted in C, C++, SnakeTron, TDS | Leave a comment

Hello world!

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
 
int main(int argc, char *argv[])
{
    cout << "Hello, world!" << endl;
 
    return 0;
}
Posted in Uncategorized | Leave a comment