Shuffling a JSON array in Java The 2019 Stack Overflow Developer Survey Results Are...

What does "rabbited" mean/imply in this sentence?

Is domain driven design an anti-SQL pattern?

Are there any other methods to apply to solving simultaneous equations?

What is the best strategy for white in this position?

How are circuits which use complex ICs normally simulated?

Can't find the latex code for the ⍎ (down tack jot) symbol

What are the motivations for publishing new editions of an existing textbook, beyond new discoveries in a field?

Unbreakable Formation vs. Cry of the Carnarium

Evaluating number of iteration with a certain map with While

If the Wish spell is used to duplicate the effect of Simulacrum, are existing duplicates destroyed?

What do hard-Brexiteers want with respect to the Irish border?

How come people say “Would of”?

Inflated grade on resume at previous job, might former employer tell new employer?

What is the steepest angle that a canal can be traversable without locks?

Realistic Alternatives to Dust: What Else Could Feed a Plankton Bloom?

Is bread bad for ducks?

Deadlock Graph and Interpretation, solution to avoid

Does a dangling wire really electrocute me if I'm standing in water?

A poker game description that does not feel gimmicky

Inline version of a function returns different value then non-inline version

Output the Arecibo Message

"To split hairs" vs "To be pedantic"

How long do I have to send payment?

Why Did Howard Stark Use All The Vibranium They Had On A Prototype Shield?



Shuffling a JSON array in Java



The 2019 Stack Overflow Developer Survey Results Are InSimplification of byte array comparison algorithmShuffling an array of cardsShuffling a deckShuffling array elements in CShuffling a list of track indicesLogic for shuffling sliding puzzleShuffling chunks of ints in an arrayBasic Pong GameJava Market Summary - JSONShuffling an array keeping some elements fixed





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2












$begingroup$


Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.



What do you think? Can it be improved?



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;
}









share|improve this question











$endgroup$



















    2












    $begingroup$


    Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.



    What do you think? Can it be improved?



    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;
    }









    share|improve this question











    $endgroup$















      2












      2








      2





      $begingroup$


      Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.



      What do you think? Can it be improved?



      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;
      }









      share|improve this question











      $endgroup$




      Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.



      What do you think? Can it be improved?



      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;
      }






      java array json shuffle






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 4 '17 at 3:35









      Jamal

      30.6k11121227




      30.6k11121227










      asked Apr 4 '11 at 6:08









      AleadamAleadam

      11315




      11315






















          1 Answer
          1






          active

          oldest

          votes


















          2












          $begingroup$

          It runs in $O(n)$ time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.



          You might consider not using Object if you can use the type that's stored in the array instead.



          I also thought I read somewhere that it should be safe to loop to $n/2$ instead of $n$ (because you're swapping with elements from $1 cdots n$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)






          share|improve this answer











          $endgroup$













          • $begingroup$
            Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
            $endgroup$
            – Aleadam
            Apr 4 '11 at 15:30










          • $begingroup$
            @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
            $endgroup$
            – FrustratedWithFormsDesigner
            Apr 4 '11 at 15:36












          • $begingroup$
            I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
            $endgroup$
            – leemes
            May 17 '12 at 20:58












          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f1640%2fshuffling-a-json-array-in-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2












          $begingroup$

          It runs in $O(n)$ time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.



          You might consider not using Object if you can use the type that's stored in the array instead.



          I also thought I read somewhere that it should be safe to loop to $n/2$ instead of $n$ (because you're swapping with elements from $1 cdots n$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)






          share|improve this answer











          $endgroup$













          • $begingroup$
            Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
            $endgroup$
            – Aleadam
            Apr 4 '11 at 15:30










          • $begingroup$
            @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
            $endgroup$
            – FrustratedWithFormsDesigner
            Apr 4 '11 at 15:36












          • $begingroup$
            I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
            $endgroup$
            – leemes
            May 17 '12 at 20:58
















          2












          $begingroup$

          It runs in $O(n)$ time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.



          You might consider not using Object if you can use the type that's stored in the array instead.



          I also thought I read somewhere that it should be safe to loop to $n/2$ instead of $n$ (because you're swapping with elements from $1 cdots n$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)






          share|improve this answer











          $endgroup$













          • $begingroup$
            Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
            $endgroup$
            – Aleadam
            Apr 4 '11 at 15:30










          • $begingroup$
            @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
            $endgroup$
            – FrustratedWithFormsDesigner
            Apr 4 '11 at 15:36












          • $begingroup$
            I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
            $endgroup$
            – leemes
            May 17 '12 at 20:58














          2












          2








          2





          $begingroup$

          It runs in $O(n)$ time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.



          You might consider not using Object if you can use the type that's stored in the array instead.



          I also thought I read somewhere that it should be safe to loop to $n/2$ instead of $n$ (because you're swapping with elements from $1 cdots n$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)






          share|improve this answer











          $endgroup$



          It runs in $O(n)$ time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.



          You might consider not using Object if you can use the type that's stored in the array instead.



          I also thought I read somewhere that it should be safe to loop to $n/2$ instead of $n$ (because you're swapping with elements from $1 cdots n$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 5 hours ago









          esote

          3,02611241




          3,02611241










          answered Apr 4 '11 at 15:15









          FrustratedWithFormsDesignerFrustratedWithFormsDesigner

          484210




          484210












          • $begingroup$
            Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
            $endgroup$
            – Aleadam
            Apr 4 '11 at 15:30










          • $begingroup$
            @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
            $endgroup$
            – FrustratedWithFormsDesigner
            Apr 4 '11 at 15:36












          • $begingroup$
            I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
            $endgroup$
            – leemes
            May 17 '12 at 20:58


















          • $begingroup$
            Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
            $endgroup$
            – Aleadam
            Apr 4 '11 at 15:30










          • $begingroup$
            @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
            $endgroup$
            – FrustratedWithFormsDesigner
            Apr 4 '11 at 15:36












          • $begingroup$
            I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
            $endgroup$
            – leemes
            May 17 '12 at 20:58
















          $begingroup$
          Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
          $endgroup$
          – Aleadam
          Apr 4 '11 at 15:30




          $begingroup$
          Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using JSONObject instead of Object but then I changed it to make it more reusable. What would be the advantage of using JSONObject instead?
          $endgroup$
          – Aleadam
          Apr 4 '11 at 15:30












          $begingroup$
          @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
          $endgroup$
          – FrustratedWithFormsDesigner
          Apr 4 '11 at 15:36






          $begingroup$
          @Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use Object, but I don't know if you can do that with JSONArray.
          $endgroup$
          – FrustratedWithFormsDesigner
          Apr 4 '11 at 15:36














          $begingroup$
          I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
          $endgroup$
          – leemes
          May 17 '12 at 20:58




          $begingroup$
          I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array.
          $endgroup$
          – leemes
          May 17 '12 at 20:58


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f1640%2fshuffling-a-json-array-in-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

          How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

          Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...