根据2D关系数组排序数组(更高,更低,无关紧要)

时间:2016-12-01 20:41:24

标签: c++ arrays algorithm sorting

我已经被这个问题困住了两天,但我仍然无法做对。

基本上,我有一个2D数组,其中包含某些数字之间的关系(在给定范围内):

  • 0 =订单无关紧要
  • 1 =第一个数字(左栏中的数字)应该是第一个
  • 2 =第二个数字(上排数字)应该是第一个

所以,我有一些2D数组,例如:

  0 1 2 3 4 5 6
0 0 0 1 0 0 0 2
1 0 0 2 0 0 0 0
2 2 1 0 0 1 0 0
3 0 0 0 0 0 0 0
4 0 0 2 0 0 0 0
5 0 0 0 0 0 0 0
6 1 0 0 0 0 0 0

我的目标是创建一个给定数字(0 - 6)的新数组,使其遵循2D数组的规则(例如,0在2之前但在6之后)。我可能还需要检查是否存在这样的数组,然后创建数组。得到这样的东西:

6 0 2 1 4 5

我的代码

(这并不重要,但我更喜欢c ++)

到目前为止,我尝试从有序数组0123456开始,然后根据表交换元素(但显然无法工作)。我也尝试根据表格将数字插入另一个数字的前面,但它似乎也没有用。

// My code example
// I have:
//    relArr[n][n]             - array of relations
//    resArr = {1, 2, ... , n} - result array

for (int i = 0; i < n; i++) {
    for (int x = 0; x < n; x++) {
        if (relArr[i][x] == 1) {
          // Finding indexes of first (i) and second (x) number
            int iI = 0;
            int iX = 0;
            while (resArr[iX] != x)
                iX++;
            while (resArr[iI] != i)
                iI++;

          // Placing the (i) before (x) and shifting array
            int tmp, insert = iX+1;
            if (iX < iI) {
                tmp = resArr[iX];
                resArr[iX] = resArr[iI];

                while (insert < iI+1) {
                    int tt = resArr[insert];
                    resArr[insert] = tmp;
                    tmp = tt;
                    insert++;
                }
            }
        } else if (relArr[i][x] == 2) {
            int iI = 0;
            int iX = 0;
            while (resArr[iX] != x)
                iX++;
            while (resArr[iI] != i)
                iI++;

            int tmp, insert = iX-1;
          if (iX > iI) {
                tmp = resArr[iX];
                resArr[iX] = resArr[iI];

                while (insert > iI-1) {
                    int tt = resArr[insert];
                    resArr[insert] = tmp;
                    tmp = tt;
                    insert--;
                }
            }
        }
    }
}

我可能错过了如何检查是否可以创建数组的正确方法。如果您愿意,可以随意使用载体。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

在您阅读输入的同时,您似乎正在重新排序输出。我认为您应该将输入解析为一组规则,稍微处理一下规则,然后在最后重新排序输出。

问题有哪些限制?如果输入显示01之前:

  | 0 1
--+----
0 |   1
1 |

它是否也保证会1之后发出0

  | 0 1
--+----
0 |   
1 | 2

如果是这样,您可以忘记2并仅查看1 s:

  | 0 1 2 3 4 5 6
--+--------------
0 |     1
1 |
2 |   1     1
3 |
4 |
5 |
6 | 1

通过阅读输入,我会存储一系列规则。我为此使用了std::vector<std::pair<int,int>>。它具有yourPair.first之前yourPair.second的优点:()

0 before 2
2 before 1
2 before 4
6 before 0

您可以放弃任何规则,其中第二个值永远不是另一个规则的第一个值。

0 before 2
6 before 0

然后需要对此列表进行排序,以便在 x &#34;之前进行排序。并且&#34; x 之前......&#34;保证按顺序排列。

6 before 0
0 before 2

然后将602移到列表0123456的前面,为您提供6021345

这有帮助吗?

答案 1 :(得分:0)

感谢您的建议。

根据建议,只有1个在2D数组中很重要。我用它们来创建有向边的向量,然后我实现了拓扑排序。我决定使用这个Topological Sorting Algorithm。它基本上是拓扑排序,但它也会检查周期。

这成功解决了我的问题。