This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 9 years ago.
I was wondering, how can I generate unique random numbers except from a specific one. For example, if I want to generate numbers in range 1 to 10 except from 3, the output should be something like this:
7 6 1 2 4 9 5 8 10
Shuffle the numbers 1 - 10 and remove 3.
It doesn't matter if you remove the 3 before or after shuffling.
Alternatively, shuffle the numbers 1 - 9 and relabel 3 as 10...
For shuffling without bias you can use for example the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Generate random number in the range 1..9 and add one if the number is greater than or equal to 3.
Generate a number. Check its value, if the number is 3 generate another one. If it isn't 3 then use it.
EDIT: Thinking before coffee is a terrible plan. If you want to get every number in the range in a random order then I agree with the others talking about shuffling lists. If however you want some random subset of the range I would store a list of forbidden values. Shuffling and only taking the first n numbers would also be suitable if the range isn't very large (e.g. not something like 0<x<INT_MAX).
Every time you generate a number check if the generated number is on the forbidden list and if it is, generate another number. Every time you generate a valid number you add it to the list to ensure generated numbers are unique. The list should also be initialised with your unwanted numbers (3 in the example given).
You may try like this:-
unsigned int
randomnumber(unsigned int min, unsigned int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
then later you can do this:-
x = randomnumber(1,10);
if (x==3)
{ x = x+1;}
or
if (x!=3)
{ printf("%d",x)}
This is my answer - returns random value in [min, max), except "except".
int myrand(int min, int max, int except) {
int rc;
do {
rc = min + rand() % (max - min);
} while(rc == except);
return rc;
}
This code will generate unique random numbers from minimum to maximum of a given range.
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, min_range, i = 0, rand_num;
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
printf("Enter your minimum of range: ");
scanf("%d", &min_range);
bool digit_seen[max_range + 1]; // VLAs For C99 only
for (int i = min_range; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + min_range;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}
Related
This question already has answers here:
Generate random number in C within a range and a specific step
(2 answers)
How to use the rand function to make numbers in a specific range?
(4 answers)
Closed 5 years ago.
I've tried but it doesn't seem to give me the desired numbers. Here's my code so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
printf("Value of n:\n");
scanf("%d", &n);
int t[n];
for(i=0; i<n; i++)
printf("%d ", rand()%20+30);
return 0;
}
printf("%d ", rand()%20+30);
generates random numbers between 30 and 50 (not included). You need
printf("%d ", rand()%10+20);
to generate between 20 and 30 (not included)
10 being the range, and 20 being the offset.
To include both end points (giving 11 possible values):
printf("%d ", rand()%11+20);
these are the expressions
number = 21 + rand() % 9 // for (20, 30)
number = 20 + rand() % 11 // for [20, 30]
Try rand()%10+20.
rand()%10 gives numbers between 0 and 9. Adding then 20 will give numbers between 20and 29.
For numbers between 20 and 30 (inclusive), use rand()%11+20.
To generate random number in range [A .. B], first take difference between numbers: D = B-A, then generate a random number in the range of [0..D] and add that to A:
unsigned myRand(unsigned fromA, unsigned toB)
{
if (fromA > toB) // check if fromA is
return myRand(toB, fromA);
int d = toB - fromA; // difference between numbers: D = B-A
int r = rand() % (d+1); // random number in the range of [0..D]
return r + fromA;
}
Or, you may just to it manually like this:
20 + (rand()%11)
Also, note that depending on implementation rand() returns values between 0 and RAND_MAX, so you won't be able to create random values large than RAND_MAX (which might be as small as 32767). In this cases you may combine multiple rand() calls to get large random numbers:
unsigned r = (rand() << 16) | rand();
I'm new to C programming (I have some very basic experience with programming via vb.NET), and I'm attempting to write a program for the Project Euler Problem #1.
https://projecteuler.net/problem=1
Algorithm
The challenge requires the programmer to find the sum of all multiples of 3 or 5 (inclusive) below 1000 (I used intInput to allow the user to enter an integer in place of 1000).
My current solution takes the input, and decrements it by 1 until (intInput - n) % 3 = 0, that is, until the next nearest multiple of 3 under the input integer is found.
The program then cycles through all integers from 1 to ((intInput - n) / 3), adding each integer to the sum of the previous integers, so long as the current integer is not a multiple of 5, in which case, it is skipped.
The resultant sum is then stored in intThreeMultiplier.
The above process is then repeated, using 5 in place of 3 to find the highest multiple of 5 under intInput, and then cycles through integers 1 to ((intInput - n) / 5), not skipping multiples of 3 this time, and stores the sum in intFiveMultiplier.
The output sum is then calculated via sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier).
The Problem
Whenever I compile and run my code, the user is allowed to input an integer, and then the program crashes. I have determined that the cause has something to do with the first For loop, but I can't figure out what it is.
I have commented out everything following the offending code fragment.
Source Code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int intInput = 0; /*Holds the target number (1000 in the challenge statement.)*/
int n = 0;
int count = 0;
int intThreeMultiplier = 1;
int intFiveMultiplier = 1;
printf("Please enter a positive integer.\n");
scanf("%d",intInput);
for( ; (((intInput - n) % 3) != 0) ; n++)
{}
/*for(; count <= ((intInput - n) / 3); count++)
{
if ((count % 5) != 0)
{
intThreeMultiplier += count;
}
}
count = 0;
for(n = 0 ; ((intInput - n) % 5) != 0 ; n++)
{}
for(; count <= ((intInput - n) / 5) ; count++)
{
intFiveMultiplier += count;
}
int sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier);
printf("The sume of all multiples of 3 or 5 (inclusively) under %d is %d.",intInput, sum);*/
}
This is my first time posting on StackOverflow, so I apologize in advance if I have broken any of the rules for asking questions, and would appreciate any feedback with respect to this.
In addition, I am extremely open to any suggestions regarding coding practices, or any rookie mistakes I've made with C.
Thanks!
scanf("%d",intInput);
might be
scanf("%d", &intInput); // note the ampersand
scanf need the address the variable where the content is to be stored. Why scanf must take the address of operator
For debugging only, print the input to verify that the input is accepted correctly, something like
printf("intInput = %d\n", intInput);
The first thing you need when you are inputting intInput you should use:
scanf("%d", &intInput);
Because scanf() need as an argument of a pointer to your variable. You are doing this by just putting the & sign before your int.
In addition I think that you should double check your algorithm, because you are summing up some numbers more than once. :)
before I ask my question I would like to point out that I did look for the answers already, and I didn't find what I was looking for.
Please bear in mind that I am a beginner in terms of programming, so please don't assume that I know everything there is to know.
Right, to the question.
My question is : How do I add together numbers that are created by random number generator ? The difficulty that I have is the fact that the number of randomly generated numbers could be different every time the program is ran. To make it clearer, the amount of randomly generated numbers is dependent on the input from user, eg if the input is 9, the program will generate 9 random numbers. This makes it difficult for me to come up with the idea of how to add the random numbers together and display them.
Here is the source code from my program. I think it is important to mention that the random numbers change every time I run the program, which is how I want them to be ( I used srand() with time, and rand() ). Also, the problem that I have currently is that the program doubles the last randomly generated number instead of adding them all together.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
int turn_total;
time_t t;
int sum;
srand((unsigned) time(&t)); // the seed for the random number generator based on the current time
for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum = roll+roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}
printf("The Total Turn Score is : %d", sum);
}
Any help, ideas or clues would be greatly appreciated.
Yo need to initialize sum first also you are not adding properly.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
time_t t;
int sum = 0;
srand((unsigned) time(&t)); // the seed for the random number generator based on the current time
for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum += roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}
printf("The Total Turn Score is : %d", sum);
}
Use
srand( ( unsigned int )time( NULL ) );
and initialize variable sum. For example
long long int sum = 0;
//...
sum += roll;
//...
printf( "The Total Turn Score is : %lld", sum );
Your program is doubling the number that was generated because that's what you tell it to do in this line:
sum = roll+roll;
Instead, you need to add the current roll to the current value of sum:
sum = sum + roll;
And you need to initialize sum to 0 so that you start by adding just the first roll.
Think about it like rolling a dice multiple times and writing down what it was each time. You roll it once and get a 3, so you write down 3. You roll it again and get a 6, so you add 6 to the previous roll to get 9. You roll again and get 2, so you add 2 to 9 and get 11, and so on. The variable sum is where you write down the new number after every roll, but you're adding to what you wrote down before.
The way you had it before, you were completely disregarding the previous rolls. rolls in the loop only refers to the latest roll that you performed, and since the loop ends at some point, sum will be left as the sum of the last value of roll. This is why you were getting double the last number.
replace
sum = roll+roll
with
sum = roll+sum;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C, how do I get a specific range of numbers from rand()?
Generate a random number within range?
I'm stuck on how to use the rand() function and include a range for that random number. I need a random number between 67.00 and 99.99 only to be printed.
This is what I have tried, but failed with...
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x = rand();
if(x>=67.00)
if(x<=99.99)
printf("%d\n",x);
else
printf("not in range");
}
Instead of checking if the result is in the range, you can force the result to be in the range that you want:
int HIGH = 100;
int LOW = 67;
int rnd = LOW + (rand() % (HIGH-LOW));
The value of rnd is in the range between LOW and HIGH-1, inclusive.
If you do not want to force the number into range, change your condition to
if(x>=67.00 && x<=99.99)
Currently, the else belongs to the inner if, so the second printf does not happen when the number is less than 67.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate a random number from within a range - C
How would you generate a random number between 1 and N-1 where N is a number the user punches in?
So far, my code is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number = 0; //number variable
printf("This program will ask you for a number, an integer, and will print out a random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user.
//gets the input
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &number); //gets the input and stores it into variable number
return (0);
}
Try something like this:-
unsigned int
randomr(unsigned int min, unsigned int max)
{
double x= (double)rand()/RAND_MAX;
return (max - min +1)*x+ min;
}
Check out this link:- http://c-faq.com/lib/randrange.html
Here is the link to the referece for random.
http://www.cplusplus.com/reference/cstdlib/rand/
you can use
num= rand() % n + 1;
Depending on how "random" you want your numbers to be, you can use rand() function from the standard libc. This function will generate numbers between 0 and RAND_MAX. You can then get the result in the good range by using a modulo operation.
Note that this generator (a LCG) is neither suitable for cryptographic applications nor scientific applications.
If you want more suitable generators, have a look at generators such as Mersenne Twister (still not cryptosecure though).
You need to look at rand. Bit of maths and you have a solution.