Unique Random Number between 0 and 9 - c++

I am trying to generate a unique random number between 0 and 9. The same number cannot be generated twice and the function will be ran 9 time (until all the 9 numbers are used.) Here is the latest way I have been trying to do this:
int uniqueRandomInt(int x) {
std::vector<int> usedRandoms;
int random = x;
//Iterate vector
for (unsigned int i = 0; i < usedRandoms.size(); i++) {
//if passed value is in vector
if (random = usedRandoms[i]) {
uniqueRandomInt(random);
}
else {
//If unique rand found put into vector
usedRandoms.push_back(random);
return random;
}
}
}
Calling it in another function using:
cout << uniqueRandomInt(-1) << endl;
Result I am getting is:
17801152 (Changes every time the function is called)
Am I going about this totally wrong? I did try other ways but with no luck and this is where I'm currently at. Thanks in advance.

I prefer to use shuffle.
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
#include <cassert>
class T455_t
{
private:
// data
std::vector<int> m_iVec ;
public:
T455_t() {}
int exec()
{
std::vector<int> iVec;
gen10();
for (int i=0; i<10; ++i)
{
int nxtRandom = uniqueRandomInt();
std::cout << nxtRandom << std::endl;
}
return(0);
}
private: // methods
void gen10() // fills data attribute with 10 digits
{
for (int i=0; i<=9; ++i)
m_iVec.push_back(i);
std::random_device rd;
std::mt19937_64 gen(rd());
std::shuffle (m_iVec.begin(), m_iVec.end(), gen);
// m_iVec now contains 10 unique numbers,
// range 0..9, in random order
}
int uniqueRandomInt()
{
assert(m_iVec.size());
int retVal = m_iVec.back(); // gets last element in vector
m_iVec.pop_back(); // removes last element
return(retVal);
}
}; // class T455_t
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "");
std::ios::sync_with_stdio(false);
std::chrono::high_resolution_clock::time_point m_start_us =
std::chrono::high_resolution_clock::now();
int retVal = -1;
{
T455_t t455;
retVal = t455.exec();
}
std::chrono::microseconds chrono_duration_us =
std::chrono::duration_cast <std::chrono::microseconds>
(std::chrono::high_resolution_clock::now() - m_start_us);
std::cout << " FINI " << chrono_duration_us.count()
<< " us" << std::endl;
return(retVal);
}

Your function doesn't appear to return a value if usedRandoms.size() is zero, which it will be the first time you call the function
int uniqueRandomInt(int x) {
std::vector<int> usedRandoms; // vector.size() = 0
int random = x;
// for loop won't be entered
for (unsigned int i = 0; i < usedRandoms.size(); i++)
{
}
// function doesn't return a value
}
It's worth noting that it's undefined behaviour to declare a function to return a value, and then not return a value. That's why the random values you're getting.
From the C++ standard, 6.6.3 (emphasis mine):
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

vector<int> initVector(){
vector<int> ret;
ret.clear();
for(int i = 0 ; i < 10 ; ++i){
ret.push_back(i);
}
return ret;
}
int uniqueRendom(){
static vector<int> randomNumbers = initVector();
int randomSize = randomNumbers.size() - 1;
if(randomSize <= 0){
return -1;
}
double randomeNum = (double)rand() / INT_MAX;
int randomIndex = (int) (randomeNum * randomSize + 0.5) ;
int returnValue = randomNumbers[randomIndex];
randomNumbers.erase(randomNumbers.begin() + randomIndex);
return returnValue;
}
include limits.h for INT_MAX.

Related

How do I print the following array to show number 1 - 1000000

I want to initialize an array and fill it from 1-1000000. How do I then print the array?
#include<iostream>
using namespace std;
const int holder = 1000000;
int main()
{
int i = 0;
int nums[holder] = {0};
for( int i = 0; i < holder; i++)
{
nums[i] = i+1;
}
return 0;
}
How about something like this:
// First create a vector containing holder elements
std::vector<int> nums(holder);
// Then set each element to the number from 1 to holder, inclusive
std::iota(begin(nums), end(nums), 1);
Then to print it:
// Print each number in the vector, separated by newlines
for (auto num : nums)
{
std::cout << num << '\n';
}
Many parts of this answer should really be part of any decent beginners book. The only "new" thing would be the std::iota call.

