Learn AP Comp Sci

Problem of the Day

Problem:

Assume that the ArrayList utility has been imported. What does the following static method do?

public static void unknown(String[] arr)
{
ArrayList<String> arr2 = new ArrayList<String>();
for (String el : arr)
arr2.add(el);
for (int i = 0; i < arr.length; i++)
arr[i] = arr2.remove( (int) (Math.random() * arr2.size()));
}
  1. Rearranges the elements of arr into a random order
  2. Copies the elements of arr into arr2 in random order
  3. Removes the items from arr in a random order
  4. Moves a random element from arr to the beginning of the Array

Show solution:

The correct answer is a. The elements from arr are copied into an ArrayList, then randomly removed from that List one at a time and put into arr again. The original values of arr have been replaced with identical values, now in a different order.