Monday, February 13, 2023

Coding Challenge #1

Answer to Challenge #399 from https://www.reddit.com/r/dailyprogrammer/

 // add up all letters in a string, with 'a' being 1 and 'z' being 26. Other characters have value 0.
// we will elect to change uppercase to lowercase to make this solution a little more flexible.

var aVal = 'a'.charCodeAt(0);
function letterVal(s){
    if(s >= "a" && s <= "z") return s.charCodeAt(0) - aVal;
    else if(s >= "A" && s <= "Z") return s.toLowerCase().charCodeAt(0) - aVal;
    else return -1;
}
function evaluate(str){
    var o = 0;
    for(var xint = 0, len = str.length;xint < len;xint++)
        o += letterVal(str.charAt(xint)) + 1;
    return o;
}

For example, evaluate('a') would return 1, evaluate('b') would return 2, and evaluate('5') would return 0.

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...