0

I have written a coding challenge. The requirement of the challenge is reversing the particular words in a sentence => still keep the oder the of the words in the sentence but reverse the characters of the word.

The input sample is something like this: RemoteIo is awesome-Candiates pass interview-best candiates are selected.

The sample output of the input above:

oIetomeR si emosewa 
setaidnaC ssap weivretni 
tseb setaidnac era detceles

As you can see the input sentences are separated by the - character so that mean we have 3 sentences in the example above and the sentence just able to contain anphabet characters and blank space only (one blank space between two words)

So my question is how can I optimize the below code and there is any theory/principle about Code Optimization. My code implementation in Java:

public class Test1 {
    public static void main (String[] args) throws java.lang.Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        
        // Put sentences to a String array.
        String[] data = input.split("-");
        
        // Loop throw sentence array
        for(int i = 0; i < data.length; i++) {
            
            // Put the words from the sentence to a String array.
            String[] words = data[i].split(" ");
            
            // Loop throw the word array
            for(int w = 0; w < words.length; w++) {
                
                // Revert the characters of each word
                for (int j = words[w].length() - 1;  j >=0; j--) {
                    if (j != 0) {
                        System.out.print(words[w].charAt(j));
                    } else {
                        System.out.print(words[w].charAt(j) + " ");
                    }
                }
                if ( w == words.length -1) {
                    System.out.println();
                }
            }
        }
    }
}
Hoang Nguyen
  • 61
  • 1
  • 13
  • 2
    It's almost always a bad idea to mix printing commands in with your logic in something like this. Map words to their reverse and then join them with a space, don't try to print spaces as you go, you'll just give yourself a headache. – Edward Peters Nov 22 '22 at 16:37
  • 1
    Do you have a reason to believe your code is insufficiently optimized? To me it looks perfectly reasonable. A good rule is to pick a good algorithm but don't worry about further optimization until you need to. – Edward Peters Nov 22 '22 at 16:39
  • @EdwardPeters My reviewer asked me to optimize my this code so I don't know where to start. – Hoang Nguyen Nov 22 '22 at 17:01
  • "Reviewer" as in code reviewer at work, fellow student...? There's a lot of cleanup I'd make you do on this, but I question the judgement of anyone telling you this needs to be more optimized from a performance standpoint. – Edward Peters Nov 22 '22 at 17:06
  • @EdwardPeters yes I think he is talking about performance otimization so do you think we can optimize this code to make it has better performance. And do we have any theory /principle about code optimization. – Hoang Nguyen Nov 22 '22 at 17:15
  • 1
    "And do we have any theory /principle about code optimization." - yes, vast libraries of theory, far too much to cover in an SO question. But no, for performance, there's nothing worthwhile to do here. That's usually the case - simple code tends to be fast, and for low-level stuff, optimization is the compiler's job, not yours. – Edward Peters Nov 22 '22 at 17:20
  • Again, are we talking about a coworker doing a code review at work, a fellow student you asked to look over your code, a TA...? I think either you're misunderstanding them or they're incorrect. – Edward Peters Nov 22 '22 at 17:21
  • Context is important here. If you're taking a class on low-level optimizations then A: why on earth is it being taught in Java? but also B: You might be able to re-arrange a couple things to shave off a bit. Literally any other context, those optimizations are a waste of time and will make more confusing, worse code. – Edward Peters Nov 22 '22 at 17:23
  • Oh, one thing you should do is pull the `if` statements that refer to the loop index variables out - those should just run unconditionally after the loop. Technically that's an optimization, as you're running the if check fewer times, but mostly it's just cleaner. – Edward Peters Nov 22 '22 at 17:27
  • 1
    One questionable optimization for reversing words would be to use a stack to reverse them (store the whole word in a stack, read the stack to get reversed word out). An additional improvement would be to use a StringBuffer to hold your solution rather than print it out character by character. – Shark Nov 22 '22 at 17:46
  • @EdwardPeters "yes, vast libraries of theory" can you list out some keywors then I will research them separately. – Hoang Nguyen Nov 22 '22 at 18:07
  • @EdwardPeters "Again, are we talking about a coworker doing a code review at work, a fellow student " he is my coworker and he is my manager. – Hoang Nguyen Nov 22 '22 at 18:08
  • 2
    @HoangNguyen since he's reviewing your code, and probably left a "plesae optimize this part" comment on this piece of code, could you ask him to "could you please clarify, what sort of improvement did you have in mind? what's actually wrong with it?" – Shark Nov 22 '22 at 18:09
  • 1
    If you just want to start researching all of optimization, google "Program optimization", but it's really a huge and diverse field - wikipedia will be a better signpost for you than I can be. – Edward Peters Nov 22 '22 at 18:10
  • If you want my advice, apply the change I described in my answer, test it to make sure everything works, and then you'll have something to show him when you ask for further clarification. – Edward Peters Nov 22 '22 at 18:11
  • No, you don't want to start by just researching all optimization, or all sorts of optimization, especially with java because even measuring the optimization percentage in java will require you to warm up the code so you can actually see how much of a difference your changes made - and you usually warm up the code by running it 100k but more likely 5mil times before you even get to measure and see changes. Optimization percentage isn't trivial to get out from Java like it is with C :D – Shark Nov 22 '22 at 18:12
  • 1
    See [link1](https://stackoverflow.com/questions/8939299/java-optimize-code), [link2](https://stackoverflow.com/questions/5666621/how-to-optimize-the-code-in-my-java-application), [link3](https://stackoverflow.com/questions/60220417/how-to-optimize-this-code-to-make-it-faster), [link4](https://stackoverflow.com/questions/1481853/technique-or-utility-to-minimize-java-warm-up-time), [link5](https://stackoverflow.com/questions/36198278/why-does-the-jvm-require-warmup). That will get you somewhat started on the complex matter of nontriviality when it comes to serious java optimization. – Shark Nov 22 '22 at 18:17
  • There are also [link6](https://stackoverflow.com/questions/5981460/optimization-by-java-compiler), dubious [external link7](https://www.geeksforgeeks.org/12-tips-to-optimize-java-code-performance/) and [link8](https://stackoverflow.com/questions/36198278/why-does-the-jvm-require-warmup) - and you've just started to enter the rabbit hole. So, just ask your coworker on what he thinks is subotimal about your thing, and then work together from there. You're a team. – Shark Nov 22 '22 at 18:20
  • 2
    To be clear, I don't actually recommend "research all of it" either, I just think that's as good as anything for where you're at. The most important lesson right now is to not be concerned with premature optimization, and to focus more on readability, maintainability and correctness. – Edward Peters Nov 22 '22 at 18:20

1 Answers1

1

The following code is bad: having ifs that refer to the loop variable is confusing and technically, maybe very slightly slower than the right way (though the compiler might just fix that for you.) // Loop throw the word array for(int w = 0; w < words.length; w++) {

                // Revert the characters of each word
                for (int j = words[w].length() - 1;  j >=0; j--) {
                    if (j != 0) {
                        System.out.print(words[w].charAt(j));
                    } else {
                        System.out.print(words[w].charAt(j) + " ");
                    }
                }
                if ( w == words.length -1) {
                    System.out.println();
                }
            }

Instead do:

  // Loop throw the word array
                for(int w = 0; w < words.length; w++) {
                    // Revert the characters of each word
                    for (int j = words[w].length() - 1;  j >0; j--) {
                        System.out.print(words[w].charAt(j) + " ");
                    }
                    System.out.print(words[w].charAt(j));
                }
                System.out.println();

Notice how I changed the j>=0 to j>0. The else block would only have triggered on the last repetition, so this is semantically equivalent.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39