rand() doesn't work even with srand( time(NULL) ) - c++

So I'm trying to generate random integers inside functions, but it returns the same numbers. NUM_SOURCES == 5 and for all 5 repetitions it gives the same number despite srand(time(0)) being called. I tried the same without std::, but the result did not change.
Any suggestions?
std::srand(time(0)); //setting seed
...
for (int i = 0; i < NUM_SOURCES; i++)
{
if (sourceDeq->at(i)->getCurrentBid() == NULL) // If the source is empty, generate a new order
{
sourceDeq->at(i)->setCurrentBid(sourceDeq->at(i)->generateBid(systemTime));
}
}
...
Bid* Source::generateBid(int sysTime)
{
bidAmount = bidAmount + 1;
return new Bid(bidAmount, generateTimeCreation(sysTime), 0, 0, 0, getNumber());
}
...
int Source::generateTimeCreation(int sysTime)
{
srand(0);
if (sLaw == UNIFORM)
return (sysTime + std::rand() % 10);
if (sLaw == EXPONENTIAL)
return(sysTime + round((1 - exp(-(std::rand() % 100))) * 10));
}

srand(0); initializes the random number generator again, so it will have the same results, every time... Don't do it.
The whole point of calling with time(NULL) is to provide a random seed.

Related

Finding Sum of Square of Digits Beginner Bug C++

So, I started learning C++ recently. This code is trying to add the sum of the squares of each numbers digits. For example: 243: 2*2 + 4*4 + 3*3 = 29.
int sumOfSquareDigits(int n) //BUG WITH INPUT OF 10, 100, 1000, etc.
{
int digits = findDigits(n);
int number;
int remainder;
int *allDigits = new int[digits];
for (int i = 0; i < digits; i++) { //assigns digits to array
if (i + 1 == digits){ //sees if there is a ones value left
allDigits[i] = n;
}
else {
remainder = (n % findPower10(digits - (i + 1)));
number = ((n - remainder) / findPower10(digits - (i + 1)));
allDigits[i] = number; //records leftmost digit
n = n - (allDigits[i] * findPower10(digits - (i + 1))); //gets rid of leftmost number and starts over
}
}
int result = 0;
for (int i = 0; i < digits; i++) { //finds sum of squared digits
result = result + (allDigits[i] * allDigits[i]);
}
delete [] allDigits;
return result;
}
int findDigits(int n) //finds out how many digits the number has
{
int digits = 0;
int test;
do {
digits++;
test = findPower10(digits);
} while (n > test);
return digits;
}
int findPower10(int n) { //function for calculating powers of 10
int result = 1;
for (int i = 0; i < n; i++)
result = result * 10;
return result;
}
And after running the code, I've figured out that it (barely) mostly works. I've found that whenever a user inputs a value of 10, 100, 1000, etc. it always returns a value of 100. I'd like to solve this only using the iostream header.
Sorry if my code isn't too readable or organized! It would also be helpful if there are any shortcuts to my super long code, thanks!
The problem is in the findDigits function. For the values 10, 100, 1000 etc, it calculates the number of the digits minus one. This happens because of the comparison in the loop, you are stopping when n is less or equal to test, but in these cases n is equal test and you should run the next iteration.
So, you should change the line 33:
} while (n > test);
to:
} while (n >= test);
Now, it should work just fine. But it will not work for negative numbers (I don't know this is required, but the solution bellow works for that case too).
I came up with a much simpler solution:
int sumOfSquareDigits(int n)
{
// Variable to mantain the total sum of the squares
int sum = 0;
// This loop will change n until it is zero
while (n != 0) {
/// The current digit we will calculate the square is the rightmost digit,
// so we just get its value using the mod operator
int current = n % 10;
// Add its square to the sum
sum += current*current;
// You divide n by 10, this 'removes' one digit of n
n = n / 10;
}
return sum;
}
I found the problem challenging managed to reduce your code to the following lines:
long long sumOfSquareDigits(long long i) {
long long sum(0L);
do {
long long r = i % 10;
sum += (r * r);
} while(i /= 10);
return sum;
}
Haven't test it thoroughly but I think it works OK.

How do I randomize these numbers?

So my homework assignment is to create a looping function to print only even numbers from 0 – 200. I need to create 100 random and even numbers(only 10 numbers can print per line). I'm having trouble randomizing the numbers. This is what I have so far:
// Loop from 0 to 200
for (i = 2, j = 1; i <= 200; i++, j++)
{
// Print even numbers(divisible by 2)
if (i % 2 == 0)
{
cout << i;
}
// Create new line after printing 10 numbers
if (j == 20)
{
j = 0;
ofs << '\n';
}
}
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
int main()
{
srand (time(NULL));
int even = rand() % 200;
if (even % 2 == 0)
{
cout<<even;
}
}
Here is some quick code that prints 100 even numbers [0..200] in a random order without repeating them:
#define PRIME 7879 /* Some big prime number (>> 100) */
#define NUMS 100 /* Number of values to process */
#define PRINT_GROUP 10 /* Number of values printed on a line */
int main()
{
int number = rand() % NUMS;
int i;
for (i = 0; i < NUMS; i++) {
printf("%d%c", 2*number, (i + 1) % PRINT_GROUP == 0 ? '\n' : ' ');
number = (number + PRIME) % NUMS;
}
return 0;
}
Apart from that, your code is a little off the way.
Here are some things that may be confusing to other coders (.. anyways if you feel comfortable with your style that's really ok)
"for (i = 2, j = 1; i <= 200; i++, j++)" 2 Variables are a little bit wierd,
try to use only one variable. .. Just make it something like this:
int j = 1;
for (i = 2; i <= 200; i++) {
j++;
//Code
if (j == 20) {
j = 0; //etc.
}
}
Beside that "J" looks familliar to "I" so that could confuse others.. try to call it "count", that's pretty standard.

Sudoku Blanks - c++

I have to write a program that takes in a Sudoku square(with all slots filled) and randomly assigns 25 blanks to be filled in. This is what I have so far but because this code has the chance to generate the same position in the array more than once I'm getting a varying number of blanks(17-21). I'm wondering if there is a simple way to get it to output 25 blanks no matter what. My print function inserts a blank if the value is zero at any spot in the array.
void insertBlanks(int square[9][9])
{
srand(time(NULL));
int i = 0;
while(i < 25)
{
int tempOne = rand() % 9;
int tempTwo = rand() % 9;
square[tempOne][tempTwo] = 0;
i = i + 1;
}
}
You should check if a 0 is already there.
if(square[tempOne][tempTwo] != 0)
{
square[tempOne][tempTwo] = 0;
i = i + 1;
}

Generate unique multiple random numbers

I want to generate unique random numbers and add item in function of these random numbers. Here is my code :
The problem is when i verify if the number generated exist in the array with the code results.contains(randomNb) :
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 1;
int results[1000];
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results[i] = randomNb;
//We add the new randomNb in the array
i++;
}
}
results is an array. That's a built-in C++ type. It's not a class type and doesn't have methods. So this can't work:
results.contains(randomNb)
You probably want to use a QList instead. Like:
QList<int> results;
Add elements to it with:
results << randomNb;
Also, you have an off-by-one error in the code. You start counting from 1 (i = 1) instead of 0. This will result in missing the last number. You should change the i initialization to:
int i = 0;
With the changes, your code would become:
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 0;
QList<int> results;
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results << randomNb;
//We add the new randomNb in the array
i++;
}
}

