import java.util.ArrayList; import java.util.Random; public class BulgarianSolitaire { public static void main(String[] args) { // You do not need to handle the User Interface (UI). // Instead you can run the JUnit test cases found in // ArrayListExercisesTests.java bulgarianSolitaire(10); } public static void bulgarianSolitaire(int numCards) { // Check if the given number of cards is triangular int n = (int) Math.sqrt(2 * numCards); if (n * (n + 1) / 2 != numCards) { System.out.println(numCards + " is not triangular"); return; } ArrayList finalArray = new ArrayList(); int sum = 0; for (int i = 1; sum + i <= numCards; i++) { finalArray.add(i); sum += i; } ArrayList pileOfCards = new ArrayList(); Random random = new Random(); int remaining = numCards; while (remaining > 0) { int pile = random.nextInt(remaining) + 1; pileOfCards.add(pile); remaining -= pile; } System.out.println(pileOfCards); while (!pileOfCards.equals(finalArray)) { int leftovers = 0; for (int i = 0; i < pileOfCards.size(); i++) { pileOfCards.set(i, pileOfCards.get(i) - 1); leftovers++; } pileOfCards.removeIf(pile -> pile == 0); pileOfCards.add(leftovers); System.out.println(pileOfCards); } } }