Jump to content

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


Botre

Recommended Posts

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
Link to comment
Share on other sites

 

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.

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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