用于移位数组元素的算法

时间:2017-02-07 07:17:46

标签: c# arrays algorithm search data-structures

我需要一个算法,它将从第一个索引中弹出数组元素并推送下一个元素(从最后一个索引处的原始数组),直到找到匹配的元素集。

如下所示:

Original array : {10,20,30,40,50,60,70,80,90,100,110,120}

1st iteration : 10,20,30,40
2nd iteration : 20,30,40,50
3rd iteration : 30,40,50,60
4th iteration : 40,50,60,70 .... and so on until the matching criteria set found.

逻辑应该迭代,直到找到所需的数组元素集(基于对元素的一些计算)

1 个答案:

答案 0 :(得分:4)

你的问题是含糊不清;如果你想转移起点:

   int array = new[] {10,20,30,40,50};

   for (int shift = 0; shift < array.Length; ++shift) {
     for (int i = shift; i < array.Length; ++i) {
       int value = array[i];

       Console.Write(value);
       Console.Write(", ");
     }

     Console.WriteLine();  
   }

结果:

   10, 20, 30, 40, 50, 
   20, 30, 40, 50,
   30, 40, 50,
   40, 50,
   50, 

如果你想旋转数组我建议 modulo arithmetics

   for (int shift = 0; shift < array.Length; ++shift) {
     for (int index = 0; index < array.Length; ++index) {
       int i = (shift + index) % array.Length;  

       int value = array[i];

       Console.Write(value);
       Console.Write(", ");
     } 

     Console.WriteLine();   
   }

结果:

   10, 20, 30, 40, 50, 
   20, 30, 40, 50, 10, 
   30, 40, 50, 10, 20,
   40, 50, 10, 20, 30,
   50, 10, 20, 30, 40,