0

I currently have a randomly mixed ArrayList.

public static void main(String[] args) {
    ArrayList<Integer> solution = new ArrayList<>();
    for (int i = 1; i <= 48; i++) {
        solution.add(i);
    }
    Collections.shuffle(solution);

This gives me a ArrayList with the numbers 1-48 randomly mixed. Now I have 4 arrays and I want to randomly add the elements of the ArrayList with out repetition.

 int[] heartsRow = new int[14];
 int[] diamondsRow = new int[14];
 int[] spadesRow = new int[14];
 int[] clubsRow = new int[14]; 

The reason the new arrays contain 14 elements is because the first two elements will always be the same.

    heartsRow[0] = 1;
    heartsRow[1] = 0;
    diamondsRow[0] = 14;
    diamondsRow[1] = 0;
    spadesRow[0] = 27;
    spadesRow[1] =0;
    clubsRow[0] = 40;
    clubsRow[1] = 0;

I want to completely fill each array with non-repeating elements of the ArrayList.

2 Answers 2

1

You can make 4 for loops, from 0 to 11, 12 to 23, 24 to 35 and 36 to 47, and add in your lists.

for (int i = 0; i < 12; i++)
    heartsRow[i + 2] = solution.get(i);

for (int i = 0; i < 12; i++)
    diamondsRow[i + 2] = solution.get(i + 12);

for (int i = 0; i < 12; i++)
    spadesRow[i + 2] = solution.get(i + 24);

for (int i = 0; i < 12; i++)
    clubsRow[i + 2] = solution.get(i + 36);
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a counting loop over the list, increment the counter by 4 in each step, and assign elements to the arrays with adjusted offsets:

for (int i = 0; i + 3 < solution.size(); i += 4) {
  int j = i / 4;
  heartsRow[2 + j] = solution.get(i);
  diamondsRow[2 + j] = solution.get(i + 1);
  spadesRow[2 + j] = solution.get(i + 2);
  clubsRow[2 + j] = solution.get(i + 3);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.