Generate 8 unique random numbers from 0 to 7 - c++

I'm making a simple script that generates 8 random values from 0 to 7 and stores them into an array named random_numbers.
This is my try:
int main(int argc, char** argv) {
int random_numbers[8];
srand((unsigned)time(NULL));
for (int i = 0; i < 8; i++) {
random_numbers[i] = 1+ rand() % 8;
cout << random_numbers[i] << endl;
}
return 0;
}
This gives me repeated values. I would like to have random_numbers filled of random values from 0 to 7, but without any repeated numbers.
How can I do that?

Generate the numbers 0 through 7, then shuffle them. Assuming this is actually C++, not C (because of the cout), use std::random_shuffle:
#include <algorithm>
#include <cstdlib>
#include <iostream>
int main()
{
int a[8] = {0, 1, 2, 3, 4, 5, 6, 7};
std::srand(unsigned(std::time(0)));
std::random_shuffle(a, a + 8);
for (int i=0; i<8; i++)
std::cout << a[i] << " ";
std::cout << std::endl;
}
Be warned: cppreference.com states that "The random number generator is implementation-defined, but the function std::rand is often used." I've seeded that with std::srand, but apparently that's not completely portable.

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
class Random {
public:
Random(){
srand( static_cast<unsigned int>(time(NULL)));
}
unsigned int operator()(unsigned int max){
double tmp = static_cast<double>( rand() ) / static_cast<double>( RAND_MAX );
return static_cast<unsigned int>( tmp * max );
}
};
int main(int argc, char** argv) {
int random_numbers[8];
int size = sizeof(random_numbers)/sizeof(int);
for(int i=0;i<size;++i)
random_numbers[i]=i;
Random r;
random_shuffle(random_numbers, random_numbers + size, r);
for (int i = 0; i < 8; i++) {
cout << random_numbers[i] << endl;
}
return 0;
}

Since you are using c++ any way I modified you code a bit more. Use vector instead of array, this should make your life easier, and this generates 0-7 in a random order without duplicates:
compile with -std=c++0x
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
int main(int argc, char** argv) {
srand(time(NULL));
vector<int> random_numbers(8);
iota(random_numbers.begin(), random_numbers.end(), 1);
random_shuffle(random_numbers.begin(), random_numbers.end());
for (unsigned i = 0; i < random_numbers.size(); i++) {
cout << random_numbers[i] << endl;
}
return 0;
}

try this code:
int random_numbers[8];
int main(int argc, char** argv) {
srand((unsigned)time(NULL));
for (int i = 0; i < 8; i++) {
random_numbers[i] =getRand(i);
cout << random_numbers[i] << endl;
}
return 0;
}
int getRand(int entries)
{
int flag = 0;
int randno ;
randno = rand() % 8;
for(int i=0;i<entries;i++)
{
if( random_numbers[i]==randno)
{
randno = rand() % 8;
continue;
}
}
return randno;
}

Related

Generate random number but required to have a certain number