Atomic int incorrectly incrementing? Intel TBB Implementation

I'm implementing a multi-threaded program to validate the Collatz Conjecture for a range of numbers using Intel TBB, and I am having trouble figuring out why the atomic variable <int> count (which keeps count of how many numbers were validated) is not incremented correctly.
For the relevant code listed below, I used a small interval (validating just numbers 1-10, but the problem scales as the interval gets larger) and I consistently get a return value of 18 for count. Any ideas?
task_scheduler_init init(4);
atomic<int> count;
void main
{
tick_count parallel_collatz_start = tick_count::now();
parallel_collatz();
tick_count parallel_collatz_end = tick_count::now();
double parallel_time = 1000 *(parallel_collatz_end - parallel_collatz_start).seconds();
}
void parallel_collatz()
{
parallel_for
(
blocked_range<int>(1,10), [=](const blocked_range<int>&r)
{ for (int k = r.begin(); k <= r.end(); k++) { collatz(k); } }
);
}
long long collatz (long long n)
{
while (n != 1) {
if (n%2 == 0)
n = (n/2);
else
n = (3*n + 1);
}
if (n == 1) {
count++;
return n;
}
return -1;
}
The reason is probably that the constructor uses the half-open range, [1, 10) which means 1 inclusive 10 exclusive, so you're not validating numbers 1-10 but rather 1-9. Additionally you probably want to use != instead of <= in your loop condition.