NicoleYork
NicoleYork

Reputation: 11

Remove indices from array and compact

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

Answers (2)

puneet_0303
puneet_0303

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

Brian McCutchon
Brian McCutchon

Reputation: 8584

  1. You have a type problem at cards[index]: this doesn't make sense, as index is an array. Perhaps you want to loop over the elements of index?
  2. You have a loop to copy elements from one array to the other. However, you return true inside the loop. That means that your loop will only run for one iteration.
  3. Your code doesn't actually compact the array or eliminate cards at the given indices. It's not really close yet, either. Here's a hint (since this is homework): right now, you're copying elements from one array to the other while keeping indices the same. What if you made the index into the old array differ by an offset from the index into the new array under certain circumstances?

You might want to try writing this assuming that there's only one card to eliminate, then generalize it to multiple cards.

Upvotes: 1

Related Questions