用于置换数组中元素的算法

Ste*_*fan 6 arrays algorithm permutation

请考虑以下情形.

我有一系列数字:

 [ 1,2,3,4 ]
Run Code Online (Sandbox Code Playgroud)

如果加入这个数组,我的数字是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 ]
Run Code Online (Sandbox Code Playgroud)

数字列表继续:

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

Guf*_*ffa 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;
}
Run Code Online (Sandbox Code Playgroud)

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


Phi*_*ler 6

这看起来像要生成排列的列表中的词汇顺序.这些搜索条件应该让您走上有用的道路.

例如,Python在2.6版本的itertools模块中包含了这个.该文档显示了实现此类算法的代码.