Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An efficient way to shuffle a JSON array in java?

Which would be the best way to do it? Right now, I convert my JSONArray to an ArrayList of a custom class, use Collections.shuffle() to perform the action, and convert back to JSONArray, which seems to be too much overhead.

The answer may be just to implement a Fisher-Yates shuffle for it, but my guess is that this may be already done so I would like to avoid reinventing the wheel. I looked at the standard JSON api and Google's Gson but they don't seem to have any implementation.

There are also simple options for a standard array in this question that could be easily ported to java, but I would gladly hear your input. I am amazed that the query http://www.google.com/search?q=java+shuffle+jsonarray did not flood me with methods.

like image 791
Aleadam Avatar asked Apr 03 '11 17:04

Aleadam


1 Answers

Sorry for posting an answer to my own question, but right now, since there was no out-of-the-box quick solution, I'm implementing my own static shuffle function based on the code from this post: Random shuffling of an array . Still looking forward to hear about the best implementation. This is what I did:

public static JSONArray shuffleJsonArray (JSONArray array) throws JSONException {
    // Implementing Fisher–Yates shuffle
        Random rnd = new Random();
        for (int i = array.length() - 1; i >= 0; i--)
        {
          int j = rnd.nextInt(i + 1);
          // Simple swap
          Object object = array.get(j);
          array.put(j, array.get(i));
          array.put(i, object);
        }
    return array;
}
like image 174
Aleadam Avatar answered Sep 22 '22 13:09

Aleadam