public int randomIndexChoice ( List < Integer > weights ) { int result = 0 , index ; double maxKey = 0.0 ; double u , key ; int weight ; for ( ListIterator < Integer > it = weights . listIterator ( ) ; it . hasNext ( ) ; ) { index = it . nextIndex ( ) ; weight = it . next ( ) ; u = random . nextDouble ( ) ; key = Math . pow ( u , ( 1.0 / weight ) ) ; // Protect from zero division? if ( key > maxKey ) { maxKey = key ; result = index ; } } return result ; }
Returns an integer at random weighted according to its index