public int findClassIndex ( HashMap < Integer , Integer > weightMap ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "findClassIndex" ) ; int classPos = 0 ; int randWeight = 0 ; // First of all determine total weight int totalWeight = 0 ; Iterator < Integer > iter = weightMap . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Integer weight = iter . next ( ) ; totalWeight = totalWeight + weight . intValue ( ) ; } // TotalWeight might be zero if a zero weighting has been applied to a class. In // that case we need to return a zero classPos if ( totalWeight > 0 ) { // Generate a random number that is between zero and the total weight randWeight = Math . abs ( rand . nextInt ( ) % totalWeight ) ; // Iterate over the weightMap again so that we can find a class index to use. // We search for the index that corresponds to the generated random value. // // So if we had 3 classes with weights 7, 2 and 1, then we'll have a total // weight of 10 and will generate a pseudo random number between 0 and 10. The // code will see if the random number... // * is less than 7, in which case it chooses index 1, // * is between 7 and 9, in which case it chooses index 2, // * is between 9 and 10, in which case it chooses index 3. Iterator < Map . Entry < Integer , Integer > > iter2 = weightMap . entrySet ( ) . iterator ( ) ; // An aggregate of the weight int aggregateWeight = 0 ; while ( iter2 . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter2 . next ( ) ; Integer mappos = ( Integer ) entry . getKey ( ) ; Integer weight = ( Integer ) entry . getValue ( ) ; aggregateWeight = aggregateWeight + weight . intValue ( ) ; // Move the classPos to the next value classPos = mappos . intValue ( ) ; if ( randWeight <= aggregateWeight ) break ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "findClassIndex" , classPos ) ; return classPos ; }
Find a pseudo random classification index based on the weightings table .