commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Othmen Tiliouine <tiliouine.oth...@gmail.com>
Subject [Bag] random pick
Date Mon, 11 Mar 2013 23:16:17 GMT
Hello,

I just saw the Bag interface and its implementations, I'm surprised that Bag
<T> (and none of these implementations) expose the method
public T pick() and public T pickAndRemit() (pick a random element)
The Bag object we see in nature, it is mainly used to this, that's why
it is widely
used in the probability that when I met 2 white balls and one black, when I
draw a ball randomly I have 2 times more likely to have a white ball

I think that if this caracteristic exists it would be very valuable.


this is a simple implementation of pick() and pickAndRemit() with HashBag

package com.otiliouine.commons.collections;

import java.util.Iterator;

import org.apache.commons.collections.bag.HashBag;

public class OpaqueHashBag extends HashBag implements OpaqueBag {

    public Object pcik() {
        if (size() == 0) {
            return null;
        }
        int randomIndex = (int) (Math.random() * size());
        int searchIndex = randomIndex;

        Iterator iterator = this.iterator();
        //iterator = this.map.keySet().iterator()
        Object selectedItem = iterator.next();
        int count;

        while (searchIndex > 0) {
            searchIndex --;
            selectedItem = iterator.next();
        }
//        while ((count = getCount(selectedItem)) < searchIndex + 1) {
//            searchIndex -= count;
//            selectedItem = iterator.next();
//        }
        return selectedItem;
    }

    public Object pickAndRemit() {
        Object picked = pcik();
        if (picked != null) {
            remove(picked, 1);
        }
        return picked;
    }
}



it can be optimized if it is writen in AbstractMapBag class

and this is the test

public class TestOpaqueHashBag {

    private OpaqueHashBag bag;

    public static void main(String ... args) {
        TestOpaqueHashBag t = new TestOpaqueHashBag();
        t.before();
        t.testpick();
    }

    public void before(){
        bag = new OpaqueHashBag();
        bag.add("white", 6);
        bag.add("black", 3);
        bag.add("red", 1);
    }

    public void testpick() {
        int w = 0, b = 0, r = 0;
        for (int i = 0; i < 1000; i++) {
            String ball = (String) bag.pcik();

            if (ball.equals("white")) {
                w ++;
            } else if (ball.equals("black")) {
                b ++;
            } else {
                r ++;
            }
        }
        System.out.println("%white = " + w/10);
        System.out.println("%black = " + b/10);
        System.out.println("%red = " + r/10);
    }

}

output :

%white = 59
%black = 30
%red = 9


Othmen TILIOUINE

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message