Thursday, December 10, 2009

Odd Number Counter Finder 3000

So after bombing an Amazon technical interview because I couldn't remember syntax and the efficiencies of data structures, it seemed like a good idea to fix that. So here's the question and the code I'm going to say is correct. I'm still reviewing the java documentation, but if you have suggestions please comment.

Create and test a function that accepts a positive integer array and returns the value that appears an odd number of times. There should only be one integer in the array that has an odd number of occurences.

Here's some broken code below. I realize this accepts non-positive integers, has bad commenting, and other issues, but my biggest question is if I'm using the most efficient data structures.



RunTests.java




import java.lang.reflect.Array;
public class RunTests {
public static void main(String[] args) {
OddNumberFinder onf = new OddNumberFinder();

TestCase[] testCases = {
new TestCase(new int[] {1}, 1),
new TestCase(null, 0),
new TestCase(new int[] { 1, 1, 2, 2, 3 }, 3),
new TestCase(new int[] { 1, 1, 0, -1, -1 }, 0),
//new TestCase(new int[] { 'a', 'b', 'c' }, null),
//new TestCase(new int[] { }, null),
//new TestCase(new int[] { 1, 1 }, null)
};

for(int i = 0; i < testCases.length; i++) {
TestCase tc = testCases[i];
try {
System.out.print("For test set ");
System.out.print(tc.toString());
System.out.println(" the odd value is " +
onf.FindOddNumber(tc.numberSet));
}
catch (Exception e) {
System.out.println("Exception");
}
}
}
}


OddNumberFinder.java



import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.lang.Exception;

public class OddNumberFinder {
public OddNumberFinder() {
}

public int FindOddNumber(int[] numbers) throws Exception {
int numbersLength = numbers.length;

//ArrayList counts = new ArrayList(); // what do I use? map?
HashMap counts =
new HashMap(numbersLength);

for(int i = 0; i < numbersLength; i++) {
int key = numbers[i];
int newValue = 0;
if(counts.containsKey(key)) {
newValue = (Integer) counts.get(key) + 1;
}
else {
newValue = 1;
}
counts.put(key, newValue);
}
Set countSet = counts.entrySet();


Iterator i = countSet.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if((Integer)me.getValue()%2 != 0) {
return (Integer)me.getKey();
}
}

throw new Exception();
}
}


TestCase.java



public class TestCase {
public int length;
public int[] numberSet;
public int expectedValue;

public TestCase(int[] numberSet, int expectedValue) {
this.numberSet = numberSet;
this.expectedValue = expectedValue;
}

public String toString() {
String s = "{";
for(int i = 0; i < numberSet.length; i++) {
s += numberSet[i];
// Add a comma unless we have reached the last of the set.
if(i != numberSet.length - 1) s += ", ";
}
return s + "}";
}
}

0 Comments:

Post a Comment

<< Home