home

java


package oddfinder;

import java.util.HashMap;
import java.util.Iterator;

//blame: shardy@@differentchairs.com

public class Main {

    /**
     * find a value in the given list that occurs an odd number of times
     */
    public static Integer findOddCount(Integer [] val)
	{
		Integer ct = null;
		HashMap bucket = new HashMap();
		for (int i=0; i<val.length; i++)
		{
			ct = (Integer) (bucket.get( val[i] ));
			int newCt = null==ct? 1 : ct.intValue()+1;
			bucket.put(val[i],new Integer(newCt) );
		}
		Iterator vkey = bucket.keySet().iterator();
		while (vkey.hasNext())
		{
			Integer v = (Integer)vkey.next();
			ct = (Integer)bucket.get(v);
			if (1==(ct.intValue()%2))
			{
				return v;
			}
		}
		return null;
	}

	public static void main(String args[]){
		Integer a1[]= {1,1,2,2,3,3,4,4,5,5,6,7,7,7,7};
		Integer a2[]= {10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10};
		Integer a3[]= {6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10};
		Integer a4[]= {10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6};
		Integer a5[]= {6,6};
		Integer a6[]= {1};

		System.out.println("odd value in a1 is " + findOddCount(a1));
		System.out.println("odd value in a2 is " + findOddCount(a2));
		System.out.println("odd value in a3 is " + findOddCount(a3));
		System.out.println("odd value in a4 is " + findOddCount(a4));
		System.out.println("odd value in a5 is " + findOddCount(a5));
		System.out.println("odd value in a6 is " + findOddCount(a6));
	}
}