프로그램이 컴파일되고 번호를 입력 할 수 있지만 생성하지 않거나 배열을 표시합니다. randomFillUnique 함수에서 선형 검색을 사용하여 while 조건을 제거하면 배열을 생성하고 표시하지만 고유 번호는 표시하지 않습니다. 중복되는 숫자가없는 2D 배열이 필요했습니다.은 선형 검색을 사용하여 2 차원 배열에 고유 번호를 생성합니다.
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
int** gen2Array(int n);
void randomFillUnique(int** arr, int n);
bool lSearch(int** arr, int n, int target);
void display(int** arr, int n);
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
randomFillUnique(gen2Array(number), number);
system("pause");
return 0;
}
int** gen2Array(int n)
{
int** arr2D = new int*[n];
for (int index = 0; index < n; index++)
arr2D[index] = new int[n];
return arr2D;
}
void randomFillUnique(int** arr, int n)
{
static default_random_engine e;
uniform_int_distribution<int> u(1, n*n);
e.seed(static_cast<int>(time(NULL)));
bool result = false;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
arr[row][col] = u(e); //generate random number
result = lSearch(arr, n, arr[row][col]);
while (result == true)
{
arr[row][col] = u(e); //generate random number
result = lSearch(arr, n, arr[row][col]);
}
}
}
display(arr, n);
delete[] arr;
}
bool lSearch(int** arr, int n, int target)
{
bool found = false;
for (int row = 0; row < n; row++)
for (int col = 0; col < n; col++)
{
if (arr[row][col] == target)
{
found = true;
return found;
}
}
return found;
}
void display(int** arr, int n)
{
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
cout << arr[row][col];
cout << endl;
}
}
arr [row, col]을 u (e)로 설정했기 때문에 항상 배열의 해당 값을 찾고 lsearch의 while 루프가 영원히 반복됩니다 –
임의로 숫자를 선택하고 중복을 거부하는 대신 ' std :: vector'를 호출 한 다음''std :: shuffle' (http://en.cppreference.com/w/cpp/algorithm/random_shuffle)을 적용하여''vector ''를 랜덤 화하십시오. 그럼 그냥 벡터에서 첫 번째 N 요소를 선택 – user4581301
오프 주제 : 메모리 누수. 'delete [] arr;'은 내부 배열이 아닌 외부 배열을 삭제합니다. 그리고 이제는 내부 배열을 가리키는 것이 없으므로 삭제하기가 매우 어렵습니다. – user4581301