I am new to c++. I am trying to generate 4 random unique numbers from 0 to 9. Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> vect;
int randNums = 4;
int countSameNums = 0;
int randNumber;
srand(time(0)); // Initialize random number generator by setting the seed
// generate 4 random unique integers and insert them all into a vector
while (true){
randNumber = rand()%10;
for (int i = 0; i < vect.size(); i++){
if (randNumber == vect[i]){
countSameNums += 1;
}
}
if (countSameNums == 0){
vect.push_back(randNumber);
countSameNums = 0;
}
if (vect.size() == randNums)
break;
}
for (int el : vect){ // print out the content of the vector
cout << el <<endl;
}
}
I can compile the code without problems. However when I run it, sometimes it prints out the correct result, i.e. the 4 unique integers, but other times the program just hangs. I also notice that If I comment the line srand(time(0)) (my random seed) it prints 4 unique numbers every time, i.e. the program never hangs. The problem of course is that by commenting srand(time(0)) I get always the same sequence of unique numbers and I want a different sequence every run. Any idea on why this isn't working? thanks
It can take long before you get 4 different numbers. There is a simpler and more efficient way to get 4 unique numbers. Take a vector containung number from 0 till 9, shuffle it, take the first 4.
Anyhow the issue in your code is that once countSameNum is not 0 you will never reset it to 0. You only reset it when it is 0 already. Change it like this:
while (true){
randNumber = rand()%10;
countSameNums = 0;
for (int i = 0; i < vect.size(); i++){
if (randNumber == vect[i]){
countSameNums += 1;
}
}
if (countSameNums == 0){
vect.push_back(randNumber);
}
if (vect.size() == randNums)
break;
}
As this is rather error-prone you should rather use std::find to see if the number is already in the vector:
if (std::find(vect.begin(),vect.end(),randNumber) == vect.end()) vect.push_back(randNumber);
And as mentioned before, there are better ways to get unique random numbers.
I need to find a way to fill an array with random numbers without having duplicates,so i wrote this code and it works.My question is,is this code efficient and will it really have no duplicates? Thanks in advance!
#include <iostream>
#include <time.h>
#include <stdlib.h>
int main(void) {
srand(time(NULL));
std::size_t array_size=100;
int array[array_size];
for(int i=0;i<array_size;i++) {
array[i]=rand()%105+1;
for(int k=0;k<array_size;k++) { // Checks if there is a duplicate in the array //
if(i!=k) { // Don't check for the same array position //
if(array[i]==array[k]) { // If a duplicate is found,repeat the check process//
array[i]=rand()%105+1;
k=-1; // -1 so the for loop starts from zero //
}
}
}
}
return 0;
}
That approach works fine when the number of desired values is much less than the number of possible values. Most of time it won't produce a duplicate value, so it just keeps the one it produced. But when there isn't a lot of slack there are lots of duplicates; when this code gets close to the end it's generating a value between 1 and 106 when there are only six or seven or so acceptable values. So it ends up spinning its wheels.
Instead of doing all that looping, create an array that holds all of the possible values, randomly shuffle it, and throw out the extra ones:
int array[105];
for (int i = 0; i < 105; ++i)
array[i] = i + 1;
std::mt19937_64 mt;
std::shuffle(std::begin(array), std::end(array), mt);
for (int i = 0; i < 100; ++i)
std::cout << array[i] << '\n';
I am writing a code that is supposed to act as a lottery. The lottery numbers available are 1-50, and there are 10 of them. The user is supposed to input one number and the program returns if the user's number matches one of the 10 random lottery numbers. I have gotten all of these parts down, but there is one problem; all 10 of the lottery numbers must be unique. I have gotten 10 unique numbers 1-50, but they weren't very random. The code I have written up to this point seems correct to me, except I know there is something missing (along with the fact that I can clean my code up a lot, but I'm focusing on the objective right now). Right now if I run the program it will return ten zeroes. I need each element in the lottery array to be a unique number from 1-50, and produce different sets of numbers each time i run the program. Any help would be appreciated.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using std::cout; using std::cin; using std::endl;
void printOut(int[]);
void draw(int[]);
bool check();
int fillFunc[10];
int main()
{
const int arraySize = 10;
int win[arraySize] = {};
srand((unsigned)time(NULL));
draw(win);
cout << "Your lottery numbers are: ";
printOut(win);
}
void draw(int fillFunc[])
{
int i;
for (i = 0; i < 10; i++)
{
if (check() == true)
continue;
fillFunc[i] = 1 + rand() % 50;
}
}
void printOut(int fillFunc[])
{
for (int i = 0; i < 10; i++)
{
cout << " " << fillFunc[i];
}
cout << "\n";
}
bool check()
{
for (int i = 0; i < 10; ++i)
{
if (fillFunc[i] == i)
return true;
}
return false;
}
(also don't ask me why the array has the name "win", this is what my prof wants me to call it)
Because check() always return true. At the start, the array is filled with zeroes so check returns true as win[0]==0 and that remains true forever as nothing changes that value. So in draw you always branch to continue and never modify anything.
To solve the problem one way could be to shuffle the sequence of 1-50 and extract the first 10 values of the shuffled array. You can use the very simple Fisher-Yates algorithm.
To answer your question that you updated in the comments you need to consider a shuffling algorithm.
I will give you an idea of how to do this that is O(n) so you don't have to "loop" thru your current list of numbers and keep checking to see if the new number was already picked...
your lottery max number is 50 so make an array of size 50 that is as follows:
lotteryNumber[0]=1
lotteryNumber[1]=2
...
lotteryNumber[49]=50
to pick a number to put into your "selected" numbers array...
indexToLotteryNumbers = rand() % 50 - numbersPickedSoFar;
randomLotteryNumber[i++] = lotteryNumber[ indexToLotteryNumbers ];
// this is the key "trick"
swap(&lotteryNumber[ indexToLotteryNumbers ], &lotteryNumber[49-numbersPickedSoFar]);
numbersPickedSoFar++;
Theory
The random numbers are the indexes and not the actual values
By swapping the number you picked with the outer element you don't care if your random number generator picks the same index because it will be different the next time.
look at a small example...say you have 1 2 3 4
rand() generates "2"
so your first # is 2 (assume 1-based indexing here) now you swap the (4th) element for the (2nd) element now you have 1 4 3 |2
(here |2 means you can't pick that number again because it's outside the
random # generator range) but you reduce the random # generation from
1-4 to 1 thru 3
rand() generates "1" so your number is "1" and you swap that with the "outer" unpicked number 3 4 |1 2
rand() generates
"2" again! your lottery number is 4 this time... and so on.
I hope this makes sense.
This is what I would do, given your constraints. Rather than check if a number is unique while you are filling the array, just pass the array into the function that chooses the number so it can return a unique value.
I also removed the redundant global array. It could be a source of bugs if you forgot to pass the local array you were working with to any of the functions.
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int getUniqueNumber(int fillFunc[])
{
while(true)
{
//pick number
int val = 1 + rand() % 50;
//assume it's unique
bool unique = true;
for (int i = 0; i < 10; ++i)
{
//if another number matches, it isn't unique, choose again
if (fillFunc[i] == val)
{
unique = false;
break;
}
}
//if it is unique, return it.
if (unique)
{
return val;
}
}
//never reached, but avoids an all control paths must return a value warning.
return -1;
}
void draw(int fillFunc[])
{
for (int i = 0; i < 10; i++)
{
fillFunc[i] = getUniqueNumber(fillFunc);
}
}
void printOut(int fillFunc[])
{
for (int i = 0; i < 10; i++)
{
cout << " " << fillFunc[i];
}
cout << "\n";
}
int main()
{
srand((unsigned)time(NULL));
const int arraySize = 10;
int win[arraySize] = {};
draw(win);
cout << "Your lottery numbers are: ";
printOut(win);
return 0;
}
There are other, perhaps better, ways to select unique numbers in a range, but I went for simple to implement and explain. You can read about some other methods in these questions:
Unique random numbers in an integer array in the C programming language
Unique (non-repeating) random numbers in O(1)?
You only assign a value to fillFunc[i] when i is 10, which is an out of bounds access. Move the assignment to inside the loop.
You have other problems too. If you do continue, you just leave an entry in the array unset.
You should try adding a lot of output statements to your program so you can more easily understand what it's doing. If you prefer, use a debugger to step through it.
This question already has answers here:
Random array generation with no duplicates
(9 answers)
Closed 5 years ago.
I want to generate random numbers and save them in an array. that' all ! but here is the point, I want to avoid duplicating and not having a number two or more times in array.
my code :
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int k, temp;
cin >> k;
int sym[k];
srand(time(NULL));
for (int i = 0; i < k; i++)
{
temp = rand() % 25 + 97;
for(int j=0; j<i; j++)
{
while(temp == sym[j])
{
temp = rand() % 25 + 97; // 25 means a and 122 means z
}
}
sym[i] = temp;
}
for(int i=0; i<k; i++)
{
cout << sym[i] << endl;
}
return 0;
}
I still get duplicated results.
I will use std::unordered_set to avoid duplicated
Random generator doesn't mean unique generation, collisions can always happen especially when the number of generated values is high and the bounds or limits for the generation is small...
to avoid duplicated elements replace this array
int sym[k];
by a set which is a container that doesn't allow duplicate entries...
std::set<int>
after that, you need to replace the logic because looping k times does not mean having k elements in the set, so you need to do a while loop until the size of the set reaches the limit k
Edit:
if you need some unsorted generated values, the instead of using a set, consider implementing an unordered_set
I'm currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which required me to read in a number from a given txt file. This number would be N. Now I'm suppose to find the Nth prime number for N <= 10 000. After I find it, I'm suppose to print it out to another txt file. Now for most parts of the question I'm able to understand and devise a method to get N. The problem is that I'm using an array to save previously found prime numbers so as to use them to check against future numbers. Even when my array was size 100, as long as the input integer was roughly < 15, the program crashes.
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main() {
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime;
trial >> prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[100], b, c, e;
bool check;
b = 0;
switch (prime) {
case 1:
{
write << 2 << endl;
break;
}
case 2:
{
write << 3 << endl;
break;
}
case 3:
{
write << 5 << endl;
break;
}
case 4:
{
write << 7 << endl;
break;
}
default:
{
for (int a = 10; a <= 1000000; a++) {
check = false;
if (((a % 2) != 0) && ((a % 3) != 0) && ((a % 5) != 0) && ((a % 7) != 0)) // first filter
{
for (int d = 0; d <= b; d++) {
c = num[d];
if ((a % c) == 0) {
check = true; // second filter based on previous recorded primes in array
break;
}
}
if (!check) {
e = a;
if (b <= 100) {
num[b] = a;
}
b = b + 1;
}
}
if ((b) == (prime - 4)) {
write << e << endl;
break;
}
}
}
}
trial.close();
write.close();
return 0;
}
I did this entirely base on my dummies guide and myself so do forgive some code inefficiency and general newbie-ness of my algorithm.
Also for up to 15 it displays the prime numbers correctly.
Could anyone tell me how I should go about improving this current code? I'm thinking of using a txt file in place of the array. Is that possible? Any help is appreciated.
Since your question is about programming rather than math, I will try to keep my answer that way too.
The first glance of your code makes me wonder what on earth you are doing here... If you read the answers, you will realize that some of them didn't bother to understand your code, and some just dump your code to a debugger and see what's going on. Is it that we are that impatient? Or is it simply that your code is too difficult to understand for a relatively easy problem?
To improve your code, try ask yourself some questions:
What are a, b, c, etc? Wouldn't it better to give more meaningful names?
What exactly is your algorithm? Can you write down a clearly written paragraph in English about what you are doing (in an exact way)? Can you modify the paragraph into a series of steps that you can mentally carry out on any input and can be sure that it is correct?
Are all steps necessary? Can we combine or even eliminate some of them?
What are the steps that are easy to express in English but require, say, more than 10 lines in C/C++?
Does your list of steps have any structures? Loops? Big (probably repeated) chunks that can be put as a single step with sub-steps?
After you have going through the questions, you will probably have a clearly laid out pseudo-code that solves the problem, which is easy to explain and understand. After that you can implement your pseudo-code in C/C++, or, in fact, any general purpose language.
There are a two approaches to testing for primality you might want to consider:
The problem domain is small enough that just looping over the numbers until you find the Nth prime would probably be an acceptable solution and take less than a few milliseconds to complete. There are a number of simple optimizations you can make to this approach for example you only need to test to see if it's divisible by 2 once and then you only have to check against the odd numbers and you only have to check numbers less than or equal to the aquare root of the number being tested.
The Sieve of Eratosthenes is very effective and easy to implement and incredibly light on the math end of things.
As for why you code is crashing I suspect changing the line that reads
for( int d=0; d<=b; d++)
to
for( int d=0; d<b; d++)
will fix the problem because you are trying to read from a potentially uninitialized element of the array which probably contains garbage.
I haven't looked at your code, but your array must be large enough to contain all the values you will store in it. 100 certainly isn't going to be enough for most input for this problem.
E.g. this code..
int someArray[100];
someArray[150] = 10;
Writes to a location large than the array (150 > 100). This is known as a memory overwrite. Depending on what happened to be at that memory location your program may crash immediately, later, or never at all.
A good practice when using arrays is to assert in someway that the element you are writing to is within the bounds of the array. Or use an array-type class that performs this checking.
For your problem the easiest approach would be to use the STL vector class. While you must add elements (vector::push_back()) you can later access elements using the array operator []. Vector will also give you the best iterative performance.
Here's some sample code of adding the numbers 0-100 to a vector and then printing them. Note in the second loop we use the count of items stored in the vector.
#include <vector> // std::vector
...
const int MAX_ITEMS = 100;
std::vector<int> intVector;
intVector.reserve(MAX_ITEMS); // allocates all memory up-front
// add items
for (int i = 0; i < MAX_ITEMS; i++)
{
intVector.push_back(i); // this is how you add a value to a vector;
}
// print them
for (int i = 0; i < intVector.size(); i++)
{
int elem = intVector[i]; // this access the item at index 'i'
printf("element %d is %d\n", i, elem);
}
I'm trying to improve my functional programming at the moment so I just coded up the sieve quickly. I figure I'll post it here. If you're still learning, you might find it interesting, too.
#include <iostream>
#include <list>
#include <math.h>
#include <functional>
#include <algorithm>
using namespace std;
class is_multiple : public binary_function<int, int, bool>
{
public:
bool operator()(int value, int test) const
{
if(value == test) // do not remove the first value
return false;
else
return (value % test) == 0;
}
};
int main()
{
list<int> numbersToTest;
int input = 500;
// add all numbers to list
for(int x = 1; x < input; x++)
numbersToTest.push_back(x);
// starting at 2 go through the list and remove all multiples until you reach the squareroot
// of the last element in the list
for(list<int>::iterator itr = ++numbersToTest.begin(); *itr < sqrt((float) input); itr++)
{
int tmp = *itr;
numbersToTest.remove_if(bind2nd(is_multiple(), *itr));
itr = find(numbersToTest.begin(), numbersToTest.end(), tmp); //remove_if invalidates iterator
// so find it again. kind of ugly
}
// output primes
for(list<int>::iterator itr = numbersToTest.begin(); itr != --numbersToTest.end(); itr++)
cout << *itr << "\t";
system("PAUSE");
return 0;
}
Any advice on how to improve this would be welcome by the way.
Here is my code. When working on a big number, it's very slow!
It can calculate all prime numbers with in the number you input!
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
int m;
int n=0;
char ch;
fstream fp;
cout<<"What prime numbers do you want get within? ";
if((cin>>m)==0)
{
cout<<"Bad input! Please try again!\n";
return 1;
}
if(m<2)
{
cout<<"There are no prime numbers within "<<m<<endl;
return 0;
}
else if(m==2)
{
fp.open("prime.txt",ios::in|ios::out|ios::trunc);//create a file can be writen and read. If the file exist, it will be overwriten.
fp<<"There are only 1 prime number within 2.\n";
fp<<"2\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
else
{
int j;
int sq;
fp.open("prime.txt",ios::in|ios::out|ios::trunc);
fp<<"2\t\t";
n++;
for(int i=3;i<=m;i+=2)
{
sq=static_cast<int>(sqrt(i))+1;
fp.seekg(0,ios::beg);
fp>>j;
for(;j<sq;)
{
if(i%j==0)
{
break;
}
else
{
if((fp>>j)==NULL)
{
j=3;
}
}
}
if(j>=sq)
{
fp.seekg(0,ios::end);
fp<<i<<"\t\t";
n++;
if(n%4==0)
fp<<'\n';
}
}
fp.seekg(0,ios::end);
fp<<"\nThere are "<<n<<" prime number within "<<m<<".\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
}
For one, you'd have less code (which is always a good thing!) if you didn't have special cases for 3, 5 and 7.
Also, you can avoid the special case for 2 if you just set num[b] = 2 and only test for divisibility by things in your array.
It looks like as you go around the main for() loop, the value of b increases.
Then, this results in a crash because you access memory off the end of your array:
for (int d = 0; d <= b; d++) {
c = num[d];
I think you need to get the algorithm clearer in your head and then approach the code again.
Running your code through a debugger, I've found that it crashes with a floating point exception at "if ((a % c) == 0)". The reason for this is that you haven't initialized anything in num, so you're doing "a % 0".
From what I know, in C/C++ int is a 16bit type so you cannot fit 1 million in it (limit is 2^16=32k). Try and declare "a" as long
I think the C standard says that int is at least as large as short and at most as large as long.
In practice int is 4 bytes, so it can hold numbers between -2^31 and 2^31-1.
Since this is for pedagogical purposes, I would suggest implementing the Sieve of Eratosthenes.
This should also be of interest to you: http://en.wikipedia.org/wiki/Primality_test
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false; // Basically the idea for this for loop is to run checks against integers. This is the main for loop in this program. I re initialize check to false ( check is a bool declared above this. )
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++) // This for loop is used for checking the currentInt against previously found primes which are stored in the num array.
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;} // this is the check. I check the number against every stored value in the num array. If it's divisible by any of them, then bool check is set to true.
if ( currentInt == 2)
{ check = false; } // since i preset num[0] = 2 i make an exception for the number 2.
if (!check)
{
e=a;
if(currentPrime <= 100){
num[currentPrime]= currentInt;} // This if uses check to see if the currentInt is a prime.
currentPrime = currentPrime+1;} // increases the value of currentPrime ( previously b ) by one if !check.
if(currentPrime==prime)
{
write<<e<<endl;
break;} // if currentPrime == prime then write the currentInt into a txt file and break loop, ending the program.
Thanks for the advice polythinker =)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime, e;
trial>>prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[10000], currentPrime, c, primePrint;
bool check;
currentPrime=0;
num[currentPrime] = 2;
currentPrime=1;
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false;
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++)
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;}
}
if (!check)
{ e=currentInt;
if( currentInt!= 2 ) {
num[currentPrime]= currentInt;}
currentPrime = currentPrime+1;}
if(currentPrime==prime)
{
write<<e<<endl;
break;}
}
trial.close();
write.close();
return 0;
}
This is the finalized version base on my original code. It works perfectly and if you want to increase the range of prime numbers simply increase the array number. Thanks for the help =)
Since you will need larger prime number values for later questions, I suggest you follow dreeves advice, and do a sieve. It is a very useful arrow to have in your quiver.