回答
更換
cards[cards.length - position + i] = cards[i];
與
cards[cards.length - position + i] = cut1[i];
既然錯誤已經指出的,應該很清楚你在哪裏走錯了。
乾杯!
太棒了!這正是我需要的。感謝您指出這個錯誤給我! – user1664285
一個for
循環簡化代碼:
for (int i = 0; i < position && position + 1 + i < cards.length; i++) {
swapCard(cards, i, position + 1 + i);
}
現在,這是swapCard
方法:
void swapCard(Card[] cards, int x, int y) {
Card temp = cards[x];
cards[x] = cards[y];
cards[y] = temp;
}
如果cards
是全球性的,修改swapCard
:void swapCard(int x, int y)
和for
循環,只需調用swapCard(i, position + 1 + i);
@Erick G.黑格斯特羅姆:這就是我的想法:
position: 0 1 2 3 4
array: 1 3 5 7 9
如果position = 1
,意味着array[1] = 3
仍然存在,陣列將變更爲:
position: 0 1 2 3 4
array: 5 3 1 7 9
如果position = 2
:
position: 0 1 2 3 4
array: 7 9 5 1 3
而且如果位置= 3:
position: 0 1 2 3 4
array: 9 3 5 7 1
但我錯了。他們希望將陣列更改:
position: 0 1 2 3 4
array: 5 7 9 3 1
其中position = 1
和:
position: 0 1 2 3 4
array: 9 7 1 3 5
其中position = 3
順便說一句,在你的榜樣,我的方法的結果是:3, 2, 1
用3張卡片1,2,3和位置1嘗試此操作。結果應該是2,3,1。您的方法結果爲2,1,3 .OP沒有要求交換,他們要求整個陣列轉移。 –
這是我的錯!但在你的例子中,我的方法的結果是:'3,2,1' –
不要重新發明輪子...
使用List/ArrayList ...他們在那裏爲這樣的邏輯使得操作更容易..
public static void main(String[] args) {
//define the maze
String[] array = { "A", "B", "C", "D", "1", "2", "3", "4" };
List<String> listA = new ArrayList<>(Arrays.asList(array));
System.out.println(listA);
// this will print [A, B, C, D, 1, 2, 3, 4]
// then add the lower half of the cards maze
List<String> cutList = new ArrayList<>(listA.subList(listA.size()/2, listA.size()));
System.out.println(cutList);
// this will print [1, 2, 3, 4]
// then add the upper half of the cards maze
cutList.addAll(listA.subList(0, listA.size()/2));
// this will print [1, 2, 3, 4, A, B, C, D]
System.out.println(cutList);
}
- 1. 帶字符的拆分數組項目
- 2. 拆分元組項目
- 3. 移動數組中的項目
- 4. 計數動態項目,然後拆分
- 5. 拆分Django項目
- 6. 拆分Django項目的「admin.py」?
- 7. 拆分數組成重疊塊(移動子組)
- 8. 在特殊項目上拆分數組,然後將項目拆分成不同的列表
- 9. 移動項目在二維數組python
- 10. 拆分數組中的JavaScript
- 11. 如何移動數組中的一組項目?
- 12. 拆分數組
- 13. 拆分數組
- 14. 根據另一個數組中的條目拆分數組
- 15. 拆分詞典中的值項目
- 16. 拆分列表中的每個項目
- 17. 在ruby中拆分和重構數組
- 18. vimrc拆分欄可移動
- 19. 如何將條目中的項目拆分爲兩個項目?
- 20. 拆分ng重複項目?
- 21. 拆分多個項目
- 22. 如何拆分數據庫項目?
- 23. 拆箱組合框項目
- 24. Python中,拆分元組項目單的東西
- 25. LINQ/Lambda更新通過將項目拆分成偶數組來列出項目
- 26. 在C中拆分數組#
- 27. 在MATLAB中拆分數組
- 28. JavaScript排序和分組中的項目
- 29. 如何將長字符串拆分爲固定數組項目
- 30. 如何數組列表中移動特定項目的第一個項目
完成。已添加代碼 – user1664285