我有一个包含整数的数组。
我想要做的是在一个位置拆分数组,并将位于该位置前面的所有项移动到数组的末尾,并将该位置后面的项移到数组的前面。
有人知道怎么做吗?
发布于 2016-04-10 06:45:27
替换
cards[cards.length - position + i] = cards[i];使用
cards[cards.length - position + i] = cut1[i];既然已经指出了错误,那么应该可以清楚地看到您的错误所在。
干杯!
发布于 2016-04-10 06:55:25
不要发明轮子..。
用名单/名单..。他们的存在是为了这样一个逻辑,使操作变得更加容易。
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);
}发布于 2016-04-10 06:53:39
使用一个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. Hagstrom:我是这么想的:
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
https://stackoverflow.com/questions/36526656
复制相似问题