Saturday, June 5, 2010

Random numbers in c++

As you know, in c++ there is one function for create random numbers. And it is:

rand();

But in rand() function, we can't giving minimum or maximum number. This function return 0 between RAND_MAX value.

And when you call rand() function, you will get same thing every time.

Example, if we try this code;

#include <stdlib.h>
#include <iostream>

using namespace std;

int main ()
{
    cout<<rand()<<endl;
    cout<<rand();
    return 0;
}
Return will be same number. But if we use srand() function, when we call rand() it's will return different number;

int main ()
{
    srand(time(0));
    cout<<rand()<<endl;
    cout<<rand();
    return 0;
}

Now, we want giving max and min numbers.

double rmax,rmin,d,final;
rmin=20;
rmax=100;
int r=rand();
d=rmax-rmin;
final=rmin+(d*(float)r/RAND_MAX);

Let's look to code; in example, out RAND_MAX value is 1000
First we create our values. In this example rmax=100, rmin=20.
And we giving rand() to int r. Let's sat it's 250.

Now our diffence (d) is equal to: 100-20=80

And final;
20+(80*(250/1000)) =
20+(80*0.25) =
20+20=
40

In this code, final number can't be smaller than rmin, and can't be bigger than rmax. And we can give float number or under zero numbers.

And finally, it's our class;

#include <stdlib.h>
#include <iostream> 
using namespace std;

class randomengine{
    public:
    int r;
    double d,s;
    void init(){srand(time(0));}
    double number(double rmax,double rmin){
        r=rand();
        d=rmax-rmin;
        s=rmin+(d*(float)r/RAND_MAX);
        return s;
        }
    };
randomengine rnd;

int main ()
{
    rnd.init();
    cout<<(int)rnd.number(20,100)<<endl;
    cout<<rnd.number(0.5,0.8);
    return 0;
}

Again sorry for bad english..

Friday, June 4, 2010

Create new function for your Shell

Well, if you hate writing same thing every time in bash shell, you can create your own fucntion.

First, open .bashrc with your editor. It's in your home directory and it's hidden files.

When you open .bashrc, goto end of file and write this;

function install {
sudo apt-get install
}

Save .bashrc and now open new shell, and example write this;

install conky
it's will do this;
sudo apt-get install conky

In this example i try install conky.

As you can see, we just write "install" for "sudo apt-get install".

And one more example; i was writing every time "sudo mount /dev/sda1 /mnt" for mount my other hdd partitions. And i create this function;

function mnt {
sudo mount /dev/sda1 /mnt
}

And when i want mount partition, i just type mnt

Sorry for bad english. I promise i will repair my language :)