Perfectly balanced - Programming Challenge [Java]

There was a challenge, it goes like this:

 "Given a string containing only the characters x and y, find whether there are the same number of xs and ys."

This is what I did:

    // Given a string containing only the characters x and y, find whether there
    // are the same number of x's and y's.
    public boolean balanced(String s) {
        int x = 0, y = 0;
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) == 'x')
                x++;
            else if (s.charAt(i) == 'y')
                y++;
        if (x == y)
            return true;
        else
            return false;
    }

Its real simple actually. The for loop runs through the string. Every character is checked and counter. By the end, if the program counter the same number of x's as the number of y's, return true, otherwise return false.

The challenge continues:

"Given a string containing only lowercase letters, find whether every letter that appears in the string appears the same number of times. Don't forget to handle the empty string ("") correctly!"

This is what I did:

    // Given a string containing only lowercase letters, find whether every
    // letter that appears in the string appears the same number of times.
    public boolean balancedBonus(String s) {
        if (s == "")
            return true;
        else {
            ArrayList<Character> letters = new ArrayList<Character>();
            ArrayList<Integer> amount = new ArrayList<Integer>();
            letters.add(0, s.charAt(0));
            amount.add(0, 1);
            for (int i = 1; i < s.length(); i++)
                if(letters.contains(s.charAt(i))){
                    amount.set(letters.indexOf(s.charAt(i)), amount.get(letters.indexOf(s.charAt(i))) + 1);
                }else{
                    letters.add(s.charAt(i));
                    amount.add(1);
                }
            for (int i = 0; i < letters.size(); i++)
                if(amount.get(i) != amount.get(0))
                    return false;
            return true;
        }
    }
This looks more complicated than it is. There are two lists, one holds the letter, and the other list holds the number of appearances of that letter at the same index. For example, if the letters list has an x at index 0, the number of x's counted will be stored in the amount list, also at index 0. The program runs through the string and checks every letter. If the letter already appears in the letters list, the amount list is updated. If the letter does not yet appear in the letters list, the letter is added to the end of the letter list, and a 1 is added to the end of the amount list. At the end, we check if the numbers stored in the amount list are all the same.



Comments

Popular posts from this blog

A* Pathfinding Algorithm Java Implementation

Additive Persistence - Programming Challenge [Java]

Ducci Sequence - Programming challenge [Java]