Java random shuffle list with two elements using Collections.shuffle -


import java.util.arraylist; import java.util.arrays; import java.util.collections; import java.util.random;  public class shufflelist {   public static void main(string[] args) {     string [] file = {"1","2"};     long seed = 3;     arraylist<string> filelist = new arraylist<string>(arrays.aslist(file));     (int i=0; i<200; i++) {       collections.shuffle(filelist, new random(seed));       seed = seed +1;       system.out.println(seed + "," + filelist);     }   } } 

the output 200 lines of [1,2], not random shuffle @ all. in fact true seed < 4000. why that? tried list of 3 elements , seeds 1 100 makes list seemingly random. what's wrong list of 2 elements?

the problem isn't shuffle - it's random small seeds. here's program demonstrating that:

import java.util.random;  public class test {     public static void main(string[] args) {         int total = 0;         (int seed = 0; seed < 4000; seed++) {             random rng = new random(seed);             total += rng.nextint(2);         }         system.out.println(total);     } } 

you'd expect output of 2000 - half calls nextint should return 0, , half should return 1. instead, it's 4000 - every call returns 1.

using seeds [10000, 13999) 240 - vastly more of calls return 0 1.

using seeds [100000, 103999) 3226 - getting bit better...

using seeds [1000000, 1003999) 2105 - better.

i don't know enough maths of rngs why happens, java.util.random kinda broken small seeds.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -