jeudi 1 juin 2017

Normalizing random in Java based on associated weights

I have some tasks with some weights associated with them:

Task1:4
Task2:10
Task3:15
Task4:1
Task5:8
Task6:3
Task7:25
Task8:12
Task9:4
Task10:12
Task11:12
Task12:10
Task13:12
Task14:20
Task15:12
Task16:12

The sum of weights is not necessarily equal to 100. In above case its 172.

I am using the RandomCollection class from this answer

I have just added the following method to RandomCollection for fetching the map generated:

public NavigableMap<Double, E> getMap() {
        return map;
    }

This is my test class:

package com.mypackage;

import java.util.Map;

public class App {

    public static void main(String[] args){
        RandomCollection<String> randomCollection = new RandomCollection<String>();

        randomCollection.add(4 * 1.0/172, "Task1");
        randomCollection.add(10 * 1.0/172, "Task2");
        randomCollection.add(15 * 1.0/172, "Task3");
        randomCollection.add(1 * 1.0/172, "Task4");
        randomCollection.add(8 * 1.0/172, "Task5");
        randomCollection.add(3 * 1.0/172, "Task6");
        randomCollection.add(25 * 1.0/172, "Task7");
        randomCollection.add(12 * 1.0/172, "Task8");
        randomCollection.add(4 * 1.0/172, "Task9");
        randomCollection.add(12 * 1.0/172, "Task10");
        randomCollection.add(12 * 1.0/172, "Task11");
        randomCollection.add(10 * 1.0/172, "Task12");
        randomCollection.add(12 * 1.0/172, "Task13");
        randomCollection.add(20 * 1.0/172, "Task14");
        randomCollection.add(12 * 1.0/172, "Task15");
        randomCollection.add(12 * 1.0/172, "Task16");

        for (Map.Entry<Double, String> entry : randomCollection.getMap().entrySet()){
            System.out.println(entry.getValue() + " : " + entry.getKey());
        }
    }
}

I am multiplying by 1.0 for getting a double and dividing by 172 to normalize.

The output of above program is:

Task1 : 0.023255813953488372
Task2 : 0.08139534883720931
Task3 : 0.16860465116279072
Task4 : 0.17441860465116282
Task5 : 0.22093023255813957
Task6 : 0.23837209302325585
Task7 : 0.38372093023255816
Task8 : 0.4534883720930233
Task9 : 0.47674418604651164
Task10 : 0.5465116279069767
Task11 : 0.6162790697674418
Task12 : 0.6744186046511628
Task13 : 0.7441860465116279
Task14 : 0.8604651162790697
Task15 : 0.9302325581395349
Task16 : 1.0

Is this correct ?

I want RandomCollection.next() to return me a Task between Task1 and Task16; but as per its importance or associated weights. i.e. if I call RandomCollection.next() 172 times, 4 times Task1 should be returned, 10 times Task2 should be returned and so on.




Aucun commentaire:

Enregistrer un commentaire