Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need to create a bulgarian solitaire game that Write the code to implement the game.should start with picking a random number piles and distributing

I need to create a bulgarian solitaire game that

Write the code to implement the game.should start with picking a random number piles and distributing the 45 cards among those piles.

Then call a method to start playing the game.

For each iteration of the game, print the piles. For example if you have 3 piles, one with 40, one with 2, one with 3 print this:

40 2 3

Now for the starting i dont always equal 45 this is what i got but my real question is whats causing my infinite loop run it a few times if it works perfect the first time

import java.util.ArrayList; import java.util.Collections; import java.util.Random;

public class BulgarianSolitaire {

ArrayList cards = new ArrayList(); Random rand = new Random(); boolean cont = true; boolean cont2 = true;

public static void main(String[] args) { BulgarianSolitaire game = new BulgarianSolitaire(); }

public BulgarianSolitaire() { System.out.println("Started"); int sum = 0; while (cont) { if (sum < 45) { cards.add(rand.nextInt(46 - sum)); } else { cont = false; }

sum = 0; for (int i = 0; i < cards.size(); i++) { sum += cards.get(i); }

removeZeros(cards);

System.out.println(cards); }

System.out.println("Finished Generating Start");

while (cont2) { solitaireStep(); System.out.println(cards); if (checkCards()) { cont2 = false; } }

Collections.sort(cards); System.out.println("Cards are sorted"); System.out.println(cards); }

public void removeZeros(ArrayList list) { for (int j = 0; j < list.size(); j++) { if (list.get(j) == 0) { list.remove(j); } } }

public void solitaireStep() {

int numberRemoved = 0;

for (int i = 0; i < cards.size(); i++) { int value = cards.get(i); cards.set(i, value - 1); removeZeros(cards); numberRemoved++; }

cards.add(numberRemoved); }

public boolean checkCards() { ArrayList expectedCards = new ArrayList();

for (int i = 1; i < 10; i++) { expectedCards.add(i); }

ArrayList sortedCards = cards; Collections.sort(sortedCards); boolean equal = true; if (sortedCards.size() != expectedCards.size()) { equal = false; }

for (int i = 0; i < sortedCards.size(); i++) { if (sortedCards.size() == expectedCards.size()) { if (sortedCards.get(i) != expectedCards.get(i)) { equal = false; } } }

return equal; } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions