code: public static int getWeightedIndex (float[] weights, Random r)
      {
          float sum = 0.0f;
          for (float weight : weights) {
              if (weight < 0.0f) {
                  return -1;
              }
              sum += weight;
          }
  
          if (sum <= 0.0) {
              return -1;
          }
          float pick = getFloat(sum, r);
          for (int ii = 0, nn = weights.length; ii < nn; ii++) {
              pick -= weights[ii];
              if (pick < 0.0) {
                  return ii;
              }
          }
  
          log.warning("getWeightedIndex failed", new Throwable()); // Impossible!
          return 0;
      }
docs: Pick a random index from the array, weighted by the value of the corresponding array
  element.
  
  @param weights an array of non-negative floats.
  
  @return an index into the array, or -1 if the sum of the weights is less than or equal to
  0.0 or any individual element is negative.  For example, passing in {0.2, 0.0, 0.6, 0.8}
  will return:
  
  <pre>{@code
  0 - 1/8th of the time
  1 - never
  2 - 3/8th of the time
  3 - half of the time
  }</pre>