Пример #1
0
  /**
   * 按照权重随机一个对象
   *
   * @param objList
   * @param objWeight
   * @return
   */
  public static <T> T randonWeightObject(List<T> objList, List<Integer> objWeight) {
    if (objList == null || objWeight == null || objList.size() != objWeight.size()) {
      throw new RuntimeException("random weight object exception");
    }

    // 累加权重
    int totalWeight = 0;
    List<Integer> fmtWeight = new ArrayList<Integer>(objWeight.size());
    for (int i = 0; i < objWeight.size(); i++) {
      totalWeight += objWeight.get(i);
      fmtWeight.add(totalWeight);
    }

    try {
      int randomWeight = GameRand.randInt(1, totalWeight);
      for (int i = 0; i < fmtWeight.size(); i++) {
        if (randomWeight <= fmtWeight.get(i)) {
          return objList.get(i);
        }
      }
    } catch (Exception e) {
      GameMonitor.catchException(e);
    }
    return null;
  }
Пример #2
0
 /**
  * 队列乱序
  *
  * @param objList
  */
 public static <T> void randomOrder(List<T> objList, int calcTimes) {
   for (int i = 0; i < calcTimes; i++) {
     for (int j = 0; j < objList.size(); j++) {
       try {
         int exchangeIdx = GameRand.randInt(0, objList.size() - 1);
         if (exchangeIdx != j) {
           T obj = objList.get(j);
           objList.set(j, objList.get(exchangeIdx));
           objList.set(exchangeIdx, obj);
         }
       } catch (Exception e) {
         GameMonitor.catchException(e);
       }
     }
   }
 }
Пример #3
0
  /**
   * 按照权重随机n个对象
   *
   * @param objList
   * @param objWeight
   * @return
   */
  public static <T> List<T> randonWeightObject(
      List<T> objList, List<Integer> objWeight, int count) {
    if (objList == null
        || objWeight == null
        || count <= 0
        || objList.size() != objWeight.size()
        || count > objList.size()) {
      throw new RuntimeException("random weight object exception");
    }

    List<Integer> objWeightStub = new ArrayList<Integer>(objWeight.size());
    objWeightStub.addAll(objWeight);
    List<T> selObjList = new ArrayList<T>(count);
    while (selObjList.size() < count) {
      // 累加权重
      int totalWeight = 0;
      List<Integer> fmtWeight = new ArrayList<Integer>(objWeightStub.size());
      for (int i = 0; i < objWeightStub.size(); i++) {
        totalWeight += objWeightStub.get(i);
        fmtWeight.add(totalWeight);
      }

      try {
        int randomWeight = GameRand.randInt(1, totalWeight);
        for (int i = 0; i < fmtWeight.size(); i++) {
          if (randomWeight <= fmtWeight.get(i)) {
            selObjList.add(objList.get(i));
            objWeightStub.set(i, 0);
            break;
          }
        }
      } catch (Exception e) {
        GameMonitor.catchException(e);
      }
    }
    return selObjList;
  }