3
\$\begingroup\$

I implemented this method and wanted to get suggestions and or improvements. The objective of the method is to print the even and odd indexes of Strings contained within an array. Each set of indexes(even and odd) should be seperated by a space.

public static void printEvenOddIndexes(String[] strings){

    for(int i = 0; i < strings.length;i++){
        String word = strings[i];
        ArrayList<Integer> oddIndexes  = new ArrayList<>();
        for(int j= 0; j < word.length();j++){
            if(j % 2 == 0){
                System.out.print(word.charAt(j));
            }else{
                oddIndexes.add(j);
            }
        }
        System.out.print(" ");
        for(Integer index : oddIndexes){
            System.out.print(word.charAt(index));
        }
        System.out.println();
    }
 }
\$\endgroup\$
4
\$\begingroup\$

Printing the characters at the even and odd indexes sounds like two similar tasks. So the code for these tasks should look very similar. You can either extract that code to a separate method, or, since it is very simple, just write the code twice.

public static void printEvenOddIndexes(String[] strings) {          
    for (String word : strings) {

        for (int i = 0; i < word.length(); i += 2) {
            System.out.print(word.charAt(i));
        }

        System.out.print(" ");

        for (int i = 1; i < word.length(); i += 2) {
            System.out.print(word.charAt(i));
        }

        System.out.println();
    }
 }

The two loops only differ by the starting index. Note the += 2 at the end of the for loop.

\$\endgroup\$
  • \$\begingroup\$ Is it consider as O(n) or O(n square) time complexity, because of using two for loops ? \$\endgroup\$ – Maulik Sakhida Aug 10 at 3:11
  • \$\begingroup\$ As always: it depends on what you define \$n\$ as. If it's the total length of all strings, \$\mathcal O(n)\$. If you take into account that Java arrays and strings have a fixed upper length limit, it's even \$\mathcal O(1)\$. \$\endgroup\$ – Roland Illig Aug 10 at 20:17
2
\$\begingroup\$

I agree with Roland Illig but just for funsies let's see how to slighlty improve your choice of a one (inner) for loop solution. (well, one loop to decide which are even and which are odd).

First improvement is using a foreach statement on the words like Panayiotis Poularakis suggests:

for(String word : words) {

This saves us the hassle of dealing with an index we don't need.

Next we can store the characters in the odd possitions into a new "word" instead of storing the indices and then looping the string again to handle those. I suggest using a StringBuilder:

StringBuilder oddChars = new StringBuilder();
for(int j = 0; j < word.length();j++){
    if(j % 2 == 0){
        System.out.print(word.charAt(j));
    }else{
        oddIndexes.add(j);
    }
}

Last let's also get rid of the index here and instead loop over all chars while using a boolean to keep track if this one is on an even index or not:

private static void printEvenOddIndices(String[] words){
    for(String word : words){
        boolean even = true;
        StringBuilder oddChars = new StringBuilder();
        for(char c : word.toCharArray()){
            if(even){
                System.out.print(c);
            } else {
                oddChars.append(c);
            }
            even = !even;
        }
        System.out.println(" " + oddChars);
    }
}

Testing this with

public static void main(String[] args) {
    printEvenOddIndices(new String[]{"a", "aba", "ababa"});
}

resulted in

a
aa b
aaa bb


last minor note: the plural of index is indices.

\$\endgroup\$
1
\$\begingroup\$

You can simplify your method, avoiding the use of the ArrayList to keep track of the odd indices, the if statement and the third loop by using a simple method to print the chars with an offset and increment value e.g.

 void print(char[] strings, int offset, int increment) {
   while(offset < strings.length) {
       System.out.print(strings[offset]);
       offset += increment;
   }
}

you could then call this from your main method as:

print(chars, 0, 2);

to print the even indices, and setting the offset to 1, will print the odd ones

Of course you should add validation to the input parameters of this method, checking that the offset is within the bounds of the array etc.

You could also replace the first for loop, with a foreach statemnet

for(String word: strings)

since the i index is not used.

\$\endgroup\$
  • \$\begingroup\$ Why should there be any validation code? This is a privately used method, therefore it should be short and concise. \$\endgroup\$ – Roland Illig Jul 11 '17 at 6:54
  • \$\begingroup\$ you are right for the context of this example keeping the method as private is enough, hence no validation is actually necessary \$\endgroup\$ – Panayiotis Poularakis Jul 11 '17 at 7:17
  • \$\begingroup\$ this is definitely the right answer, i would recommend some null checks but generalizing the task is a great idea \$\endgroup\$ – downrep_nation Jul 11 '17 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.