Randomly iterate over ArrayList in Java

后端 未结 5 1384
滥情空心
滥情空心 2020-12-30 14:36

Seems a very basic question. I\'ve an ArrayList al and I would like to iterate over it. Normally,

for(int i : al) {
    // some c         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 14:55

    Use the following class:

    import java.util.Enumeration;
    import java.util.Random;
    
    public class RandomPermuteIterator implements Enumeration {
        int c = 1013904223, a = 1664525;
        long seed, N, m, next;
        boolean hasNext = true;
    
        public RandomPermuteIterator(long N) throws Exception {
            if (N <= 0 || N > Math.pow(2, 62)) throw new Exception("Unsupported size: " + N);
            this.N = N;
            m = (long) Math.pow(2, Math.ceil(Math.log(N) / Math.log(2)));
            next = seed = new Random().nextInt((int) Math.min(N, Integer.MAX_VALUE));
        }
    
        public static void main(String[] args) throws Exception {
            RandomPermuteIterator r = new RandomPermuteIterator(100);
            while (r.hasMoreElements()) System.out.print(r.nextElement() + " ");
            //output:50 52 3 6 45 40 26 49 92 11 80 2 4 19 86 61 65 44 27 62 5 32 82 9 84 35 38 77 72 7 ...
        }
    
        @Override
        public boolean hasMoreElements() {
            return hasNext;
        }
    
        @Override
        public Long nextElement() {
            next = (a * next + c) % m;
            while (next >= N) next = (a * next + c) % m;
            if (next == seed) hasNext = false;
            return  next;
        }
    }
    

提交回复
热议问题