Generating random integers [duplicate] - c++

This question already has answers here:
How to generate a random integer number from within a range
(11 answers)
Closed 3 years ago.
I am trying to write a code that can generate 3 random integers from 1 to 100. I thought of using array to store the integers, but I have no idea how I am going to access those 3 random integers.
I want my code to return something like: 5 92 66. Is there any better way to go about it?
#include <iostream>
using namespace std;
int main()
{
int nums[100];
for(int index = 1; index < 101; index++)
{
nums[index] = 1;
}
return 0;
}
I expect output to be something like: 88 17 3.

Create a set S.
Repeat while number of elements in S < 3
Create random number N with 1 <= N <= 100
If number N not in S
Insert N into S
Now S contains 3 different random numbers. You can create random numbers with std::uniform_int_distribution

Related

Generate random values with fixed sum in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I saw tons of answers to this question on the web but, can you believe me? I still don't get the solution of this problem. I have an array of values. The size of this array is "n". I have also the defined value "sum". What I want is to generate "n" random values in such a way that their sum is equals to "sum", preferably uniformly distributed, otherwise (for example) having the first random number equals to "sum" and the rest equals to zero is not that nice. I need two algorithms which accomplish this task. One with positive Integers and one with positive Floats. Thanks a lot in advance!
First generate n random variables. Then sum them up: randomSum. Calculate coefficient sum/randomSum. Then multiply all random variables with that coefficient.
Integers would pose a problem... Rounding too (probably)
You can generate n numbers with a normal distribution then normalize them to your sum
You can generate n values defined by this : ((Sum - sumOfGeneratedValues) / n - (numberOfGeneatedValue)) -+X (With X maximal deviance)
Example :
SUM = 100 N = 5
+- 10
Rand between 100 - 0 / 5 - 0 --> 20 +-10 (So bewteen 10 and 30)
Value1 = 17;
Rand between 100 - 17 / 5 - 1 ---> 21 +-10 (So between 11 and 31)
... etc
Deviance would make your random uniform :)
you have a loop, where the number of iterations is equal to the number of random numbers you want minus 1. for the first iteration, you find a random number between 0 and the sum. you then subtract that random number from the sum, and on the next iteration you get another random number and subtract that from the sub sum minus the last iteration
its probably more easy in psuedocode
int sum = 10;
int n = 5; // 5 random numbers summed to equal sum
int subSum = sum;
int[] randomNumbers = new int[n];
for(int i = 0; i < n - 2; i++)
{
randomNumbers[i] = rand(0, subSum); // get random number between 0 and subSum
subSum -= randomNumbers[i];
}
randomNumbers[n - 1] = subSum; // leftovers go to the last random number
My C++ is very (very very) rusty. So let's assume you already know how to get a random number between x and y with the function random(x,y). Then here is some psuedocode in some other c derived language:
int n = ....; // your input
int sum = ....; // your input
int[] answer = new int[n];
int tmpsum = 0;
for (int i=0; i < n; i++) {
int exactpart = sum/n;
int random = (exactpart/2) + random(0,exactpart);
int[i] = tmpsum + random > sum ? sum - tmpsum : random;
tmpsum += int[i];
}
int[n-1] += sum - tmpsum;

