Reputation: 85
Move the first half of cards into firstHalf // This may or may not be done in one line of code Move the remaining elements in cards into secondHalf // This may or may not be done in one line of code While there are elements in firstHalf Remove the element at the start of firstHalf and add it to cards Remove the element at the start of secondHalf and add it to cards EndWhile If secondHalf has any elements remaining Remove the element at the start of secondHalf and add it to cards EndIf
this is the error I am getting. Why is my list growing if I am removing?Should I be doing something like this inside my first for loop
firstHalf.add(cards.remove(0));
cards= firstHalf.add(cards.remove(0));
this is the error I am getting
shuffle() should not change the number of elements in cards. cards had contained a complete 52 card deck, but now has size: 71 expected:<52> but was:<71>
public void shuffle(ListGenerator gen) {
List<PlayingCard> firstHalf = gen.createNewList();
List<PlayingCard> secondHalf = gen.createNewList();
for (int i = 0; i <= (cards.size() / 2); i++) {
firstHalf.add(cards.remove(0));
}
secondHalf.addAll(cards);
while (firstHalf.isEmpty() == false) {
cards.add(firstHalf.remove(0));
cards.add(secondHalf.remove(0));
}
if (secondHalf.isEmpty() == false) {
cards.add(secondHalf.remove(0));
}
}*
Upvotes: 1
Views: 87
Reputation: 319
You are using the same variable i.e card in for loop and also removing the item from same card variable. Therefore, you are actually adding less number of element in firstHalf and your card still has the size that exceeds half of its original size.
for (int i = 0; i <= (cards.size() / 2); i++) {
firstHalf.add(cards.remove(0));
}
the size of firstHalf after the for loop ::18
the size of the card after the for loop::34
you should use the different variable for loop. like:
List<Integer> cardSize = cards.size();
for (int i = 0; i <= (cardSize / 2); i++) {
firstHalf.add(cards.remove(0));
}
I believe it should solve your issue.
Upvotes: 1
Reputation: 1
secondHalf.addAll(cards)
Here you are adding elements to the secondHalf, but you didn't remove the elements in cards. Add below line to code.
cards.clear();
Upvotes: 0
Reputation: 31
I'd expect
secondHalf.addAll(cards);
Doesn't remove the entries from cards. Add a test after that line to see if cards is empty.
Upvotes: 0
Reputation: 50716
When you call secondHalf.addAll(cards);
, you're not removing those cards from cards
. Add this afterwards:
cards.clear();
Upvotes: 1
Reputation: 37404
you need to clear the cards
because cards still has elements which were previously added to secondHalf
secondHalf.addAll(cards);
cards.clear();
//^^^^^^^^^^^^
Upvotes: 3