2017-02-07 54 views
0

我需要一種算法,它將從第一個索引中彈出數組元素,並將下一個元素(從最後一個索引處的原始數組中)推送到找到的匹配元素集。移動數組元素的算法

象下面這樣:

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. 

邏輯應迭代,直到所要求的組中發現的數組元素的(基於元素一些計算)

+0

這似乎是一個相當微不足道的問題,你已經試過了什麼代碼? – Ben

+2

爲什麼不簡單地使用一個計數器,直到array.Length - 5 – ViVi

+0

雖然你可以修改數組,但如果你只是在尋找5個元素的子集,就沒有必要。使用開始/結束索引迭代5個元素並/或利用「ArraySegment」對5組進行簡單計算。 –

回答

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, 

如果你想旋轉數組我建議模算術

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,