我有一个包含整数的数组。
我想要做的是将数组拆分到一个位置,并将位于该位置前面的所有项目移动到数组的末尾,并将该位置之后的项目移动到数组的前面。
有谁知道如何做到这一点?
答案 0 :(得分: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);
}
答案 1 :(得分:2)
替换
cards[cards.length - position + i] = cards[i];
与
cards[cards.length - position + i] = cut1[i];
既然已经指出错误,那么你应该清楚错误的地方。
干杯!
答案 2 :(得分:-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
是全局的,请修改swapCard
:void swapCard(int x, int y)
并在for
循环中,只需致电swapCard(i, position + 1 + i);
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
如果position = 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
BTW,在您的示例中,我的方法的结果是:3, 2, 1