My game server class library -- randomly select one or n objects by weight

Source: Internet
Author: User
Select by weight

When writing game servers, you often encounter similar requirements: from the listRandomSelect one or more entriesWeight(The higher the weight, the more likely it is to be selected ). For example, you can kill a monster from an equipment list. This requirement is similar to the lucky big turntable in real life:

Algorithm Implementation

This requirement is common, so I want to write it more commonly. First, the interfaceWeightedIndicates the object with a weight value,Getweight ()Method return weight:

public interface Weighted {    public int getWeight();}
WeightedbaseIs the abstract Implementation of the weighted interface:

public abstract class WeightedBase implements Weighted {        private final int weight;    public WeightedBase(int weight) {        if (weight <= 0) {            throw new IllegalArgumentException("weight <= 0!");        }        this.weight = weight;    }    @Override    public int getWeight() {        return weight;    }    }
WeightedintAn integer that indicates the value of the ownership:

Public class weightedint extends weightedbase {private final int value; Public weightedint (INT weight, int value) {super (weight); this. value = value;}/*** returns an integer. * @ return */Public int getvalue () {return value ;}}

Because not every class can implement the weighted interface or inherit weightedbase (such as the class in a third-party library ),WeightfunctionInterface to represent the weight calculation function,Apply ()The method calculates the weight of a given object:

public interface WeightFunction<T> {    public int apply(T t);}
Finally, tool class WeightutilThe specific selection algorithm is implemented in this class. The method list of this class is as follows:

public class WeightUtil {    public static <T extends Weighted> List<T> select(List<T> list, int n)    public static <T> List<T> select(List<T> list, int n, WeightFunction<T> wf)    public static <T extends Weighted> T selectOne(List<T> list)    public static <T extends Weighted> T selectOne(List<T> list, int randomInt)    public static <T> T selectOne(List<T> list, WeightFunction<T> wf)    public static <T> T selectOne(List<T> list, int randomInt, WeightFunction<T> wf)}
The most important method is to receive three parameters. Selectone ()Other methods depend on this method. The Code is as follows:

    public static <T> T selectOne(List<T> list, int randomInt, WeightFunction<T> wf) {        if (list.isEmpty()) {            throw new IllegalArgumentException("empty list!");        }        if (randomInt < 0) {            throw new IllegalArgumentException("negative randomInt: " + randomInt);        }        if (list.size() == 1) {            return list.get(0);        }                int weightSum = 0;        for (T obj : list) {            weightSum += wf.apply(obj);            if (weightSum > randomInt) {                return obj;            }        }                String msg = String.format("total weight (%d) <= randomInt (%d)", weightSum, randomInt);        throw new IllegalArgumentException(msg);    }

GitHub Project

To complete the code, clone my GitHub project. This article is just the beginning, hoping to put more code into this project in the future.


My game server class library -- randomly select one or n objects by weight

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.