I am trying to create a sequence of 4 different numbers and randomly generated from 0 to 100 but it must have number 86, here is what I did:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Loop to get 3 random numbers
for(int i = 0; i < 3; i++)
{
int random = rand() % 101;
// Print the random number
cout << random << endl;
}
cout << 86 << endl;
}
But I don't want to put 86 at the end, are there any ways to place it at any random position in the sequence ? Thank you
My approach using modern C++
#include <algorithm>
#include <iostream>
#include <array>
#include <random>
namespace {
std::default_random_engine generator(std::random_device{}());
int random(int min, int max) {
return std::uniform_int_distribution<int>{min, max}(generator);
}
}
int main() {
std::array<int, 4> elements = {86};
for (int i = 1; i < elements.size(); ++i) {
elements[i] = random(0, 100);
}
std::shuffle(elements.begin(), elements.end(), generator);
for (int nbr : elements) {
std::cout << nbr << "\n";
}
return 0;
}
You can do exactly as you said - place it in a random position. First, you store the four numbers to be generated in an array; then, you decide which position is 86; then, you fill the rest and print it.
int main()
{
srand((unsigned) time(NULL));
int nums[4];
int loc86 = rand() % 4;
for(int i = 0; i < 4; i++)
{
nums[i] = i != loc86 ? rand() % 101 : 86;
}
for(int i = 0; i < 4; i++)
{
// Print the random number
cout << num[i] << endl;
}
}
A bit offtopic, but if you really care about precision of the random number generation (and that it approaches uniform random distribution well enough), you might use pragmatic c++ random number generators as described here.
Two approaches
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Take a random position
const int j = rand() % 4;
// Loop to get 3 random numbers
for(int i = 0; i < 4; i++)
{
if (i == j)
cout << 86 << endl;
else
cout << rand() % 101 << end;
}
}
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Fill and shuffle the array
int r[4] = {86, rand() % 101, rand() % 101, rand() % 101};
std::shuffle(std::begin(r), std::end(r));
for(int i = 0; i < 4; i++)
cout << r[i] << end;
}

C++ Array of random numbers

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.

Filling an 1D array in C++

I have an integer array:
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
What I want to do is to create another array in terms of the multiplicity. So I define another array by:
int multi[7]={0};
the first index of the multi array multi[0] will tell us the number of multiplicity of the array listint that has zero. We can easily see that, there is no zero in the array listint, therefore the first member would be 0. Second would be 1 spice there are only 1 member in the array. Similarly multi[2] position is the multiplicity of 2 in the listint, which would be 3, since there are three 2 in the listint.
I want to use an for loop to do this thing.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
multi[j] = 1;
}
cout << "multi hit \n" << multi[1] << endl;
return 0;
}
After running this code, I thought that I would want the multiplicity of the each element of the array of listint. So i tried to work with 2D array.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int i, j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7][10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
for (j = 0; j < count; j++) {
multi[j][i] = 1;
}
}
cout << "multi hit \n" << multi[4][i] << endl;
return 0;
}
The first code block is something that I wanted to print out the multiplicity. But later I found that, I want in a array that multiplicity of each elements. SO isn't the 2D array would be good idea?
I was not successful running the code using 2D array.
Another question. When I assign j = count, I mean that that's the multiplicity. so if the value of count is 2; I would think that is a multiplicity of two of any element in the array listint.
A 2d array is unnecessary if you're just trying to get the count of each element in a list.
#include <iostream>
int main() {
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[8] = { 0 };
for (int i : listint)
++multi[i];
for (int i = 0; i < 8; ++i)
std::cout << i << ": " << multi[i] << '\n';
return 0;
}
There's also a simpler and better way of doing so using the standard collection std::map. Notably, this doesn't require you to know what the largest element in the array is beforehand:
#include <map>
#include <iostream>
int main() {
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
std::map<int, int> multi;
for (int i : listint)
multi[i]++;
for (auto [k,v] : multi)
std::cout << k << ": " << v << '\n';
}
Try this incase maps won't work for you since you're a beginner, simple:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = {1,2,2,2,4,4,5,5,7,7};
int multi[8]={0};
for(int i=0; i<10; i++)
{
multi[listint[i]]++; // using listint arrays elements as index of multi to increase count.
}
for( int i=1; i<8; i++)
{
cout << "multi hit of "<<i<<" : "<< multi[i]<<endl;
}
return 0;
}
OR if numbers could get large and are unknown but sorted
#include <iostream>:
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count = 0;
int index = 0; // used to fill elements in below arrays
int Numbers[10] = {0}; // storing unique numbers like 1,2,4,5,7...
int Count[10] = {0}; // storing their counts like 1,3,2,2,2...
int listint[10] = {1, 2, 2, 2, 4, 4, 5, 5, 7, 7};
for(int i = 0; i < sizeof(listint) / sizeof(listint[0]); i++)
{
count++;
if (listint[i] != listint[i+1]) {
Numbers[index] = listint[i];
Count[index] = count;
count=0;
index++;
}
}
for(int i=0; i<index; i++)
{
cout << "multi hit of "<<Numbers[i]<<" is " << Count[i]<<endl;
}
return 0;
}

