C ++ - 二维数组柱状排列

时间:2016-04-23 23:22:03

标签: c++ arrays algorithm permutation

我想找到使用std::next_permutation解决转置密码的所有排列。为此,我创建了一个带有文本的2D动态字符数组。我有一个键指的是数组的列数。

离。 与key = 3

1 2 3 4 5 6 7 8 9

可能的排列将是

2 1 3 5 4 6 8 7 9

一切正常,直到<Unable to read memory> 0xfdfdfdfd <Error reading characters of string.>始终与transArr[4][0]的{​​{1}}相同。{/ p>

代码:

key = 6

我无法理解为什么会发生这种情况,因为我在数组内部进行迭代,一切都已就绪。 我正在测试的文字是void transpositionCipher(char *text){ int key = 6, col = 0, row = 0, tempTextLength = length, numOfCol = 0, counter = 0, i=0,j=0; char **tranArr; string fileName; ofstream output,transpositions[5]; output.open("output.txt"); //for (key = 2; key < 7; key++){ output << "KEY IS " << key << "\n"; //fix length to create the columns. while (tempTextLength % key != 0){ if (tempTextLength - 1 % key == 0){ tempTextLength--; } else tempTextLength++; } output << tempTextLength << "\n"; //fixed column length for each key. numOfCol = tempTextLength / key; //allocation tranArr = new char*[key]; for (j = 0; j < key; ++j) tranArr[j] = new char[numOfCol]; //fill the array with the text for (i = 0; i < tempTextLength; i++){ if ((text[i] > 96 && text[i] < 123) || i < tempTextLength ){ if (col == numOfCol){ row++; col = 0; } if (i >= length){ tranArr[row][col] = '-'; } else tranArr[row][col] = text[i]; col++; } } //create the permutations fileName = "trans_key_"+to_string(key)+".txt"; transpositions[key-2].open(fileName); transpositions[key-2] << "Permutations with key = " << key << "\n"; sort(tranArr, tranArr + key); do { for (int k = 0; k < numOfCol; k++){ for (int l = 0; l < key; l++){ transpositions[key-2] << tranArr[l][k] << '\t'; } transpositions[key-2] << "\n"; } transpositions[key-2] << "\n\n"; counter++; } while (next_permutation(tranArr, tranArr + key)); //deallocation for (j = 0; j < key; j++) delete[] tranArr[j]; delete [] tranArr; //reset row = 0; col = 0; tempTextLength = length; counter = 0, numOfCol = 0; //} }

0 个答案:

没有答案