Saturday, April 14, 2018

Today I'm taking a break from my previous post below on Java Interfaces to discuss a small coding question I came across  and post it here for thoughts:
/*
Implement a class with following methods
put( key, value );

delete( key );
getRandom(); // returns one of the values added randomly
Additional Requirements : No duplicates:
No dups.
    -    update existing
*/
public class MyNoDuplicateContainerWithGetRandom
{
    // for map based access
    private Dictionary<Object, Object>> dict;
    private List<Object> keys; // array
 
    public MyContainer() {
        dict = new Dictionary<Object, Object>> ();
        keys = new List<Object>();
    }
 
    public void put(Object key, Object value)
    {
        if (dict.ContainsKey(key)){
            dict[key] = value;
        }else
        {
            using(tr = new TransactionScope()){
            dict.Add(key, value);
            keys.Add(key);
            }
        }
    }
 
    public Object getRandom(){
        var r = new Random();     
        int index = r.Next(list.Count());
        Object key = keys[index];
        return dict[key];
    }
 
    public Object delete(Object key){
        if (dict.ContainsKey(key))
        {
                using (tr = new TransactionScope()){
                Object value = dict.Remove(key);
                list.Remove(key);
                }
        }
        return null;
    }

  • https://1drv.ms/w/s!Ashlm-Nw-wnWtheIEHpU4Jua0V79

No comments:

Post a Comment