2016-04-10 21 views
0

我有一個數組,其中包含整數。拆分和移動數組中的項目

我想要做的是將數組拆分到某個位置,並將該位置前的所有項目移動到數組的末尾,並將位置之後的項目移動到數組的前面。

有沒有人知道如何去做這件事?

+0

完成。已添加代碼 – user1664285

回答

2

更換

cards[cards.length - position + i] = cards[i]; 

cards[cards.length - position + i] = cut1[i]; 

既然錯誤已經指出的,應該很清楚你在哪裏走錯了。

乾杯!

+0

太棒了!這正是我需要的。感謝您指出這個錯誤給我! – user1664285

-1

一個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是全球性的,修改swapCardvoid 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

+0

用3張卡片1,2,3和位置1嘗試此操作。結果應該是2,3,1。您的方法結果爲2,1,3 .OP沒有要求交換,他們要求整個陣列轉移。 –

+0

這是我的錯!但在你的例子中,我的方法的結果是:'3,2,1' –

3

不要重新發明輪子...

使用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); 
    }