0

프로그램이 컴파일되고 번호를 입력 할 수 있지만 생성하지 않거나 배열을 표시합니다. 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; 
    } 
} 
+0

arr [row, col]을 u (e)로 설정했기 때문에 항상 배열의 해당 값을 찾고 lsearch의 while 루프가 영원히 반복됩니다 –

+0

임의로 숫자를 선택하고 중복을 거부하는 대신 ' std :: vector'를 호출 한 다음''std :: shuffle' (http://en.cppreference.com/w/cpp/algorithm/random_shuffle)을 적용하여''vector ''를 랜덤 화하십시오. 그럼 그냥 벡터에서 첫 번째 N 요소를 선택 – user4581301

+0

오프 주제 : 메모리 누수. 'delete [] arr;'은 내부 배열이 아닌 외부 배열을 삭제합니다. 그리고 이제는 내부 배열을 가리키는 것이 없으므로 삭제하기가 매우 어렵습니다. – user4581301

답변

1

당신이 U (예) 당신이 lsearch 이전에 배열의 항목을 설정하고 있으므로, lsearch는 항상 true를 반환하고 잠시 영원히 반복됩니다. 아래 코드는 여러분의 코드에 따라 수정되어야합니다 (나머지 코드는 예상대로 동작한다고 가정합니다). user4581301이 지적했듯이, 더 나은 접근법이있을 수 있지만, 나는 그걸 작동시킬 수있을 정도로 충분히 갈 것입니다.

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))); 
int nextEntry; 
bool result = false; 
for (int row = 0; row < n; row++) 
{ 
    for (int col = 0; col < n; col++) 
    { 
     result = true; 
     while (result == true) 
     { 
      nextEntry = u(e); //generate random number 
      result = lSearch(arr, n, nextEntry); 
      if (result != true) 
       {arr[row][col]=nextEntry;} 
     } 
    } 
} 
display(arr, n); 
delete[] arr; 
} 
+0

도움을 주셔서 대단히 감사합니다. 이제 작동합니다. 나는 임시 변수를 넣으려고했지만 당신은 나를 위해 그것을했다. 다시 – timeToTime

+0

고마워요. (결과 == true) while (결과), 내 if (결과! = true)는 단지 if (! (결과)) 또는 if (! 결과)를 말할 수있는 동안 꽤 확신합니다. –

0

다른 방법은 iota를 사용하여 배열로 이동합니다 모든 고유 정수 컨테이너를 생성하는 것입니다 :

std::shuffle(invalues.begin(), invalues.end(), 
      std::mt19937{std::random_device{}()}); 

:

std::vector<int> invalues(n*n, 0); 
std::iota(invalues.begin(), invalues.end(), 1); 

그런 다음 해당 컨테이너 셔플 그런 다음 매트릭스에 값을 하나씩 입력하십시오.

또한 vector<vector<int>> 대신 내장 된 배열을 사용할 수

for (const auto &row : m) { 
    for (const auto &elem : row) { 
    std::cout << elem << " "; 
    } 
    std::cout << std::endl; 
} 
:

for (auto &row : m) { 
    for (auto &elem : row) { 
    elem = invalues.back(); 
    invalues.pop_back(); 
    } 
} 

그런 다음 행렬을 표시 :

using matrix = std::vector<std::vector<int>>; 

// initialising a vector<vector<int>> to be a certain size is a bit clumsy 
matrix m(size_y, std::vector<int>(size_x, 0)); 

그런 다음 매트릭스에 입력 값을 공급

Here's a full example in an online compiler.

+1

감사합니다. 고맙습니다. – timeToTime

0

확인. 여기에 제가 언급 한 쉬운 방법이 있습니다. std :: vector가 허용되지 않는다면 단순한 1D 벡터만으로도 충분할 것이다. 그러나 평범한 소프트웨어 엔지니어는 vector으로 선택하기 전에 정말 열심히 생각할 것이다.

몇 가지 다른 버그를 수정하기 위해 몇 가지 다른 변경을했습니다.

Documentation on std::vector

iota을 보여 정확히이 기술을 사용

Documentation on std::shuffle

Documentation on std::iota.

#include <iostream> 
#include <string> 
#include <random> 
#include <vector> 
#include <algorithm> // std::shuffle and std::iota 
#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); 
//Added to properly delete the 2dArray 
void del2Array(int ** arr, int n); 

int main() 
{ 
    int number = 10; 
    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; 
} 

//Added to properly delete the 2dArray 
void del2Array(int ** arr, 
       int n) 
{ 
    for (int index = 0; index < n; index++) 
     delete arr[index]; 
    delete arr; 
} 
void randomFillUnique(int** arr, int n) 
{ 
    //do the seeding here 
    static default_random_engine e(static_cast<int>(time(NULL))); 
// otherwise 
// e.seed(static_cast<int>(time(NULL))); 
// runs every time reseeding the RNG to potentially the give the same results 
// if run more than once in a second. Plus the seeding is expensive. 

    std::vector<int> v(n*n); // make and size vector 
    std::iota (v.begin(), v.end(), 0); // init vector with 1 through n*n 
    std::shuffle(v.begin(), v.end(), e); 

    size_t index = 0; 
    for (int row = 0; row < n; row++) 
    { 
     for (int col = 0; col < n; col++) 
     { 
      arr[row][col] = v[index++]; //generate random number 
     } 
    } 
    display(arr, n); 
    del2Array (arr, n); // frankly I don't think you want his here 
         // why fill an array only to delete it? 
         // more logical to display and delete back in main. 
} 

void display(int** arr, int n) 
{ 
    for (int row = 0; row < n; row++) 
    { 
     for (int col = 0; col < n; col++) 
      cout << arr[row][col] << "\t"; //added a tab to make the printing easier to read 
     cout << endl; 
    } 
} 

. 재밌 니?

+0

모든 도움과 조언에 감사드립니다. 나는 그것을 메모 할 것입니다. – timeToTime