Clyde
Clyde

Reputation: 85

When to use set and add methods in list

cutDeck() does the last step of shuffling -- cutting the deck. This should move the first cutLocation number of cards ("first" meaning at the lowest index) from cards and add them to the back of the List. Make certain that you add cards in the same (relative) order that they were originally stored.

public List<PlayingCard> cutDeck(int cutLocation) {
    for (int i = 0; i < cutLocation; i++) {
        cards.add(cards.get(i));
    }
    for (int i = 0; i < cutLocation; i++) {
        cards.remove(cards.get(i));
    }
    return cards;
}

This is the error message i am getting

cutDeck(133) did not correctly cut when cards had 208 cards. At index 0 expected 5H but was 3C expected:<[5H]> but was:<[3C]>

I can't see how I am doing something wrong, is it my logic should I be using the cards.set() instead of cards.add()?

Upvotes: 2

Views: 54

Answers (2)

nickb
nickb

Reputation: 59709

Your removal is wrong. Imagine cards has five cards in it and we're splitting it after the first two cards.

1 2 3 4 5

After your first loop terminates, you get:

1 2 3 4 5 1 2

Now, your second loop starts and removes the first card at i = 0, which is 1

2 3 4 5 1 2

Now, your second loop removes the first card at i = 1, which is 3, and NOT 2!

This is where your mistake is. You could simplify the whole logic to a single for loop:

for(int i = 0; i < cutLocation; i++) {
    cards.add(cards.remove(0));
}

Upvotes: 1

Progman
Progman

Reputation: 19555

When you removed the first card in your second for loop all your cards will have been shifted to the front by one position. But your loop variable i is still increasing and you use it in your cards.get(i) call. This means that when you are in the second iteration of your loop you will call cards.get(1), but this would be the original third card to remove. After that you try to remove the next card with cards.get(2), but it would delete the original fifth card and so on.

You might want to use cards.removeAt(0) to (always) remove the card at the beginning until you reached the limit cutLocation.

Upvotes: 0

Related Questions