-2

I have an assignment that wants ne to make a magic square program where you generate random numbers 1-9 and assign them to a 2D array, I cannot figure out how to generate random numbers that don't repeat and I was wondering if someone can help me it's c++.

in advance thank you!

2 Answers2

0

Take a look at std::random_shuffle, in the algorithm header. It should work with almost all of the stl containers, assuming that is sufficient. For example, you could use it on a vector with the integers 1 through 9, and then convert it back to an array. It's not the most efficient method, but it saves you most of the coding effort.

Hope this helps!

sabreitweiser
  • 643
  • 3
  • 13
0
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

// Returns true if the item is in the list, otherwise false
bool checkInList(std::vector<int> &list, int value)
{
    for (int i = 0; i < list.size(); ++i)
    {
        if (list.at(i) == value)
        {
            return true;
        }
    }

    return false;
}

// min inclusive, max exclusive
// make sure to set a new seed before using to help make results more random. (std::srand)
int randomInt(int min, int max) 
{
    return rand() % (max - min) + min;
}

int main() 
{
    std::vector<int> list;
    std::srand(std::time(0));

    while (list.size() < 9)
    {
        int num = randomInt(1, 10); 

        if (!checkInList(list, num))
        {
            list.push_back(num);
        }
    }

    for (int i = 0; i < list.size(); ++i)
    {
        std::cout << list.at(i) << std::endl;
    }

    return 0;
}

I liked sabreitweiser's answer for the simplicity, but it doesn't do exactly what you asked for.

The code I posted should be along the lines of what you're looking for.

DrowsySaturn
  • 1,587
  • 1
  • 10
  • 4