Realizando mais alguns testes, criei um gerador de números randomicos, no qual o usuário informa um número inteiro e o programa utiliza esse número como escopo para gerar um número randômico.
A saída com o comando time
foi conforme pode ser visto abaixo:
Escrito em C++:
$ time ./randomizer_c 1000000
Welcome to random int.
The number you typed as maximum in a range was 1000000
The random number is 2043
real 0m0.006s
user 0m0.006s
sys 0m0.000s
Escrito em Python 3:
$ time python3 -c "import random2 ; a = random2.randint(0,1000000) ; print('O numero sorteado foi {}'.format(a))"
O numero sorteado foi 940853
real 0m0.052s
user 0m0.046s
sys 0m0.007s
O código do “random int” em C++:
#include <iostream> // For cout and cin
#include <cstdlib> // For srand() and rand()
#include <ctime> // For time()
#include <cstring> // For strtol()
// randomizer code as seen on http://www.fredosaurus.com/notes-cpp/misc/random.html
using namespace std;
int number;
int randomizer(int number);
int main(int argc, char*argv[]) {
char*p;
int randomized;
if(!argv[1]) {
cout << "Welcome to random int.\nTo randomize a number between 1 and 20, type 20, for example." << endl;
cout << "Please, type an integer number: " << endl;
cin >> number;
randomized = randomizer(number);
cout << "\nThe random number is " << randomized << endl;
} else {
int number = strtol(argv[1], &p, 10); // https://stackoverflow.com/questions/9748393/how-can-i-get-argv-as-int/38669018
cout << "Welcome to random int.\nThe number you typed as maximum in a range was " << argv[1] << endl;
randomized = randomizer(number);
cout << "\nThe random number is " << randomized << endl;
}
return 0;
}
int randomizer(int number) {
int random;
srand(time(0)); // initializa random number generator.
random = (rand() % number) + 1;
return random;
}
0 comments:
Postar um comentário