2015-04-25 19 views
0

我正在構建一個強大的邏輯和隨機化的keygen,並以'部分密鑰驗證'爲基礎。我需要通過旋轉數組來添加另一個隨機函數,但是在Stack Overflow中找到的所有示例都與我的需求不同。具有一個固定值的旋轉陣列

我開始以與陣列:

int[] q = new int[5]; 
    for (int i = 0; i < q.Length; i++) 
    { 
     q[i] = i; 
    } 

現在我有:

q[0] = 0; 
q[1] = 1; 
q[2] = 2; 
q[3] = 3; 
q[4] = 4; 

我需要順時針,但我需要保持一個不變的值,如例如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 

第二步驟應是(通過添加再次+ 1的順時針方向):如果可能我還需要

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更多的int轉發,但它不是我的情況。請不要使用此代碼,因爲它在某些情況下不起作用。使用接受的答案,因爲它很有趣!

回答

0

假設陣列具有至少2個元素,你可以嘗試這樣的事情(設置step+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; 
} 
0

這裏是一個通用的功能,你可以用它來實現你的結果:

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; 
} 

這裏是伴隨回滾功能:

public static T[] Rollback<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, 0, result, 1, array.Length - 1); 
    result[0] = array[array.Length - 1]; 

    // restore the location of the fixed item 
    int skp = ((fix + 1) + array.Length) % array.Length; 
    result[skp] = result[fix]; 
    result[fix] = array[fix]; 

    return result; 
} 

它可以用作如下:

var input = new[] {0, 1, 2, 3, 4}; 
var result = Rotate(input, 2);  // yields {1, 3, 2, 4, 0} 
var rollback = Rollback(result, 2); // yields {0, 1, 2, 3, 4} 

也請記住,這個函數是通用的,因此它可以與任何類型的(具有下文char陣列證明)的數組。

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'} 
+0

非常有趣的字符旋轉,非常感謝! –