Random Number Array/ minimum

#include <stdlib.h>
#include <cstdlib>
#include <ctime>
using namespace std;
int minimum(int zahlen[])
{
int minimum;
int o = 0;
bool prüf = false;
while (true)
{
for (int p = 0; p < 20; p++)
{
if (o == zahlen[p])
{
minimum = zahlen[p];
prüf = true;
}
}
if (prüf == true)
{
break;
}
o++;
}
return minimum;
}
void main()
{
srand(clock());
int array[20];
for (int i = 0; i < 20; i++)
{
array[i] = rand();
}
//Minimum
cout << "Die kleinste Zufallszahl die erstellt wurde ist die: " << minimum(array) << endl;
system("PAUSE");
}
Hi,
I have to create a 20 numbers long random array and check for the smallest number.
I know my code is probably not the best method to use for this problem but I am just always getting 371, 374, 202 or 208 as result. Never something else.
Is there a problem I don't see?
It most likely has to do with your use of clock(). According to this, clock() does not give you the current time. It gives you the time since your program started. So everytime you run this program, it takes roughly the same time for it to call clock(), meaning that the random seed is always about the same. To get the actual current world time, use std::chrono::system_clock::now() instead.
Also, an easier way of finding the minimum is this.
int minimum(int _randomNumbers[], int _arraySize)
{
int minimum = _randomNumbers[0]; // By default, let's assume the element 0 has the smallest number.
// Note that in this loop, i starts from 1, since there's no need to compare with element 0.
for (int i = 1; i < _arraySize; ++i)
{
if (_randomNumbers[i] < minimum)
{
minimum = _randomNumbers[i];
}
}
return minimum;
}

Vector inside vector (creating chromosomes)

I'm attempting to build a genetic algorithm that can take a certain amount of variables (say 4), and use these in a way so that you could have 2a + 3b + c*c + d = 16. I realise there are more efficient ways to calculate this, but I want to try and build a genetic algorithm to expand later.
I'm starting by trying to create "organisms" that can compete later. What I've done is this:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <random>
// Set population size
const int population_size = 10;
const int number_of_variables = 4;
int main()
{
// Generate random number
std::random_device rd;
std::mt19937 rng(rd()); // random-number engine (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(-10, 10);
// Set gene values.
std::vector<int>chromosome;
std::vector<int>variables;
for (int i = 0; i < number_of_variables; ++i)
{
double rand_num = uni(rng);
variables.push_back (rand_num);
std::cout << variables[i] << "\n";
}
return 0;
}
What happens is it will fill up the number_of_variables vector, and output these just because that makes it clear for me that it's actually doing what I intend for it to do. What I want it to do however is to fill up each "chromosome" with one variables vector, so that for example chromosome 0 would have the values {1, 5, -5, 9} etc.
The following code obviously isn't working, but this is what I'd like it to do:
for (int j = 0; j < population_size; ++j)
{
for (int i = 0; i < number_of_variables; ++i)
{
double rand_num = uni(rng);
variables.push_back(rand_num);
}
chromosome.push_back(variables[j]);
std::cout << chromosome[j] << "\n";
}
Meaning it'd fill up the variables randomly, then chromosome1 would take those 4 values that "variables" took, and repeat. What actually happens is that (I think) it only takes the first value from "variables" and copies that into "chromosome" rather than all 4.
If anyone could help it'd be very much appreciated, I realise this might be simply a rookie mistake that is laughably simply in the eyes of someone more experienced with vectors (which would probably be 99% of the people on this website, hah).
Anyway, thanks :)
#include <iostream>
#include <vector>
#include <random>
// Set population size
const int population_size = 10;
const int number_of_variables = 4;
int main()
{
// Generate random number
std::random_device rd;
std::mt19937 rng(rd()); // random-number engine (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(-10, 10);
// Set gene values.
std::vector< std::vector<int>>chromosome;
for( int kp = 0; kp < population_size; kp++ )
{
std::vector<int>variables;
for (int i = 0; i < number_of_variables; ++i)
{
double rand_num = uni(rng);
variables.push_back (rand_num);
}
chromosome.push_back( variables );
}
// display entire population
for( auto c : chromosome )
{
for( auto v : c )
{
std::cout << v << " ";
}
std::cout << "\n";
}
// display 4th member of population
for( auto v : chromosone[ 3 ] )
{
std::cout << v << " ";
}
std::cout << "\n";
return 0;
}
http://ideone.com/2jastJ
You can place a vector inside a vector with the syntax:
std::vector<std::vector<int>>
but you will need to make the outer vector large enough for num_variables.
#include <vector>
#include <cstdlib>
using Individual = std::vector<int>;
using Population = std::vector<Individual>;
// short for std::vector<std::vector<int>>;
const size_t number_of_variables = 8;
int main() {
Population population(10);
for (auto& individual : population) {
individual.resize(number_of_variables);
for (size_t j = 0; j < number_of_variables; ++j) {
individual[j] = j; // replace with random number
}
}
}
Live demo: http://ideone.com/pfufGt

