Created
May 9, 2012 10:09
-
-
Save charleehu/2643524 to your computer and use it in GitHub Desktop.
Weight algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* $Id: WeightUtil.java 406 2012-08-14 07:44:42Z xiaowei.hu $ | |
* Copyright 2012-2014 Oak Pacific Interactive. All rights reserved. | |
*/ | |
package com.renren.socialgame.kp.util; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Random; | |
/** | |
* 权重util | |
* | |
* @author <a href="mailto:[email protected]">Xiaowei Hu</a> | |
* @version 1.0 2012-8-14 下午03:07:57 | |
* @since 1.0 | |
*/ | |
public class WeightUtil { | |
public static interface WeightObject<T> { | |
int getWeight(T t); | |
} | |
/** | |
* 通过权重值获取对象 | |
* | |
* @param <T> | |
* @param list | |
* @param obj | |
* @return | |
*/ | |
public static <T> T weight(List<T> list, WeightObject<T> obj) { | |
List<Integer> weightValue = new ArrayList<Integer>(); | |
for (T t : list) { | |
weightValue.add(obj.getWeight(t)); | |
} | |
return list.get(getIndexByWeight(weightValue)); | |
} | |
private static int getIndexByWeight(List<Integer> weight) { | |
int count = 0; | |
for (int i = 0; i < weight.size(); i++) { | |
count += weight.get(i).intValue(); | |
} | |
Random random = new Random(); | |
int seed = random.nextInt(count) + 1; | |
for (int i = 0; i < weight.size(); i++) { | |
int preSum = 0; | |
for (int j = i; j >= 0; j--) { | |
preSum += weight.get(j).intValue(); | |
} | |
if (preSum >= seed) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment