Home > Net >  Generate random number but required to have a certain number
Generate random number but required to have a certain number

Time:08-15

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

CodePudding user response:

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.

CodePudding user response:

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; 
}

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related