I need to generate random non repeating number array in C++, in this part of code I generate random numbers using, srand function, but some of the numbers are repeating. The main task is to generate random numbers for lottery ticket, so I need to generate numbers until golden number which is marked as int golden.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
int golden = 31;
int i = 0;
int array[35];
srand((unsigned)time(0));
while(i != golden){
array[i] = (rand()%75)+1;
cout << array[i] << endl;
i++;
}
}
One strategy is to populate an array with numbers from 1 to 75, and then use std::random_shuffle() on it. You can then read the numbers from the array until you hit the golden number.
I had a similar task and used two functions to solve the problem of repeating numbers.
#include <iostream>
#include <ctime>
using namespace std;
void generateRandom(int array[], int length);
bool findVal(int array[], int size, int value);
int main() {
int arraySize = 10;
int array[arraySize];
generateRandom(array, arraySize);
for (auto i : array) {
cout << i << " ";
}
return 0;
}
void generateRandom(int array[], int length) {
srand((int) time(nullptr));
int temp;
for (int i = 0; i < length; ++i) {
temp = rand() % 20 + 1;
if (findVal(array, i, temp)) {
i--;
continue;
} else {
array[i] = temp;
}
}
}
bool findVal(int *array, int size, int value) {
for (int i = 0; i < size; ++i) {
if (array[i] == value) {
return true;
}
}
return false;
}
Within the generateRandom function, you can switch the 20 and 1 used in the for loop with your preferred upper and lower limits respectively.
Related
I have a bit of a problem with this. I've tried to create a function to return a random number and pass it to the array, but for some reason, all the numbers generated are "0".
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int generLosNum(int);
int main()
{
srand(time(NULL));
int LosNum;
const int rozmiar = 10;
int tablica[rozmiar];
for(int i=0; i<rozmiar; i++)
{
tablica[i] = generLosNum(LosNum);
cout << tablica[i] <<" ";
}
return 0;
}
int generLosNum(int LosNum)
{
int LosowyNum;
LosowyNum = (rand() % 10);
return (LosNum);
}
So the return for your int generLosNum(int LosNum) was printing 0 because you had it returning LosNum which was initialized equaling to zero. I changed your code so it works and will print out the 10 random numbers.
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int generLosNum();
int main()
{
srand(time(NULL));
int LosNum = 0;
const int rozmiar = 10;
int tablica[rozmiar];
for (int i = 0; i < rozmiar; i++)
{
tablica[i] = generLosNum();
cout << tablica[i] << " ";
}
return 0;
}
int generLosNum()
{
int LosowyNum;
LosowyNum = (rand() % 10);
return LosowyNum;
}
Change your method generLosNum to the following and the method signature to int generLosNum() and it should work.
int generLosNum()
{
return (rand() % 10);
}
Reason: As others also mentioned in the comments, you were just returning the number that you passed in as parameter and also the logic for this method doesn't even need a parameter.
I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine.
this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
int sumOfElements(int[],int);
int number;
int sum=0;
int main()
{
int a[10];
getElements(a,5);
sumOfElements(a,5);
cout<<"The sum is "<<sumOfElements(a,5)<<endl;
return 0;
}
//Getting array's elements
void getElements(int numbers[],int size_)
{
for (int i=0; i<size_; i++)
{
cout<<"numbers["<<i<<"]: ";
cin>>number;
numbers[i]=number;
}
cout<<'\n';
}
//Calculation the sum of array's elements
int sumOfElements(int numbers[],int size_)
{
for(int i=0;i<size_;i++)
{
sum+=numbers[i];
}
cout<<sum<<endl;
return sum;
}
any idea? thank you in advance!
You defined int sum globally and were calling sumOfElementstwice, so sum contained twice what you expected.
Here is a modified version of your code that does what you want:
#include <iostream>
using namespace std;
void getElements(int[], int);
int sumOfElements(int[], int);
int main() {
int numbers[5];
getElements(numbers, 5);
cout << sumOfElements(numbers, 5);
return 0;
}
void getElements(int numbers[], int size) {
for (int i = 0; i < size; i++) {
cin >> numbers[i];
}
}
int sumOfElements(int numbers[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
return sum;
}
Here is a modified and simpler version of your program:
#include <array>
#include <iostream>
#include <numeric>
using namespace std;
int main(){
const int num_elements_to_sum = 5;
array<int, num_elements_to_sum> elements;
for(int i=0; i<num_elements_to_sum; ++i){
cin>>elements[i];
}
int sum = accumulate(elements.begin(), elements.end(), 0);
cout<<"Sum: "<<sum<<endl;
return 0;
}
C++ has a dedicated fixed size array container, use this instead of C-style arrays. This then allows to use standard library algorithms instead of your own implementation (e.g. accumulate).
My C++ program to calculate all the prime numbers using sieve of Eratosthenes method stops after 200,000. But I need to calculate the primes up to 2 million. Help would be appreciated if someone could tell me where I went wrong with my code.
#include <iostream>
#include<math.h>
using namespace std;
void isprime(long long int prime[],long int n)
{
for(long long int i=0;i<=n;i++)
{
prime[i]=1;
}
prime[0]=prime[1]=0;
for(long long int i=2;i<=sqrt(n);i++)
{
if(prime[i]==1)
{
for(long long int j=2;i*j<=n;j++)
prime[i*j]=0;
}
}
for(long long int i=0;i<=n;i++)
{
if(prime[i]==1)
cout<<i<<endl;
}
}
int main()
{
long long int n;
cout<<"enter number";
cin>>n;
long long int prime[n+1];
isprime(prime,n);
return 0;
}
Since each sieve element contains only a 0 or 1, there is no need to use a long long int to store each one. std::vector<bool> potentially uses 1 bit per element and thus is optimal for memory efficiency.
Here is your code with a very few modifications to use a std::vector<bool>. Since some bit manipulation is required to get and set individual elements, this version may be slower than code which uses one byte or int per sieve element. You can benchmark various versions and decide the right trade-off for your needs.
#include <cmath>
#include <cstddef>
#include <exception>
#include <iostream>
#include <string>
#include <vector>
// returns the number of primes <= n
long isprime(long n) {
std::vector<bool> prime(n + 1);
for (long i = 0; i <= n; i++) {
prime[i] = 1;
}
prime[0] = prime[1] = 0;
long upper_bound = std::sqrt(n);
for (long i = 2; i <= upper_bound; i++) {
if (prime[i] == 1) {
for (long j = 2; i * j <= n; j++)
prime[i * j] = 0;
}
}
long num_primes = 0;
for (long i = 0; i <= n; i++) {
if (prime[i] == 1) {
++num_primes;
// std::cout << i << std::endl;
}
}
return num_primes;
}
int main() {
std::cout << "Enter the sieve size: ";
std::string line;
std::getline(std::cin, line);
std::cout << std::endl;
long len = std::stol(line);
long num_primes = isprime(len);
std::cout << "There are " << num_primes << " primes <= " << len << std::endl;
return 0;
}
Please read the task first: http://codeabbey.com/index/task_view/neumanns-random-generator
I have to keep track of the number of iterations, but I get very strange results. In the example after the task we have the numbers 0001 and 4100 and they should come to loop after 2 and 4 iterations. But my results are 1, 4 or if I change the place of the counter 2 or 5 but never 2 and 4. Here is my code:
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
int setvalue = 1; // use to exit the loop if setvalue == 0;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
while(setvalue == 1)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
setvalue = 0;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}
Going in and out of a string the way you have is really very ugly and extremely expensive computationally.
Use
(value % 1000000) / 100;
instead to extract the middle four digits. This works by (1) taking the modulus to remove the leading two digits then (2) removing the last two with integer division.
As it's so much simpler, I suspect that will fix your bugs too.
Here is the correct code, thank you for all your help.
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
results_vec.push_back(value);
while(true)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
break;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}
I'm trying some exercise to learn the use of pointers with arrays and functions.
So I tried to code a "strange way" to find out primes within a certain range.
The problem is that the output always add the return value of the function with the algorithm for the primes. if I omit it, it shows is '32767', if I write return *pt, it adds the last number of the range, even if it's not a prime!
Just tried it with number 6: it's not a prime but it pops up!
#include <iostream>
int show_primes(const int * begin, const int * end);
int main()
{
using namespace std;
int i = 0;
int End_Array = 0;
cout << "Write the last number in your range (it always start from number 2)";
cin >> End_Array;
i=End_Array;
int cookies[i];
for(i=-1; i<End_Array; i++)
cookies[i] = i+1;
cout << show_primes(cookies, cookies + End_Array-1);
}
int show_primes (const int * begin, const int * end)
{
using namespace std;
const int * pt;
int z = 0;
for (pt = begin; pt < end; pt++, z=0)
{
for (int n=2; n<=*pt; n++)
if ( *pt%n == 0 )
++z;
if (z==1)
cout << *pt <<endl;
}
return *pt ;
}
Your loop is accessing a value at negative index.
cookies[i] = i+1; //For first iteration, value of i is -1
So for(i=-1; i<End_Array; i++) should be changed to for(i=0; i<End_Array; i++)
Also, you do not need to return from the function as you are printing the values within itself
Although you are using pointers for your learning, a more simpler implementation would be:
#include <iostream>
using namespace std;
void show_primes(int num)
{
bool flag = false;
for (int pt = 2; pt < num; pt++)
{
if ( num%pt == 0 )
{
flag = true;
break;
}
}
if(!flag)
{
cout<<num<<' ';
}
}
int main()
{
int End_Array = 0;
cout << "Write the last number in your range(>2)";
cin >> End_Array;
for(int i=2; i<End_Array; i++)
{
show_primes(i);
}
}
P.S.: Can someone please highlight that is it a bad practice to include std namespace in every functional block as OP has done.(I think it is)
for(i=0; i<End_Array; i++) // Start from zero
cookies[i] = i; //Use i
// Don't use cout
show_primes(cookies, cookies + End_Array-1);