This is a homework question, but it's a small part of a much bigger project. One of the constraints is that we are not allowed to use STL for any reason.
I've attempted to roll up my own rand() function using ctime and an incrementing modifier. I figured that even though this doesn't have a consistent seed, the function should output semi-random numbers so long as it's not fed the same modifier more than once per second.
//notcstdlib.cpp
//<ctime> <cmath>
int rand(int mod)
{
time_t seed;
return std::abs(seed * mod);
}
but this sample code
//main.cpp
#include "notcstdlib.h"
#include <iostream>
int main(int argc, char** argv)
{
int f;
for(int i = 1; i <= 10; i++)
{
f = rand(i);
std::cout << "random num= " << f << "\n";
std::cout << "rand % 10 = " << f%10 << "\n";
}
return 0;
}
Always returns 7 as the first value and only even numbers between 0 and 8 for every other number.
//Output 1 //Output 2 //Output 3
random num= 134514987 | random num= 134514987 | random num= 134514987
rand % 10 = 7 | rand % 10 = 7 | rand % 10 = 7
random num= 13261304 | random num= 24238584 | random num= 27941368
rand % 10 = 4 | rand % 10 = 4 | rand % 10 = 8
random num= 19891956 | random num= 36357876 | random num= 41912052
rand % 10 = 6 | rand % 10 = 6 | rand % 10 = 2
random num= 26522608 | random num= 48477168 | random num= 55882736
rand % 10 = 8 | rand % 10 = 8 | rand % 10 = 6
random num= 33153260 | random num= 60596460 | random num= 69853420
rand % 10 = 0 | rand % 10 = 0 | rand % 10 = 0
random num= 39783912 | random num= 72715752 | random num= 83824104
rand % 10 = 2 | rand % 10 = 2 | rand % 10 = 4
random num= 46414564 | random num= 84835044 | random num= 97794788
rand % 10 = 4 | rand % 10 = 4 | rand % 10 = 8
random num= 53045216 | random num= 96954336 | random num= 111765472
rand % 10 = 6 | rand % 10 = 6 | rand % 10 = 2
random num= 59675868 | random num= 109073628 | random num= 125736156
rand % 10 = 8 | rand % 10 = 8 | rand % 10 = 6
random num= 66306520 | random num= 121192920 | random num= 139706840
rand % 10 = 0 | rand % 10 = 0 | rand % 10 = 0
Obviously I'm missing some important aspect of rand() and I'm not implementing it. Is there a better way to tackle this issue?