2017-05-05 207 views
-1

我正在用這個打磚牆,而我似乎無法把頭圍住它。得到每一個第n個元素或最後一個

給定一個對象列表,我怎樣才能得到從結尾開始的第三個元素(所以第三個到最後一個,第六個到最後一個等),但如果它到了最後,只剩下1或2個,返回第一個元素。

我本質上是試圖模擬從股票中繪製三張牌,並在耐心的比賽中檢查有效的移動,但由於某種原因,我正在與這一概念掙扎。

編輯:

到目前爲止,我已經試過看着使用標準的for循環增加一步。這導致了我第二個需要,即如果最後一個循環中少於三個,就得到第一個元素。

我已經嘗試了其他關於堆棧溢出的建議,以獲得列表中的第n個元素,但是它們也都不提供第二個要求。

不完全確定哪些代碼我可以發佈,這不會是一個簡單的循環。因爲我的問題是代碼的邏輯,而不是代碼本身。

例如:

給出的列表 1,2,3,4,5,6,7,8,9,10

我想獲得一個清單, 8,5 ,2,1 作爲回報。

+0

要顯示的任何代碼? – MickyD

+0

你嘗試過什麼嗎?即使這只是思考過程,告訴我們你到目前爲止的。 – Kroltan

+0

我沒想到需要這個代碼,我認爲它會很快。我會添加我迄今爲止嘗試過的這個。 – Ben

回答

1

僞代碼:

List<object> filtered = new List<object>(); 
List<object> reversedList = myList.Reverse(); 
if(reversedList.Count % 3 != 0) 
{ 
    return reversedList.Last(); 
} 
else 
{ 
    for(int i = 3; i < reversedList.Count; i = i +3) 
{ 
    filterList.Add(reversedList[i]); 
} 
if(!filterList.Contains(reversedList.Last()) 
{ 
    filterList.Add(reversedList.Last()); 
} 
+0

嘿謝謝你的答覆。猜猜我的文字在我的文章中仍然需要一些小小的工作。我希望這兩種情況都會發生,所以它會循環遍歷你的for循環,但是如果沒有第三個元素,就得到第一個元素(因爲我們倒退了,技術上第一個是最後一個)。我會稍微更新我的文章。 – Ben

+0

因此得到每一個第三項和最後一項,如果它不能被3整除?如果小於3,只返回最後一個? –

+0

是的,沒錯。我已經在我的問題中發佈了一個示例,我希望將它清除一點 – Ben

1

嘗試使用此代碼 -

List<int> list = new List<int>(); 
List<int> resultList = new List<int>(); 
int count = 1; 
for (;count<=20;count++) { 
    list.Add(count); 
} 
for (count=list.Count-3;count>=0;count-=3) 
{ 
    Debug.Log(list[count]); 
    resultList.Add(list[count]); 
} 
if(list.Count % 3 > 0) 
{ 
    Debug.Log(list[0]); 
    resultList.Add(list[0]); 
} 
0

不得不嘗試和使用LINQ做。 不確定它是否符合您的要求,但適用於您的示例。

 var list = Enumerable.Range(1, 10).ToList(); 
     //Start with reversing the order. 
     var result = list.OrderByDescending(x => x) 
      //Run a select overload with index so we can use position 
      .Select((number, index) => new { number, index }) 
      //Only include items that are in the right intervals OR is the last item 
      .Where(x => ((x.index + 1) % 3 == 0) || x.index == list.Count() - 1) 
      //Select only the number to get rid of the index. 
      .Select(x => x.number) 
      .ToList(); 

     Assert.AreEqual(8, result[0]); 
     Assert.AreEqual(5, result[1]); 
     Assert.AreEqual(2, result[2]); 
     Assert.AreEqual(1, result[3]); 
相關問題