M
M
MrBe2015-11-11 18:17:13
Java
MrBe, 2015-11-11 18:17:13

Is it possible to simplify the algorithm?

Hello, I wrote an algorithm for a java lab, but it turned out to be too complicated to understand. Please advice on how to simplify it. You can only use arrays.


Task:
Shift in the entered string of even characters by 2 positions to the right. The shift is assumed to be circular.

public static String moveLetters(String a) {
        char[] chars = a.toCharArray();
        char lastChar = ' ';
        if (chars.length % 2 == 0) {
            lastChar = chars[chars.length - 1];
        } else if ((chars.length - 1) % 2 == 0) {
            lastChar = chars[chars.length - 2];
        }
        char tmp = chars[1];
        chars[1] = lastChar;
        if (chars[chars.length-1]%2==0)
            chars[chars.length-1] = tmp;
        if (chars[chars.length - 1] % 2 != 0) {
            for (int i = 2; i < chars.length; i++) {
                for (int j = 0; j < chars.length; j++) {
                    if (((i + 1) % 2 == 0) & (tmp != ' ')) {
                        char tmp2 = chars[i];
                        chars[i] = tmp;
                        tmp = tmp2;
                    }
                }
            }
        }
        return new String(chars);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mrrl, 2015-11-11
@MrBe

Somehow like that? True, this is C#, but the difference should be small.

public static String moveLetters(String a) {
        int L=a.Length;
        char[] chars = new char[L];
        for(int x=0;x<L;x++) chars[x]=a[x==1 ? L-L%2-1 : x-2*(x%2)];
        return new String(chars);
}

M
MrBe, 2015-11-11
@MrBe

For the future, in case someone is not strong in the ternary operator, rewrote for if ... else

public static String moveLetters(String s) {
        int L = s.length();
        char[] chars = new char[L];
        int i = 0;
        for (int x = 0; x < L; x++) {
            if (x % 2 == 0) {
                i = x;
            } else {
                if (x == 1) {
                    i = L - L % 2 - 1;
                } else {
                    i = x - 2;
                }
            }
            chars[x] = s.toCharArray()[i];
        }
        return new String(chars);
    }

* for those who do not understand the code from the previous answer in C#, only for Java
public static String moveLetters(String str) {
        int L = str.length();
        char[] chars = new char[L];
        for (int x = 0; x < L; x++) {
            chars[x] = str.toCharArray()[(x % 2 == 0) ? (x) : (x == 1) ? (L - L % 2 - 1) : (x - 2)];
        }
        return new String(chars);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question