6

考虑以下情况

我有一个数字数组:

 [ 1,2,3,4 ]

如果加入了这个数组,我将拥有数字1234

我想交换数字以达到最接近的更高数字

1234将变为1243,将变为1324,将变为1342等等。

我需要使用什么算法来在数组中进行这些更改?

理想情况下,我想以这种方式使用该算法:(假设 Array 将此算法作为一个称为演练的函数)

 [ 1,2,3,4].walkthrough() # gives [ 1, 2, 4, 3 ]
 [ 1,2,4,3].walkthrough() # gives [ 1, 3, 2, 4 ]

数字列表继续:

1234
1243
1324
1342
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241

4

2 回答 2

9

这给了你下一个排列:

bool Increase(int[] values) {
   // locate the last item which is smaller than the following item
   int pos = values.Length - 2;
   while (pos >= 0 && values[pos] > values[pos + 1]) pos--;
   // if not found we are done
   if (pos == -1) return false;
   // locate the item next higher in value
   int pos2 = values.Length - 1;
   while (values[pos2] < values[pos]) pos2--;
   // put the higher value in that position
   int temp = values[pos];
   values[pos] = values[pos2];
   values[pos2] = temp;
   // reverse the values to the right
   Array.Reverse(values, pos + 1, values.Length - pos - 1);
   return true;
}

编辑:
将 Array.Sort 更改为 Array.Reverse。这些项目始终按降序排列,并且应该按升序排列,因此它们给出相同的结果。

于 2009-08-27T19:48:54.563 回答
6

这看起来像您想按词汇顺序生成列表的排列。这些搜索词应该让您走上一条有用的道路。

例如,Python从 2.6 版开始将其包含在itertools模块中。该文档显示了实现这种算法的代码。

于 2009-08-27T19:19:07.730 回答