@ SuppressWarnings ( "unchecked" ) // This is not good code, but what's there to be done? TODO public static < T > T sample ( Counter < T > c , Random rand ) { Iterable < T > objects ; Set < T > keySet = c . keySet ( ) ; objects = c . keySet ( ) ; if ( rand == null ) { rand = new Random ( ) ; } else { // TODO: Seems like there should be a way to directly check if T is // comparable if ( ! keySet . isEmpty ( ) && keySet . iterator ( ) . next ( ) instanceof Comparable ) { List l = new ArrayList < T > ( keySet ) ; Collections . sort ( l ) ; objects = l ; } else { throw new RuntimeException ( "Results won't be stable since Counters keys are comparable." ) ; } } double r = rand . nextDouble ( ) * c . totalCount ( ) ; double total = 0.0 ; for ( T t : objects ) { // arbitrary ordering total += c . getCount ( t ) ; if ( total >= r ) return t ; } // only chance of reaching here is if c isn't properly normalized, or if // double math makes total<1.0 return c . keySet ( ) . iterator ( ) . next ( ) ; }
Does not assumes c is normalized .