Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Is there anything wrong with this Java code?

  1. Oct 1, 2013 #1
    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.

    Code (Text):

    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);  
                 }
            }
               
        }          
    }
     
     
  2. jcsd
  3. Oct 1, 2013 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Whatever editor or IDE you are using, turn off the tabs. If you have a good editor or IDE, you can enter tabs but it should immediately translate them to spaces. Look at what you posted. Does that look professional? Does it follow the Java coding standard? Be honest.

    Always use braces, even for one-liners. This kind of coding will bite you one day.
    Code (Text):
    if (nums.contains(N - thisInt))
        output.printf("%d %d\n", thisInt, N - thisInt);
    What is to be done with duplicates? What if the user enters 1,1,1,7,7? Did you clarify the intent (requirements) with the interviewer?

    Finally, your code is an O(n*log(n)) algorithm. That's not near as bad as an O(n2) algorithm, but java supplies a HashSet that turns this into an O(n) algorithm.
     
  4. Oct 2, 2013 #3
    I have no idea what you mean by "Java coding standard." A lot of indentations did get screwed up when I copy-pasted my code.

    I thought it was considered elegant to use no braces on 1-line for, while and if statements.

    No, these were the instructions he emailed me:

    Write a simple java program. Given an array of integers stored in a file with one number per line, find all the pairs of integers that add up to 8. The output will also needs to be stored in a file with one pair per line.
    An example input array looks like this:
    3
    2
    4
    6
    5
    7
    20
    1

    The output will be like this:
    3 5
    2 6
    7 1



    Yea, I was thinking about doing that.
     
  5. Oct 2, 2013 #4

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Here's a link: http://www.oracle.com/technetwork/java/codeconv-138413.html [Broken]. It's been discussed in this forum, see [post]4496898[/post] and following.


    Exactly. The best way to ensure that indentation cannot get screwed up is to not have tabs in the source code. You can safely assume that people will use a monospaced font to look at your code, which means using spaces for whitespace is safe. The only thing you should assume about how tabs are handled is that they won't be handled how you use them. So either don't use them, or use an IDE/editor that translates tabs into spaces.


    In the 1970s when C was new? Yes. Nowadays? It's considered extremely bad form.


    He wanted to see what assumptions you made and how you handled them. You made an assumption regarding duplicates but you did not document that assumption anywhere. When people write requirements they never spell everything out. Never. One of your jobs as a programmer is to document up front any assumptions you have made in translating those requirements into code. Hidden assumptions in code have been the cause of an immense number of problems and disagreements.

    Where to spell them out? One good place is in the comments. It's good to place those assumptions up front rather than hidden deep within the code. In Java, that "up front" location would be in the javadoc commentary. You didn't use any javadoc style comments, which may be another reason that you didn't get a return call from the interviewer.
     
    Last edited by a moderator: May 6, 2017
  6. Oct 2, 2013 #5
    When I emailed him back, I told him that I assumed they had to be unique pairs because his example had a "4" in the input but no "4 4" in the output. I also told him that, although his example showed only positive integers, I made no assumption that we were dealing with only positive integers.

    I don't understand the point of vague instructions. I think I mentioned in this forum one of my interviews where all the guy asked was, "How do you find a word in a dictionary?" I didn't even know whether he was talking about a real-life dictionary or some data abstraction.
     
  7. Oct 2, 2013 #6

    Ibix

    User Avatar
    Science Advisor

    Neither do I, but they're more or less the only kind you ever get. Whether you handle that gracefully is one of the things they are testing...
     
    Last edited: Oct 2, 2013
  8. Oct 2, 2013 #7

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    A Michael Jackson song immediately came to mind:
    If They Say -
    Why, Why, Tell 'Em That Is Human Nature
    Why, Why, Does He Do Me That Way
    If They Say -
    Why, Why, Tell 'Em That Is Human Nature
    Why, Why, Does He Do Me That Way
     
  9. Oct 3, 2013 #8
    Well, the guy just invited me to an onsite interview. Time for a massive Java review session.
     
  10. Oct 3, 2013 #9

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Good luck!
     
  11. Oct 3, 2013 #10

    Mark44

    Staff: Mentor

    If you aren't clear what he means, ask for clarification. If you don't get clarification, make sure that you state what your assumptions are. One of the things that interviewers often look for is how well you deal with ambiguity.
     
  12. Oct 3, 2013 #11
    Sounds good.

    If I need to think about a programming question, should I tell them "I need a moment to think" and then mull it over silently until I have a clear answer, or should I always launch right into a think-out-loud, stream-of-consciousness answer that evolves? I feel like I did the latter in my last interview and it didn't go well as a result.
     
  13. Oct 3, 2013 #12

    Mark44

    Staff: Mentor

    "I need a moment to think" definitely seems better to me.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Is there anything wrong with this Java code?
Loading...