- #1
- 986
- 12
I had a phone interview with a guy and I thought it went well. At the end he told me to send him a Java program that reads from a file containing a list of integers, one per line, and prints out all the pairs that sum to 8. I thought I made a pretty good algorithm that finds all the pairs that sum to N. I thought I organized it and commented it well.
Anyways, he hasn't got back to me in a few days, so he must think it sucks or something.
Anyways, he hasn't got back to me in a few days, so he must think it sucks or something.
Code:
import java.util.*;
import java.io.*;
public class SumToN {
// N: The integer sum to which we want to search for
// distinct integer pairs
public static final int N = 8;
public static void main(String[] args) throws FileNotFoundException {
// "Numbers.txt" must be in the directory and must contain
// on each line exactly 1 integer
Scanner input = new Scanner(new File("Numbers.txt"));
// Output will be saved in the directory as "Sum_Pairs.txt"
PrintStream output = new PrintStream(new File("Sum_Pairs.txt"));
/* Algorithm:
Create an instance of a binary tree which will act as
a set to hold all the integers from the input.
Then check, for each integer K in the input, whether K is
already in the tree; if it's not, add it, but first output
K and (N - K) if (N - K) is in the tree.
*/
Set<Integer> nums = new TreeSet<Integer>();
while (input.hasNextInt()) {
int thisInt = input.nextInt();
if (!nums.contains(thisInt)) {
if (nums.contains(N - thisInt))
output.printf("%d %d\n", thisInt, N - thisInt);
nums.add(thisInt);
}
}
}
}