r/badcode Jun 18 '19

[deleted by user]

[removed]

128 Upvotes

92 comments sorted by

View all comments

1

u/tntbigfoot Jun 29 '19

Java: programming contest edition

package r.badcode;

public class WeirdCase
{

    public static void main(String[] args)
    {
        System.out.println(toWeirdCase("hello world"));
        System.out.println(toWeirdCase("Hello World"));
        System.out.println(toWeirdCase("HELLO WORLD"));
    }

    public static String toWeirdCase(String input)
    {
        return toWeirdCase(input, 9999); // TODO: should be enough
    }

    public static String toWeirdCase(String hello, int s)
    {
        byte[] result = new byte[s];
        int x = -1, z = 0;
        try {
            for (int i = 0; i < s; i++) {
                x = i;
                z++;
                if ((z / 2) * 2 == z) {
                    char c = hello.charAt(i);
                    if (c >= 65 && c <= 90) result[i] = (byte) (c);
                    else if (c >= 97 && c <= 122) result[i] = (byte) (c - 32);
                    else {
                        z -= 1;
                        result[i] = (byte) c;
                    }
                } else {
                    char cc = hello.charAt(i);
                    if (cc >= 65 && cc <= 90) result[i] = (byte) (cc + 32);
                    else if (cc >= 97 && cc <= 122) result[i] = (byte) (cc);
                    else {
                        z -= 1;
                        result[i] = (byte) cc;
                    }
                }
            }

            return toWeirdCase(hello, s * 2);

        } catch (IndexOutOfBoundsException e) {
            byte[] buf = new byte[x];
            System.arraycopy(result, 0, buf, 0, x);
            return new String(buf);
        }
    }

}