Wednesday, May 20, 2015

More JavaScript

Code learning continues.  Another great resource is www.interviewcake.com.  I haven't explored the entire site, but I like the weekly challenge the owner sends out by email.  One recent challenge involved taking a given string and evaluating whether it could be re-arranged into a palindrome (e.g., "house" would return "false", "civci" would return "true", etc.).  Here is one solution:

function checkPal (str) {
 
    var counts = {};
    var ch, count, i, oddCount, key;
    for (i = 0; i < str.length; i++) {
        ch = str.charAt(i);
        if (counts[ch] > 0) {
            counts[ch]++;
        } else {
            counts[ch] = 1;
        }
    }
 
    oddCount = 0;
    for (key in counts) {
        if (counts[key] % 2 == 1) {
            oddCount++;
        }
    }
 
    if (oddCount == 1 || oddCount === 0) {
        return true ;
        } else {
            return false;
        }
}

The solution first creates an associative array from the characters of the string.  The important bit comes next.  A palindrome has at most one character which appears an odd number of times.  The function counts the values of each key, and if there is more than one key with an add value, the string cannot be a palindrome, and the function returns "false".