C# 具有一个固定值的旋转数组
我正在构建一个基于“部分密钥验证”的强大逻辑和随机密钥生成。我需要通过旋转数组将其添加到另一个随机函数中,但我在Stack Overflow找到的所有示例都有不同的需求 我从一个数组开始:C# 具有一个固定值的旋转数组,c#,arrays,rotation,C#,Arrays,Rotation,我正在构建一个基于“部分密钥验证”的强大逻辑和随机密钥生成。我需要通过旋转数组将其添加到另一个随机函数中,但我在Stack Overflow找到的所有示例都有不同的需求 我从一个数组开始: int[] q = new int[5]; for (int i = 0; i < q.Length; i++) { q[i] = i; } 我需要顺时针旋转它,但我需要保持一个值不变,例如q[2]=2 然后第一步应顺时针加+1: q[0] = 1; q[1] =
int[] q = new int[5];
for (int i = 0; i < q.Length; i++)
{
q[i] = i;
}
我需要顺时针旋转它,但我需要保持一个值不变,例如q[2]=2
然后第一步应顺时针加+1:
q[0] = 1;
q[1] = 3; //bypassed 2nd value
q[2] = 2;
q[3] = 4;
q[4] = 0; //come back to 0
q[0] = 3; //bypassed 2nd value
q[1] = 4;
q[2] = 2;
q[3] = 0; //come back to 0
q[4] = 1;
第二步应再次顺时针加+1:
q[0] = 1;
q[1] = 3; //bypassed 2nd value
q[2] = 2;
q[3] = 4;
q[4] = 0; //come back to 0
q[0] = 3; //bypassed 2nd value
q[1] = 4;
q[2] = 2;
q[3] = 0; //come back to 0
q[4] = 1;
如果可能,我还需要回滚功能。。。非常感谢
感谢双方的帮助:同时我创建了我的解决方案:
for (int i = 0; i < q.Length; i++)
{
if (i == fixed_int) { } //donothing
else if ((q[i] + 1) == fixed_int) { q[i] = q[i] + 2; }
else if ((q[i] + 1) == (q.Length + 1)) { q[i] = 0; }
else { q[i] = q[i] + 1; }
}
当固定值没有2个整数前进时,这将失败,但我的情况不是这样。请不要使用此代码,因为它在某些情况下不起作用。使用公认的答案,因为它的岩石 假设阵列至少有2个元素,您可以尝试以下方法,将步骤设置为+1和-1以进行不同的旋转:
void Rotate(int[] a, int fix, int step)
{
int i = (fix + step + a.Length) % a.Length;
int n = (fix - step + a.Length) % a.Length;
int t = a[i];
while(i != n)
{
int j = (i + step + a.Length) % a.Length;
a[i] = a[j];
i = j;
}
a[n] = t;
}
以下是一个通用函数,可用于实现您的结果:
public static T[] Rotate<T>(T[] array, int fix)
{
// check for errors
if (array == null) throw new ArgumentNullException("array");
if (fix < 0 || fix > array.Length - 1) throw new IndexOutOfRangeException();
T[] result = new T[array.Length];
// copy the input into the results
Array.Copy(array, 1, result, 0, array.Length - 1);
result[array.Length - 1] = array[0];
// restore the location of the fixed item
int j = ((fix - 1) + array.Length) % array.Length; // index of "fix - 1"
result[j] = result[fix];
result[fix] = array[fix];
return result;
}
还请记住,此函数是泛型的,因此它可以使用下面用char array演示的任何类型的数组
var charArr = "abcdef".ToCharArray();
var charRslt = Rotate(charArr, 3); // {'b', 'c', 'e', 'd', 'f', 'a'}
var charRlbk = Rollback(charRslt, 3); // {'a', 'b', 'c', 'd', 'e', 'f'}
var charArr = "abcdef".ToCharArray();
var charRslt = Rotate(charArr, 3); // {'b', 'c', 'e', 'd', 'f', 'a'}
var charRlbk = Rollback(charRslt, 3); // {'a', 'b', 'c', 'd', 'e', 'f'}