Use entire list in pseudo-random number generation [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pseudo-Random Traversal of a Set
I'm trying to write an algorithm that will put the songs of a playlist into a random order, so if there are 10 songs, I need the random number generator to hit every value from 0-9 before repeating. Using the algorithm: x_current = (a * x_prev + c) mod m, is there any way to achieve this with certain values for a c and m?
Try using std::random_shuffle
vector<int> playOrder;
// set some values:
for (int i=1; i<10; ++i) playOrder.push_back(i); // 1 2 3 4 5 6 7 8 9
// Don't forget to seed, or mix will be the same each run
srand(time(NULL));
// using built-in random generator:
random_shuffle ( playOrder.begin(), playOrder.end() );
// An example of how you might use the new random array.
for(int i=0; i<playOrder.size(); i++)
player.PlayTrack(playOrder[i]);
Take a look at this question. Also, for small playlists, simply shuffling an array with the song numbers will be sufficient.

possible combinations and loops

i have to make all possible combinations of a 2d array..for e.g. if i have a array of 4x3 ...i m using 4 loops,all runs up to 3.. to get all combinations...
for.e.g if i have a 4x3 array as given below..
1 2 3
4 5 6
7 8 9
10 11 12
i will have to make combinations like
1,4,7,10
1,4,7,11
1,4,7,12
1,4,8,10
1,4,8,11
1,4,8,12
1,4,9,10
1,4,9,11
1,4,9,12
1,5,8,10
1,5,8,11
1,5,8,12
...........
and so on....
in short all such combinations...the max number of possible combinations in this case will be 3 power 4....and if i have a array of nxm then maximum combinations will be m power n....can any one help creating it....i want help to solve it in generic .....i think recursive function shall be used...as i don't know the no of loop...it will be known during run time...
void buildArray(vector <int> build, vector< vector <int> > &arrays)
{
int position = build.size();
if (position == arrays.size()) { /* current build is one of the solutions*/}
else {
for (int i = 0; i < arrays[position].size(); i++)
{
build.push_back(arrays[position][i]);
buildArray(build, arrays);
build.pop_back();
}
}
}

How can I find the number of ways a number can be expressed as a sum of primes? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generating the partitions of a number
Prime number sum
The number 7 can be expressed in 5 ways as a sum of primes:
2 + 2 + 3
2 + 3 + 2
2 + 5
3 + 2 + 2
5 + 2
Make a program that calculates, in how many ways number n can be
expressed as a sum of primes. You can assume that n is a number
between 0-100. Your program should print the answer in less than a
second
Example 1:
Give number: 7 Result: 5
Example 2:
Give number: 20 Result: 732
Example 3:
Give number: 80 Result: 10343662267187
I've been at this problem for hours. I can't figure out how to get n from (n-1).
Here are the sums from the first 30 numbers by a tree search
0 0 0 1 2 2 5 6 10 16 19 35 45 72 105 152 231 332 500 732 1081 1604 2351 3493 5136 7595 11212 16534 24441
I thought I had something with finding the biggest chain 7 = 5+2 and somehow using the knowledge that five can be written as 5, 3+2, 2+3, but somehow I need to account for the duplicate 2+3+2 replacement.
Look up dynamic programming, specifically Wikipedia's page and the examples there for the fibonacci sequence, and think about how you might be able to adapt that to your problem here.
Okay so this is a complicated problem. you are asking how to write code for the Partition Function; I suggest that you read up on the partition function itself first. Next you should look at algorithms to calculate partitions. It is a complex subject here is a starting point ... Partition problem is [NP complete] --- This question has already been asked and answered here and that may also help you start with algorithms.
There're several options. Since you know the number is between 0-100, there is the obvious: cheat, simply make an array and fill in the numbers.
The other way would be a loop. You'd need all the primes under 100, because a number which is smaller than 100 can't be expressed using the sum of a prime which is larger than 100. Eg. 99 can't be expressed as the sum of 2 and any prime larger than 100.
What you also know is: the maximum length of the sum for even numbers is the number divided by 2. Since 2 is the smallest prime. For odd numbers the maximum length is (number - 1) / 2.
Eg.
8 = 2 + 2 + 2 + 2, thus length of the sum is 4
9 = 2 + 2 + 2 + 3, thus length of the sum is 4
If you want performance you could cheat in another way by using GPGPU, which would significantly increase performance.
Then they're is the shuffling method. If you know 7 = 2 + 2 + 3, you know 7 = 2 + 3 + 2. To do this you'd need a method of calculating the different possibilities of shuffling. You could store the combinations of possibilities or keep them in mind while writing your loop.
Here is a relative brute force method (in Java):
int[] primes = new int[]{/* fill with primes < 100 */};
int number = 7; //Normally determined by user
int maxLength = (number % 2 == 0) ? number / 2 : (number - 1) / 2; //If even number maxLength = number / 2, if odd, maxLength = (number - 1) / 2
int possibilities = 0;
for (int i = 1; i <= maxLength; i++){
int[][] numbers = new int[i][Math.pow(primes.length, i)]; //Create an array which will hold all combinations for this length
for (int j = 0; j < Math.pow(primes.length, i); j++){ //Loop through all the possibilities
int value = 0; //Value for calculating the numbers making up the sum
for (int k = 0; k < i; k++){
numbers[k][j] = primes[(j - value) % (Math.pow(primes.length, k))]; //Setting the numbers making up the sum
value += numbers[k][j]; //Increasing the value
}
}
for (int x = 0; x < primes.length; x++){
int sum = 0;
for (int y = 0; y < i; y++){
sum += numbers[y];
if (sum > number) break; //The sum is greater than what we're trying to reach, break we've gone too far
}
if (sum == number) possibilities++;
}
}
I understand this is complicated. I will try to use an analogy. Think of it as a combination lock. You know the maximum number of wheels, which you have to try, hence the "i" loop. Next you go through each possibility ("j" loop) then you set the individual numbers ("k" loop). The code in the "k" loop is used to go from the current possibility (value of j) to the actual numbers. After you entered all combinations for this amount of wheels, you calculate if any were correct and if so, you increase the number of possibilities.
I apologize in advance if I made any errors in the code.

C++ How I can get random value from 1 to 12? [duplicate]

This question already has answers here:
Generating a random integer from a range
(14 answers)
Closed 6 years ago.
How I can get in C++ random value from 1 to 12?
So I will have 3, or 6, or 11?
Use the following formula:
M + rand() / (RAND_MAX / (N - M + 1) + 1), M = 1, N = 12
and read up on this FAQ.
Edit: Most answers on this question do not take into account the fact that poor PRN generators (typically offered with the library function rand()) are not very random in the low order bits. Hence:
rand() % 12 + 1
is not good enough.
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <time.h>
// initialize random seed
srand( time(NULL) );
// generate random number
int randomNumber = rand() % 12 + 1;
// output, as you seem to wan a '0'
cout << setfill ('0') << setw (2) << randomNumber;
to adress dirkgently's issue maybe something like that would be better?
// generate random number
int randomNumber = rand()>>4; // get rid of the first 4 bits
// get the value
randomNumer = randomNumer % 12 + 1;
edit after mre and dirkgently's comments
Is there some significance to the leading zero in this case? Do you intend for it to be octal, so the 12 is really 10 (in base 10)?
Getting a random number within a specified range is fairly straightforward:
int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
*/
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
(The while loop is to prevent skewed results -- some outputs happening more often than others). Skewed results are almost inevitable when/if you use division (or its remainder) directly.
If you want to print it out so even one-digit numbers show two digits (i.e. a leading 0), you can do something like:
std::cout << std::setw(2) << std::setprecision(2) << std::setfill('0') << number;
Edit: As to why this works, and why a while loop (or something similar) is needed, consider a really limited version of a generator that only produces numbers from, say, 0 to 9. Assume further that we want numbers in the range 0 to 2. We can basically arrange the numbers in a table:
0 1 2
3 4 5
6 7 8
9
Depending on our preference we could arrange the numbers in columns instead:
0 3 6
1 4 7
2 5 8
9
Either way, however, we end up with the one of the columns having one more number than any of the others. 10 divided by 3 will always have a remainder of 1, so no matter how we divide the numbers up, we're always going to have a remainder that makes one of the outputs more common than the others.
The basic idea of the code above is pretty simple: after getting a number and figuring where in a "table" like one above that number would land, it checks whether the number we've got is the "odd" one. If it is, another iteration of the loop is executed to obtain another number.
There are other ways this could be done. For example, you could start by computing the largest multiple of the range size that's still within the range of the random number generator, and repeatedly generate numbers until you get one smaller than that, then divide the number you receive to get it to the right range. In theory this could even be marginally more efficient (it avoids dividing the random number to get it into the right range until it gets a random number that it's going to use). In reality, the vast majority of the time, the loop will only execute one iteration anyway, so it makes very little difference what we execute inside or outside the loop.
You can do this, for example:
#include <cstdlib>
#include <cstdio>
#include <time.h>
int main(int argc, char **argv)
{
srand(time(0));
printf("Random number between 1 and 12: %d", (rand() % 12) + 1);
}
The srand function will seed the random number generator with the current time (in seconds) - that's the way it's usually done, but there are also more secure solutions.
rand() % 12 will give you a number between 0 and 11 (% is the modulus operator), so we add 1 here to get to your desired range of 1 to 12.
In order to print 01 02 03 and so on instead of 1 2 3, you can format the output:
printf("Random number between 01 and 12: %02d", (rand() % 12) + 1);
(rand() % 12 + 1).ToString("D2")