Generating a random value array without repeating

I want to make a method that generates an array with random values between 0 and 6 in it without repeating those values.
This is what I've got:
void randomArray(){
randNum = rand() % 6;
code[0] = randNum
for (int i = 1; i < 4; i++){
randNum = rand() % 6;
code[i] = randNum;
while (code[i] == code[i - 1]){
randNum = rand() % 6;
code[i] = randNum;
}
}
}
But I'm getting repeated values on the random-generated array.
PD: I also need to use a similar method to make an array of enum's.
You could do something like this:
int randomFromSet(std::vector<int>&_set)
{
int randIndex = rand() % _set.size();
int num = _set[randIndex];
_set.erase(_set.begin() + randIndex);
return num;
}
This chooses a random int from a provided set of numbers, and removes that choice from the set so that it can't be picked again.
Used like so:
std::vector<int> mySet {0,1,2,3,4,5,6};
std::cout<<randomFromSet(mySet)<<'\n;
#include <random>
#include <vector>
#include <numeric>
#include <iostream>
using std::cout;
using std::endl;
int main() {
const int sz = 7;
std::vector<int> nums(sz);
std::iota(std::begin(nums), std::end(nums), 0);
std::default_random_engine re;
int i = 8;
while(--i > 0) {
auto my_set{ nums };
std::shuffle(my_set.begin(), my_set.end(), re);
for (auto x : my_set) {
cout << x << " ";
}
cout << endl;
}
}
Im new to c++ , can I add my answer too?
its c-style c++ sorry for that.but its easy to code and to understand at the same time.
#include <iostream> //std::cout
#include <ctime> //time() function
#include <cstdlib> //rand() and srand() functions
void rand_gen(unsigned int arr[],unsigned int sizeofarray)
{
srand((unsigned int)time(0);
for (unsigned int c = sizeofarray ; c > 0 ; c--)
{
unsigned int r = rand()%sizeofarray;
if (arr[r] != 404)
{
std::cout<<"Try No."<<(sizeofarray+1)-c<<" : "<<arr[r]<<"\n";
arr[r] = 404;
} else { c++; }
}
}
int main()
{
unsigned int n[7]={0,1,2,3,4,5,6};
rand_gen(n,7);
std::cin.get();
return 0;
}

I want to print out the last result done by the loop C++

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i;
int n=0;
int F[10];
F[0]=0;
F[1]=1;
cin>>n;
for(i=2; i<n+1; ++i)
{
F[i]=(F[i-1])+F[i-2];
cout <<F[i]<<endl;
}
getch();
return 0;
}
now this is a sort of a fibonacci number generator, but it outputs all previous numbers in the fibonacci series. I want it to print the last one. For example, if the input is 8, i want it to output "21" instead of 1 2 3 5 8 13 21.
#include <iostream>
#include <conio.h>
int main()
{
int F[10];
F[0] = 0;
F[1] = 1;
int n = 0;
cin >> n;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i-1] + F[i-2];
}
std::cout << F[n] << std::endl;
getch();
}
Since you already know the index of the last element (n), you can just print that after the loop. I also did some other cleanup that didn't change the functionality of the program.
Note that the program originally and still assumes that n is less than 10.
Just store only 2 last values:
#include <iostream>
using namespace std;
int main()
{
int F[2] = { 1, 1 };
int n = 0;
cin>>n;
for(int i=2; i<n; ++i)
{
swap( F[0], F[1] );
F[1] += F[0];
}
std::cout << F[1] << std::endl;
return 0;
}