Home > database >  Variable Length Array elements random generator
Variable Length Array elements random generator

Time:11-17

simple task, to generate arrays with length I want to.

I don't also know how to get array I've created, except my own weird method. Does the first part of my code work alright and I should reconsider the way I want to get them (optional)?

although, I do understand why do I get the same values each time, but I don't think, it's related to my problem somehow.

I'm writing down this:

  cin >> x;
  int array1[x];
  int array2[x]; 
  for (int i = 0; i <= x; i  ) {
    array1[i] = rand() % 10   1;
    array2[i] = rand() % 10   1;
  }
  

  cout << "[" << array1[a];
  for (int a = 0; a <= x; a  ) {
    a  = 1; 
    cout << ", " <<array1[a];
  }


  cout << "] [" << array2[b];
  for (int b = 0; b <= x; b  ) {
    b  = 1; 
    cout << ", " << array2[b];
  }
  cout << "]";

why do i get some abnormal answer for x = 6, 5, 15 cases like this:

[2, 5, 9, 6, 0] [8, 1, 9, 6, 32759]
[2, 5, 9, 6, 2, 8, 3, 2, 8] [8, 1, 9, 6, 2, 7, 4, 7, 7]

CodePudding user response:

Or using header and std::vector, std::generate (no raw loop). Also when you write code, write small readable functions. And to get unique random numbers random generators need to be seeded.

#include <algorithm>
#include <iostream>
#include <random>
#include <vector>

int generate_random_number()
{
    // only initialize the generator and distribution once (static)
    // and initialize the generator from a random source (device)
    static std::mt19937 generator(std::random_device{}());
    static std::uniform_int_distribution<int> distribution{ 1,10 };
    return distribution(generator);
}

// overload stream output for vector, so we can use vectors in std::cout
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
    bool comma{ false };
    
    os << "[";
    for (const int value : values)
    {
        if (comma) os << ", ";
        os << value;
        comma = true;
    }
    os << "]";

    return os;
}

// helper function to create an array of given size
std::vector<int> create_random_array(const std::size_t size)
{
    std::vector<int> values(size); // create and allocate memory for an array of size ints
    std::generate(values.begin(), values.end(), generate_random_number); // fill each value in the array with a value from the function call to generate_random_number
    return values;
}

int main()
{
    std::size_t count;
    std::cout << "how many random numbers ? : ";
    std::cin >> count;

    auto array1 = create_random_array(count);
    std::cout << array1 << "\n";

    auto array2 = create_random_array(count);
    std::cout << array2 << "\n";

    return 0;
}
  • Related