2017-02-07 7 views
0

EDIT: В настоящее время я работаю над проектом. Я почти закончен, хотя я не могу понять, как заполнить мой вектор (матрицу) не повторяющимися случайными числами. Я получаю случайные числа, но некоторые из них повторяются. Я попробовал реализовать метод, который проверяет, существует ли число, нажатое в вектор, но это не работает.Не повторяющиеся случайные числа 2D-вектор (C++)

Есть ли простой способ сделать это?

#include <iostream> 
#include <iomanip> 
#include <vector> 
#include <cstdlib> 
#include <ctime> 

using namespace std; 

/* 
The purpose of this program is to create a matrix using 2D vectors, then decide 
if it is a perfect matrix or not. 
*/ 

void matrix(int); 

int main() 
{ 
    int input; 
    char again = 'y'; 

    cout << "Welcome to my perfect matrix program. The function of the program is" 
      "\nto:" 
      "\n" 
      "\n 1. Allow the user to enter the size of the perfect matrix, such as" 
      "\n  N. N>=2." 
      "\n 2. Create a 2 D vector array of size N x N." 
      "\n 3. Populate the 2 D vector array with distinct random numbers." 
      "\n 4. Display the sum for each row, column, and diagonals then" 
      "\n  determine whether the numbers in N x N vector array are perfect" 
      "\n  matrix numbers."; 
    cout << endl << endl; 

    while(again == 'y' || again == 'Y') 
    { 
     cout << "\nEnter the size of the matrix : "; 
     cin >> input; 

     while(input < 2) 
     { 
      cout << "\nError *** Incorrect input - You entered a number < 2" 
        "\nEnter a Positive integer Number >= 2: "; 
      cin >> input; 
     } 

     matrix(input); 

     cout << "\nWould you like to find another perfect matrix?" 
       "\nEnter y || Y for yes or n || N for no: "; 
     cin >> again; 

     if(again == 'N' || again == 'n') 
     { 
      cout << "\nThis perfect matrix algorithm is implemented by B" 
        "\nFebruary 13th - 2017\n"; 
     } 

     while(again != 'Y' && again != 'y' && again != 'N' && again != 'n') 
     { 
      cout << "\nError *** Invalid choice - Must enter y|Y or n|N" << endl; 
      cout << "\nWould you like to find another perfect matrix?" 
        "\nEnter y || Y for yes or n || N for no: "; 
      cin >> again; 
     } 
    } 

    return 0; 
} 

void matrix(int value) 
{ 
    int N = value; 
    bool isPerf = true; 
    int sum = 0, 
     i, 
     j; 

    int diagSum1 = 0, 
     diagSum2 = 0; 

    vector<vector<int> >arr; 

    srand(time(0)); 

    for(i = 0; i < N; i++) 
    { 
     vector<int> temp; 
     bool check; 
     int digit; 
     for(j = 0; j < N; j++) 
     { 
      do 
      { 
       digit = rand()%8; 
       check = true; 
       for(int k = 0; k < j; k++) 
       { 
        if(digit == temp.front()) 
        { 
         check = false; 
         break; 
        } 
       } 
      }while(!check); 
      temp.push_back(digit); 
     } 
     arr.push_back(temp); 
    } 

    cout << endl; 
    cout << "The perfect matrix that is created for size " << value << ":"; 
    cout << endl << endl; 

    for(i = 0; i < arr.size(); i++) 
    { 
     for(j = 0; j < arr[i].size(); j++) 
     { 
      cout << arr[i][j]; 
      cout << " "; 
     } 
     cout << endl << endl; 
    } 

    for(i = 0; i < arr.size(); i++) 
    { 
     for(j = 0; j < arr[i].size(); j++) 
     { 
      sum += arr[i][j]; 
     } 
    } 
    int perf = sum/3; 

    cout << "The perfect number is: " << perf << endl << endl; 

    for(i = 0; i < arr.size(); i++) 
    { 
     int rowSum = 0; 
     for(j = 0; j < arr[i].size(); j++) 
     { 
      rowSum += arr[i][j]; 
     } 
     cout << "Sum of numbers in Row # " << i + 1 << " = " << rowSum; 
     if(rowSum != perf) 
     { 
      isPerf = false; 
     } 
     cout << endl; 
    } 
    cout << endl; 


    for(i = 0; i < arr.size(); i++) 
    { 
     int colSum = 0; 
     for(j = 0; j < arr[i].size(); j++) 
     { 
      colSum += arr[j][i]; 
     } 

     cout << "Sum of numbers in Column # " << i + 1 << " = " << colSum; 
     if(colSum != perf) 
     { 
      isPerf = false; 
     } 
     cout << endl; 
    } 
    cout << endl; 


for(i = 0; i < arr.size(); i++) 
{ 
     diagSum1 += arr[i][i]; 
     diagSum2 += arr[i][arr.size() - i - 1]; 
} 

cout << "Sum of numbers in first diagonal = " << setw(3) << diagSum1 << endl; 
if(diagSum1 != perf) 
    { 
     isPerf = false; 
    } 
cout << "Sum of numbers in second diagonal = " << setw(3) << diagSum2 << endl; 
if(diagSum2 != perf) 
    { 
     isPerf = false; 
    } 

cout << endl; 

if(isPerf) 
{ 
    cout << "The above is a perfect matrix" << endl; 
} 
else 
    cout << "The above is not a perfect matrix" << endl; 

cout << endl; 

}

ответ

0

Одним из вариантов является создание временного набора для вас, чтобы заполнить с случайных чисел. Проверяйте размер набора, когда вы вставляете элемент, и когда размер равен количеству требуемых элементов, выполните итерацию по набору, чтобы получить значения и заполнить матрицу.

... 
std::set<int> distinct; 
while (distinct.size() < input) { 
     int r_num = /* random number generation */ 
     distinct.insert(r_num); 
} 
std::set<int>::iterator it; 
for (it = distinct.begin(); it != distinct.end(); it++) { 
     /* method of adding to matrix */ = *it; 
} 
...