Reputation: 11
I am making a card game for school and i am trying to implement a method to delete cards at specified indices, then compact the array..
This is the code I have so far (nonworking) - can anyone give me some pointers as to where I am going wrong? Thanks.
private boolean removeCardsAt(int[] index){
cards[index] = cards[cards.length - 1];
Card[] newCards = new Card[cards.length - 1];
for( int i = 0; i < newCards.length; i++) {
newCards[i] = cards[i];
return true;
}
return false;
}
Upvotes: 0
Views: 98
Reputation: 197
Considering paramter paased is array of indecis to be removed from Cards array:-
private static boolean removeCardsAtIndex(int[] index){
int cardsLength = cards.length;
for(int i = 0 ; i < index.length ; i++){
int paramInt = index[i];
int numberOfElements = cards.length - paramInt - 1;
if (numberOfElements > 0) {
System.arraycopy(cards, paramInt + 1, cards, paramInt, numberOfElements);
cards[(--cardsLength)] = null;
}
}
Card[] newCards = new Card[cardsLength];
for( int i = 0; i < cardsLength; i++) {
newCards[i] = cards[i];
}
if(newCards.length < cards.length){
return true;
}
return false;
}
Note: After each iteration on index array,Copy the elements after the index,onto the same array starting at index position,Also card elements indexes are updated on each iteration.
Upvotes: 0
Reputation: 8584
cards[index]
: this doesn't make sense, as index
is an array. Perhaps you want to loop over the elements of index
?return true
inside the loop. That means that your loop will only run for one iteration.You might want to try writing this assuming that there's only one card to eliminate, then generalize it to multiple cards.
Upvotes: 1