Home » U++ Library support » U++ Core » random functions proposal
random functions proposal [message #35137] |
Mon, 16 January 2012 17:06 |
|
ratah
Messages: 107 Registered: July 2010
|
Experienced Member |
|
|
Hello everybody,
I looked for a random function between an interval (a,b) and did not find (maybe I am so pressed).
So, I decide to write these 2 functions c_random_a_b and upp_random_a_b for you.
#include <Core/Core.h>
using namespace Upp;
int putBetween(const int x1, const int x2, const int x3)
{
int copie_x1 = x1;
int copie_x2 = x2;
// Put x3 between x1 et x2
int d1 = x3 - copie_x1;
int d2 = x3 - copie_x2;
if(copie_x2 < copie_x1)
{
int tmp = copie_x2;
copie_x2 = copie_x1;
copie_x1 = tmp;
}
if(x3 >= copie_x1 && x3 <= copie_x2) return x3;
if(d1 == 0) d1 = (copie_x2-copie_x1)/2;
double rapport = 100*cos(d1+d2)*(copie_x2-copie_x1);
if(rapport < 0) rapport *= -1;
double dnewx3 = (100*copie_x1 + rapport)/100;
int newx3 = (int) round(dnewx3);
return newx3;
}
int c_rand_a_b(int x1, int x2)
{
// Using standard C function rand()
if(x1 == x2)
return x1;
int x3 = rand();
int newx3 = putBetween(x1, x2, x3);
return newx3;
}
int upp_rand_a_b(int x1, int x2)
{
// Using U++ function Random()
if(x1 == x2)
return x1;
String s3;
dword dw3 = Random();
s3 << dw3;
int x3 = StrInt(s3);
int newx3 = putBetween(x1, x2, x3);
return newx3;
}
CONSOLE_APP_MAIN
{
Cout() << "Random function proposal"; Cout().PutEol();
int a, b;
String sa, sb;
do
{
Cout().PutEol();
Cout() << "Enter a number named \"a\":";
sa = ReadStdIn();
a = StrInt(sa);
}
while(a<0);
do
{
Cout().PutEol();
Cout() << "Enter another number different of " << a << " named \"b\":";
sb = ReadStdIn();
b = StrInt(sb);
}
while(b<0 || b==a);
Cout().PutEol();
Cout() << "--------------------------";
/// Proposal 1: c_rand_a_b(a,b)
// To use c_rand_a_b correctly, you might reset srand each time you reexecute the program
// Otherwise you get the same sequential data
Time t = GetSysTime();
srand((unsigned int) t.second*1000);
Cout().PutEol();
Cout() << "Using standard C rand() function : c_rand_a_b(" << a << ", " << b << ") ";
Cout().PutEol();
for(int i=0; i<10; i++)
{
Cout() << c_rand_a_b(a, b) << " ";
}
/// Proposal 2: upp_rand_a_b(a,b)
Cout().PutEol();
Cout() << "Using U++ Random() function : upp_rand_a_b(" << a << ", " << b << ")";
Cout().PutEol();
for(int i=0; i<10; i++)
{
Cout() << upp_rand_a_b(a, b) << " ";
}
Cout().PutEol();
}
If similar function does not exist yet, could you add this to UPP Core.
Thank you
|
|
|
Goto Forum:
Current Time: Sat May 04 14:34:08 CEST 2024
Total time taken to generate the page: 0.02896 seconds
|