Number generator in time - random

:)
I need a program in java, what will generate random numbers in time. Rage of random numbers is 1-100. If there will be sequence of numbers 1,50 and 95, program will stop and in the output must be written count of all random generated numbers, start and end time of generating numbers.
I need this program for my school assignment, and Im not so good at it :(
If can someone help me, it would be great.
Thanx and have a nice day :)

I made you a quick program that will generate a random amount of numbers up to 1000. The range of numbers printed are 1-100.
import java.util.Random;
Random number = new Random();
int y = number.nextInt(1000);
System.out.println("random numbers:");
for (int i = 1; i <= y; i++) {
int x = 1 + (int) (Math.random() * 100);
System.out.println(x);
}
}
}

Related

C++ srand() repeating the same string of numbers [duplicate]

So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, though y and z are different.
int main () {
srand ( (unsigned)time(NULL));
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
using the function
//random Vector
template <class T>
void Vector<T>::randvec()
{
const int min=-10, max=10;
int randx, randy, randz;
const int bucket_size = RAND_MAX/(max-min);
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
x = randx;
do randy = (rand()/bucket_size)+min;
while (randy <= min && randy >= max);
y = randy;
do randz = (rand()/bucket_size)+min;
while (randz <= min && randz >= max);
z = randz;
}
For some reason, randx will consistently return 8, whereas the other numbers seem to be following the (pseudo) randomness perfectly. However, if I put the call to define, say, randy before randx, randy will always return 8.
Why is my first random number always 8? Am I seeding incorrectly?
The issue is that the random number generator is being seeded with a values that are very close together - each run of the program only changes the return value of time() by a small amount - maybe 1 second, maybe even none! The rather poor standard random number generator then uses these similar seed values to generate apparently identical initial random numbers. Basically, you need a better initial seed generator than time() and a better random number generator than rand().
The actual looping algorithm used is I think lifted from Accelerated C++ and is intended to produce a better spread of numbers over the required range than say using the mod operator would. But it can't compensate for always being (effectively) given the same seed.
I don't see any problem with your srand(), and when I tried running extremely similar code, I did not repeatedly get the same number with the first rand(). However, I did notice another possible issue.
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
This line probably does not do what you intended. As long as min < max (and it always should be), it's impossible for randx to be both less than or equal to min and greater than or equal to max. Plus, you don't need to loop at all. Instead, you can get a value in between min and max using:
randx = rand() % (max - min) + min;
I had the same problem exactly. I fixed it by moving the srand() call so it was only called once in my program (previously I had been seeding it at the top of a function call).
Don't really understand the technicalities - but it was problem solved.
Also to mention, you can even get rid of that strange bucket_size variable and use the following method to generate numbers from a to b inclusively:
srand ((unsigned)time(NULL));
const int a = -1;
const int b = 1;
int x = rand() % ((b - a) + 1) + a;
int y = rand() % ((b - a) + 1) + a;
int z = rand() % ((b - a) + 1) + a;
A simple quickfix is to call rand a few times after seeding.
int main ()
{
srand ( (unsigned)time(NULL));
rand(); rand(); rand();
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
Just to explain better, the first call to rand() in four sequential runs of a test program gave the following output:
27592
27595
27598
27602
Notice how similar they are? For example, if you divide rand() by 100, you will get the same number 3 times in a row. Now take a look at the second result of rand() in four sequential runs:
11520
22268
248
10997
This looks much better, doesn't it? I really don't see any reason for the downvotes.
Your implementation, through integer division, ignores the smallest 4-5 bit of the random number. Since your RNG is seeded with the system time, the first value you get out of it will change only (on average) every 20 seconds.
This should work:
randx = (min) + (int) ((max - min) * rand() / (RAND_MAX + 1.0));
where
rand() / (RAND_MAX + 1.0)
is a random double value in [0, 1) and the rest is just shifting it around.
Not directly related to the code in this question, but I had same issue with using
srand ((unsigned)time(NULL)) and still having same sequence of values being returned from following calls to rand().
It turned out that srand needs to called on each thread you are using it on separately. I had a loading thread that was generating random content (that wasn't random cuz of the seed issue). I had just using srand in the main thread and not the loading thread. So added another srand ((unsigned)time(NULL)) to start of loading thread fixed this issue.

My Random Number Generator is producing small numbers

I'm trying to create a "random" number generator for my online game.
I want to create the number purely based on positions and stats of players, and also based on a small counter that increments by 1 each step in my controller.
Here's my code to create a "seed" and another function to use the seed to generate a random number from 0 -> max non-inclusive:
function generate_seed(){
var num = 1;
for(var i = 0; i < number_of_players; i++){
var prevNum = num;
num++;
}
num+=obj_controller.randStep; //randStep is a variable that gets incremented by 1 in my controller object each step
//Loops through all players
with(obj_player){
if(x % 2){num+=x;}
else {num-=x;}
if(y % 2){num+=y;}
else {num-=y;}
if(hp % 2){num+=hp;}
else {num-=hp;}
if(randStep % 2){num+=randStep;}
else {num-=randStep;}
}
return abs(num);
}
function random(var max){
//Generate synced random number from 0 -> max, does not include max
var seeder = synced_random_generate();
seeder+= max * 5; //Make sure the seed is greater than max
return seeder mod max;
}
The thing is, this sort of works, but if I do:
random(20000);
It will usually return a fairly small number relative to the max (20,000).
I've never seen it return a number greater than 3000. Which is very strange.
Does anyone know what's wrong or a possible simpler way to generate a random number based on player positions/stats and an incrementing counter in my controller?
Found a really great solution online:
int rand1(int lim)
{
static long a = 100001;
a = (a * 125) % 2796203;
return ((a % lim) + 1);
}

Non repetitive random number generator in c

I want to make a program that will give me 4 random numbers in the range 1 - 20 without any of them being the same. It does give me 4 different random numbers but every couple of tries 2 numbers are the same. I don't want that.
Here's my code:
int main(){
int g;
srand(time(0));
start:;
scanf("%d",&g);
switch(g){
case 1:RNG_4_10();
break;
default:exit(0);
break;
}
goto start;
}
int RNG_4_10(){
int a,n,i,c;
for(c=0;c<10;c++){
printf("\n");
for(i=0;i<4;i++){
a = (rand() % 20 + 1); //give a random value to a;
n = a; //assign n the value of a;
while(a == n){
a = rand() % 20 + 1;
}
printf("%d\t",a);
}
}
}
Also, I know that RNG's have a probability of repeating numbers and in theory they could generate the same number for infinity, but what I don't get is how can I have 2 similar numbers on the same run. I added that while to avoid that. Is this code wrong or my understanding is awful?
Most random number generators will have a probability of repeating values. If they didn't their behaviour would be less random by various measures.
If you want four random values in the range 1-20, then create an array of 20 elements with all those values, and shuffle it with the help of your random number generator. Then pick the first four values.
A common technique to shuffle is (in pseudocode)
/* shuffle an array of n elements */
for (i = n-1; i > 0; --i)
{
swap(array[i], array[gen(n)]); /* zero-based array indexing */
}
where gen(n) returns a suitably random value with values between 0 and n-1, possibly with repetition.

How to make sure a set of points are not chosen again by rand()

I'm writing a code that performs a random scan over a set of 4 numbers. I'd like to scan 10000 points (millions later). I just learned about rand(), so here's the relevant part:
int numPoints = 10000;
double A,B,C,D;
for (i=0; i<=numPoints1;i++) {
srand ( time(NULL) );
A = rand() % 500 + 100;
B = rand() % 500 + 100;
C = rand() % 100 - 100;
D = rand() % 5 + 2.5;
Then these four variable are fed into a function (A,B,C,D).
The code performs some checks and calculations inside the loop.
}
However, I noticed in the output file that many times, the same set of A,B,C,D is picked.
Q: Any suggestions as to how can I improve the situation?
You should move the call to srand out of the loop. Like this:
srand(time(NULL));
for (i = 0; i <= numPoints1; i++)
{
...
}
What's happening is that you're re-initializing the random number generator with each iteration. As I recall, time returns the time as a number of seconds. So time(NULL) will only change once per second, meaning that you'll be seeding the random number with the same seed multiple times.
That said, this won't guarantee that a set of numbers isn't repeated. It will, however, make duplicates much less likely.

Adding the sum of numbers using a loop statement

I need serious help dividing the positive numbers and the negative numbers.
I am to accumulate the total of the negative values and separately accumulate the total of the positive values. After the loop, you are then to display the sum of the negative values and the sum of the positive values.
The data is suppose to look like this:
-2.3 -1.9 -1.5 -1.1 -0.7 -0.3 0.1 0.5 0.9 1.3 1.7 2.1 2.5 2.9
Sum of negative values: -7.8 Sum of positive
values: 12
So far I have this:
int main () {
int num, num2, num3, num4, num5, sum, count, sum1;
int tempVariable = 0;
int numCount = 100;
int newlineCount = 0, newlineCount1 = 0;
float numCount1 = -2.3;
while (numCount <= 150)
{
cout << numCount << " ";
numCount += 2;
newlineCount ++;
if(newlineCount == 6)
{
cout<< " " << endl;
newlineCount = 0;
}
}
**cout << "" << endl;
while (numCount1 <=2.9 )
{
cout << numCount1 << " ";
numCount1 += 0.4;
newlineCount1 ++;
} while ( newlineCount1 <= 0 && newlineCount >= -2.3 );
cout << "The sum is " << newlineCount1 << endl;**
return 0;
}
I do not know C/C++ but here is a general idea of the loop assuming the values are coming from an array. (since I am unaware of how they are coming in, i.e. user input, etc.)
Logic:
Use a for loop structure opposed to a while, to loop over each element of the array.
Initialize two variables to keep count, positiveSum and negativeSum.
At each iteration of the element, check to see if it's greater than 0. That's how you can divide the positive and negative numbers accordingly.
If greater than zero, add the element onto the running positiveSum, else add it to the running sum of negativeSum.
When the loop finishes, positiveSum and negativeSum should have the calculated sum.
If this is homework, (I don't remember if the homework tag was there prior to the question, or was added on later) this pseudo code should point you in the right direction without explicitly doing the entire work for you.
Pseudo Java Code (not tested or compiled)
// as a good convention, I always initialize variables,
// for numbers I always use zero's.
double positiveSum, negativeSum = 0.0;
// assuming array holds the array of values.
for (i=0; i < array.length; i++) {
// if positive, add it to the count
if (array[i] > 0) positiveSum = positiveSum + array[i];
// else negative
else negativeSum = negativeSum + array[i];
}
Once it's completed, both positiveSum and negativeSum should hold the correct calculated sum.
If you have any questions along the way, I can edit my answer to help you achieve the correct answer, I wish I could give it away but that's what your responsibilities are for homework.
I would loop through each number individually, let's call it currentValue
if the number is negative, negativeNumberTotal += currentValue
else if positive, positiveNumberTotal += currentValue
You will get your individual totals that way. Very simple.
You are clearly overcomplicating the problem. First of all you don't need two separate loops for the numbers, as there is a constant 0.4 difference between them, even between -0.3 and 0.1. You only have to check if it's negative or not to know how to sum them up.
Loops are simpler if you use an integer as counter. As you want 14 numbers you can simply count from 0 to 13, and from that you can easily calculate the corresponding floating point value.
Example C# code:
double negSum = 0.0, posSum = 0.0;
for (int i = 0; i < 14; i++) {
double number = -2.3 + (double)i * 0.4;
if (number < 0) {
negSum += number;
} else {
posSum += number;
}
}
You can of course use a floating point number in the loop, but then you need to take into account the inexact nature of floating point numbers. You should make sure to use an ending interval that is something like halfway between the last number that you want and the next.
double negSum = 0.0, posSum = 0.0;
for (double number = -2.3; number < 3.1; number += 0.4) {
if (number < 0) {
negSum += number;
} else {
posSum += number;
}
}
Also, when repeatedly accumulating floating point numbers (like adding 0.4 over and over again), you also accumulate rounding errors. Most numbers can't be represented exactly as floating point numbers, so it's likely that you are actually adding something like 0.3999999999999994225 instead of 0.4 each iteration. It's not likely to add up to something that is enough to show up in this small example, but you should be aware of this effect so that you can anticipate it in situations with more numbers.
You have several magic numbers, whose purpose I'm not sure of, e.g numcount1 = -2.3 In general you want to avoid magic numbers.
You might want to give your variables more descriptive names than num1, num2, etc.
Could you explain more precisely what the parameters are for your assignment?
EDIT:
I've noticed that you are using very weird conditions to control your loop. You are continuing until numcount1 is = 2.9, which is a very fragile sort of setup. The first thing I would do in your shoes is to rewrite your program so that the loop terminates when there are no more numbers to add. (Alternatively, you could just make it stop after, say 12 values.)
EDIT AGAIN:
OK, how about this
int sumOfPos = 0, sumOfNeg = 0, currentValue = -2.3, terminationValue = 2.9;
while (currentValue <= terminationValue) {
if ( /* there is a missing condition here */ ) {
// need a statement here to increment your negative counter
} else {
// need a statement here to increment your positive counter
}
}
// put some statements here to do output
This is easily solvable with pure math:
lowerBound = -2.3
upperBound = 2.9
incAmount = 0.4
signChange = lowerBound % incAmount
numBelowChange = -(lowerBound-signChange)/incAmount
avgNegValue = -(numBelowChange+1)/2.0*incAmount + signChange
sumOfNegative = numBelowChange*avgNegValue
numAboveChange = (upperBound-signChange)/incAmount
avgPosValue = (numAboveChange+1)/2.0*incAmount + signChange
sumOfPositive = numAboveChange*avgPosValue + signChange
It's more accurate, and more efficient than looping and adding.
With the constants you provided,
signChange = 0.1
numBelowChange = 6.0
avgNegValue = -1.3
sumOfNegative = -7.8
numAboveChange = 7.0
avgPosValue = 1.7
sumOfPositive = 12.0
If you're unfamiliar with the % operator, x%y means "divide x by y and return the remainder". So 5%2=1
http://en.wikipedia.org/wiki/Modulo_operator
I'm not a programmer, but I thought it was best to keep the inside of a loop as lean as possible. This version works without any if statements inside the loop, just simple addition. It's late at night, and I've had a couple of whiskies, but I think this algorithm would work (it worked when I tried implementing it in python). It's psuedo code, so you'll have to write it up in yr language of choice:
neg_total =0
abs_total=0
loop with i in all_your_numbers
total += i
abs_total += abs(i)
end
neg_total=(total-abs_total)/2
pos_total=abs_Total+neg_Total
print "sum of negative values =", neg_total
print "sum of positive values =", pos_total
I'm not sure if this is good programming practice, I'm just chuffed that it worked. Points if you can explain how.

Resources