Jump to content

RandomCollection (for antiban, random behavior, etc...)


Recommended Posts

Posted (edited)

Leeched from: http://stackoverflow.com/a/6409791

import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;

/**
 * @author 		Bjorn Krols (Botre)
 * @version		0.0
 * @since		April 27, 2015
 */

public class RandomCollection<Generic> {

	private final NavigableMap<Double, Generic> map;
	
    private final Random random;
    
    private double total = 0;

    public RandomCollection() {
        this(new Random());
    }

    public RandomCollection(Random random) {
        this.random = random;
        map = new TreeMap<Double, Generic>();
    }

    public void add(double weight, Generic result) {
        if (weight <= 0) return;
        total += weight;
        map.put(total, result);
    }

    public Generic get() {
        double value = random.nextDouble() * total;
        return map.ceilingEntry(value).getValue();
    }
	
}

public static void main(String[] args) {
	RandomCollection<String> rc = new RandomCollection<String>();
	rc.add(1, "1");
	rc.add(1, "2");
	System.out.println(rc.get());
	
}
Edited by Botre
  • Like 1
Posted

 

Leeched from: http://stackoverflow.com/a/6409791

import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;

/**
 * @author 		Bjorn Krols (Botre)
 * @version		0.0
 * @since		April 27, 2015
 */

public class RandomCollection<Generic> {

	private final NavigableMap<Double, Generic> map;
	
    private final Random random;
    
    private double total = 0;

    public RandomCollection() {
        this(new Random());
    }

    public RandomCollection(Random random) {
        this.random = random;
        map = new TreeMap<Double, Generic>();
    }

    public void add(double weight, Generic result) {
        if (weight <= 0) return;
        total += weight;
        map.put(total, result);
    }

    public Generic get() {
        double value = random.nextDouble() * total;
        return map.ceilingEntry(value).getValue();
    }
	
}

public static void main(String[] args) {
	RandomCollection<String> rc = new RandomCollection<String>();
	rc.add(1, "1");
	rc.add(1, "2");
	System.out.println(rc.get());
	
}

 

Hhm, what exactly does this do.

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...