How do I delete a particular element in an integer array given an if condition?

I'm trying to delete all elements of an array that match a particular case.
for example..
if(ar[i]==0)
delete all elements which are 0 in the array
print out the number of elements of the remaining array after deletion
what i tried:
if (ar[i]==0)
{
x++;
}
b=N-x;
cout<<b<<endl;
this works only if i want to delete a single element every time and i can't figure out how to delete in my required case.
Im assuming that i need to traverse the array and select All instances of the element found and delete All instances of occurrences.
Instead of incrementing the 'x' variable only once for one occurence, is it possible to increment it a certain number of times for a certain number of occurrences?
edit(someone requested that i paste all of my code):
int N;
cin>>N;
int ar[N];
int i=0;
while (i<N) {
cin>>ar[i];
i++;
}//array was created and we looped through the array, inputting each element.
int a=0;
int b=N;
cout<<b; //this is for the first case (no element is deleted)
int x=0;
i=0; //now we need to subtract every other element from the array from this selected element.
while (i<N) {
if (a>ar[i]) { //we selected the smallest element.
a=ar[i];
}
i=0;
while (i<N) {
ar[i]=ar[i]-a;
i++;
//this is applied to every single element.
}
if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step.
{
x++;
}
b=N-x;
cout<<b<<endl;
i++;
}
return 0; }
the entire question is found here:
Cut-the-sticks
You could use the std::remove function.
I was going to write out an example to go with the link, but the example form the link is pretty much verbatim what I was going to post, so here's the example from the link:
// remove algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
Strictly speaking, the posted example code could be optimized to not need the pointers (especially if you're using any standard container types like a std::vector), and there's also the std::remove_if function which allows for additional parameters to be passed for more complex predicate logic.
To that however, you made mention of the Cut the sticks challenge, which I don't believe you actually need to make use of any remove functions (beyond normal container/array remove functionality). Instead, you could use something like the following code to 'cut' and 'remove' according to the conditions set in the challenge (i.e. cut X from stick, then remove if < 0 and print how many cuts made on each pass):
#include <iostream>
#include <vector>
int main () {
// this is just here to push some numbers on the vector (non-C++11)
int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
int arsz = sizeof(arr) / sizeof(int);
std::vector<int> vals;
for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
std::vector<int>::iterator beg = vals.begin();
unsigned int cut_len = 2;
unsigned int cut = 0;
std::cout << cut_len << std::endl;
while (vals.size() > 0) {
cut = 0;
beg = vals.begin();
while (beg != vals.end()) {
*beg -= cut_len;
if (*beg <= 0) {
vals.erase(beg--);
++cut;
}
++beg;
}
std::cout << cut << std::endl;
}
return 0;
}
Hope that can help.
If you have no space bound try something like that,
lets array is A and number is number.
create a new array B
traverse full A and add element A[i] to B[j] only if A[i] != number
assign B to A
Now A have no number element and valid size is j.
Check this:
#define N 5
int main()
{
int ar[N] = {0,1,2,1,0};
int tar[N];
int keyEle = 0;
int newN = 0;
for(int i=0;i<N;i++){
if (ar[i] != keyEle) {
tar[newN] = ar[i];
newN++;
}
}
cout<<"Elements after deleteing key element 0: ";
for(int i=0;i<newN;i++){
ar[i] = tar[i];
cout << ar[i]<<"\t" ;
}
}
Unless there is a need to use ordinary int arrays, I'd suggest using either a std::vector or std::array, then using std::remove_if. See similar.
untested example (with c++11 lambda):
#include <algorithm>
#include <vector>
// ...
std::vector<int> arr;
// populate array somehow
arr.erase(
std::remove_if(arr.begin(), arr.end()
,[](int x){ return (x == 0); } )
, arr.end());
Solution to Cut the sticks problem:
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
// Cuts the sticks by size of stick with minimum length.
void cut(vector<int> &arr) {
// Calculate length of smallest stick.
int min_length = INT_MAX;
for (size_t i = 0; i < arr.size(); i++)
{
if (min_length > arr[i])
min_length = arr[i];
}
// source_i: Index of stick in existing vector.
// target_i: Index of same stick in new vector.
size_t target_i = 0;
for (size_t source_i = 0; source_i < arr.size(); source_i++)
{
arr[source_i] -= min_length;
if (arr[source_i] > 0)
arr[target_i++] = arr[source_i];
}
// Remove superfluous elements from the vector.
arr.resize(target_i);
}
int main() {
// Read the input.
int n;
cin >> n;
vector<int> arr(n);
for (int arr_i = 0; arr_i < n; arr_i++) {
cin >> arr[arr_i];
}
// Loop until vector is non-empty.
do {
cout << arr.size() << endl;
cut(arr);
} while (!arr.empty());
return 0;
}
With a single loop:
if(condition)
{
for(loop through array)
{
if(array[i] == 0)
{
array[i] = array[i+1]; // Check if array[i+1] is not 0
print (array[i]);
}
else
{
print (array[i]);
}
}
}

Recursively find min and max value in array

I made a recursive function to find the max and min value from an array which may contain arbitrary number of elements. The main reason behind making this was to develop an idea in finding the min max value from the pixel data of a Dicom image. I made this recursive function as a test code where I filled an int type array with random numbers ranging from 0-1000. My code is as below. I presented the whole code, you can run the program very easily in Visual Studio yourself.
#include <stdio.h>
#include <string>
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
void recursMax(int* a, int size, int* maxValue)
{
int half = size/2;
int* newMax = new int[half];
for(int i=0; i<half; i++)
{
newMax[i]=a[i]>a[size-i-1]?a[i]:a[size-i-1];
}
if(half>1)
{
recursMax(newMax, half, maxValue);
}
if(half == 1)
{
*maxValue = newMax[0];
delete [] newMax;
}
}
void recursMin(int* a, int size, int* minValue)
{
int half = size/2;
int* newMin = new int[half];
for(int i=0; i<half; i++)
{
newMin[i]=a[i]<a[size-i-1]?a[i]:a[size-i-1];
}
if(half>1)
{
recursMin(newMin, half, minValue);
}
if(half == 1)
{
*minValue = newMin[0];
delete [] newMin;
}
}
int main ()
{
int size = 100;
int* a = new int[size];
srand(time(NULL));
for(int i=0; i<size; i++)
{
a[i]=rand()%1000;
cout<<"Index : "<<i+1<<", "<<a[i]<<endl;
}
cout<<endl<<endl<<"Now we look to find the max!"<<endl;
int maxValue = 0;
int minValue = 0;
recursMax(a, size, &maxValue);
cout<<maxValue<<endl;
recursMin(a, size, &minValue);
cout<<"Now we look for the min value!"<<endl<<minValue<<endl;
cout<<"Checking the accuracy! First for Max value!"<<endl;
for(int i=0; i<size; i++)
{
cout<<"Index : "<<i+1<<", "<<maxValue-a[i]<<endl;
}
cout<<"Checking the accuracy! Now for min value!"<<endl;
for(int i=0; i<size; i++)
{
cout<<"Index : "<<i+1<<", "<<a[i]-minValue<<endl;
}
delete [] a;
return 0;
}
My question to you is that, do you think my algorithm works correctly? I'm have some doubt. Also, am I handling or maintaining the memory correctly? Or there will be some memory leakage in the code?
You should take delete [] newMax; out of last if statement, otherwise you'll never free memory. Like this:
if(half == 1)
{
*maxValue = newMax[0];
}
delete [] newMax;
And the same for recursMin function.
Your algorithm seems working, but excessive. Using recursion and allocating memory just to find min and max is not a good style.
For the max value I'd go with something like this:
int ArrayMax(const int *begin, const int *end)
{
int maxSoFar = *begin; // Assume there's at least one item
++begin;
for(const int *it = begin; it!=end; ++it)
{
maxSoFar = std::max(maxSoFar, *it);
}
return maxSoFar
}
Now you can say:
int main ()
{
int size = 100;
int* a = new int[size];
srand(time(NULL));
for(int i=0; i<size; i++)
{
a[i]=rand()%1000;
cout<<"Index : "<<i+1<<", "<<a[i]<<endl;
}
int theMax = ArrayMax(a, a+size);
}
Needless to say, you can convert ArrayMax into a template function to take any type, and ArrayMin is easily implemented using the same pattern.
I would suggest this code for finding the minimum, maximum is similar:
int min = std::numeric_limits<int>::max();
for(int i = 0; i < size ; i++) min = std::min(min,a[i]);
A lot shorter, no memory allocation, easy loop so the compiler will probably 1) vectorize it for maximum speed 2) use correct prefetching for even higher speed.
Only a partial answer because I haven't verified the algorithm in detail, but you're much better off copying the array first, then using that copy destructively to store your values.
It might use more memory, but saves you both runtime and bug chasing time on memory management.
You could probably improve things with an iterative implementation rather than a recursive one, if you risk running into degerate case that cause too deep recursion.
Using algorithm from STL:
Since C++11: you may use std::minmax_element to retrieve both at once : https://ideone.com/rjFlZi
const int a[] = {0, 1, 42, -1, 4};
auto it = std::minmax_element(std::begin(a), std::end(a));
std::cout << *it.first << " " << *it.second << std::endl;
In C++03, you may use std::min_element and std::max_element.
This is terrible algorithm for finding minimum and maximum. You can use simpler, shorter and faster solution:
const int maxInArray( const int* beg, const int* end) {
const int* it = std::max_element( beg, end);
if ( it == end)
{
std::cout << "There is no smallest element" << std::endl;
}
else
{
std::cout << "The smallest element is " << *it << std::endl;
}
return *it;
}
or iterate over the array:
int maxInArray( const int* beg, const int* end) {
int max;
if ( end - beg < 1 ) return -1;
max = *beg
while ( beg++ != end) {
if ( *beg > max) max = *beg;
}
return max;
}
with no boost support:
#include <iostream>
#include <limits>
int main() {
int max = std::numeric_limits<int>::min();
int min = std::numeric_limits<int>::max();
int num;
while ( std::cin >> num) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
std::cout << "min: " << min << std::endl;
std::cout << "max: " << max << std::endl;
return 0;
}
or with help from boost:
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
using namespace boost::accumulators;
int main() {
// Define an accumulator set for calculating the mean, max, and min
accumulator_set<double, features<tag::min, tag::max> > acc;
int num = -1;
bool empty = true;
while ( std::cin >> num && num >= 0) {
empty = false;
acc( num);
}
if ( ! empty) {
// Display the results ...
std::cout << "Min: " << min( acc) << std::endl;
std::cout << "Max: " << max( acc) << std::endl;
}
return 0;
}
Basically finding max in array is not recommended by recursion as it is not required. Divide and conquer algorithms(recursive) are more time costly. But even though if you want to use it, you can use my below algorithm. Basically, it brings the largest element of array at first position and has almost linear running time.(This algo is just a recursive-illusion though!):
int getRecursiveMax(int arr[], int size){
if(size==1){
return arr[0];
}else{
if(arr[0]< arr[size-1]){
arr[0]=arr[size-1];
}
return(getRecursiveMax(arr,size-1));
}
}