algorithm - Java-Randomized Queue Iterator Causes Invalid Range Exception -
i have implementation of randomized queue in java. although enqueue, dequeue , sample operations work fine, iterator causes invalid range exception thrown every time in shuffle method.
i not understand why since random number generation in shuffle()
method bound size of queue. here code:
private int n=0; private item[] queue; public randomizedqueue(){ queue= (item[]) new object[8]; } // construct empty randomized queue public boolean isempty(){ return n==0; } // queue empty? public int size(){ return n; }// return number of items on queue private void resize(int capacity){ item[] copy=(item[]) new object[capacity]; for(int i=0;i<n;i++){ copy[i]=queue[i]; } queue=copy; } private class queueiterator implements iterator<item>{ int i=0; public queueiterator(){ if(n>0){ shuffle(); } } @override public boolean hasnext() { return i<n; } @override public item next() { item item=queue[i]; i++; return item; } @override public void remove() { throw new java.lang.unsupportedoperationexception("remove not supported"); } } public void enqueue(item item){ if(item==null){ throw new java.lang.nullpointerexception("can't insert null items"); } if(n==queue.length){ resize(2*queue.length); } queue[n++]=item; } // add item public item dequeue(){ if(isempty()){ throw new java.util.nosuchelementexception("queue empty"); } int i=stdrandom.uniform(0, n); item item=queue[i]; exchange(i,n-1); n=n-1; queue[n]=null; return item; } // remove , return random item public item sample(){ if(isempty()){ throw new java.util.nosuchelementexception("queue empty"); } int i=stdrandom.uniform(0,n); return queue[i]; } // return (but not remove) random item public iterator<item> iterator(){ return new queueiterator(); } // return independent iterator on items in random order private void exchange( int i, int j){ item swap=queue[i]; queue[i]=queue[j]; queue[j]=swap; } private void shuffle(){ for(int i=0;i<n;i++){ int j=stdrandom.uniform(0, i); exchange(i,j); } }
in method shuffle()
:
private void shuffle(){ for(int i=0;i<n;i++){ int j=stdrandom.uniform(0, i); exchange(i,j); } }
in first iteration, when call stdrandom.uniform(0, 0)
, throws exception because second argument must strictly greater first. should change for
loop minimum value i
1.
from documentation:
uniform
public static int uniform(int a, int b)
returns integer uniformly in [a, b).
throws:
illegalargumentexception - if b <= a
illegalargumentexception - if b - >= integer.max_value
Comments
Post a Comment