Saturday, March 25, 2023

Coding Challenge #32

 // Daily Coding Challenge #34
// make a (made up) pallindrome from a word using as few characters as possible
// Example: race -> ecarace
// Example: google -> elgoogle
// if the word is already a pallindrome, it will be nigh doubled (eke -> ekeke)
function pallindromize(str){
    // we'll always be wrapping around the first letter
    // get the first letter, keep going until we get another of that letter
    // if the first & second instance of the letter have mirrored chars between them, just add the reversed proceeding letters to the front
    // else we use a substring of 2nd char onwards reversed as a prepending string for the original string
    var fromwhere = 0; // after this index is reversed and prepended
    for(var xint = 1;xint < str.length;xint++){
        if(str.charAt(xint) == str.charAt(0)){
            // check chars between are mirrored
            var lvar = 0; // first instance of the char, left one
            var rvar = xint; // 2nd instance of the char, right one
            var matched = true;
            while(lvar < rvar){
                if(str.charAt(lvar) != str.charAt(rvar)){
                    matched = false;
                    break;
                }
                lvar++;
                rvar--;
            }
            if(matched) fromwhere = xint;
            break;
        }
    }
    
    // reverse end of pallindrome, prepend to mid-char-n-later of pallindrome
    var s = "";
    for(var xint = str.length - 1;xint > fromwhere;xint--){
        s += str.charAt(xint);
    }
    return s + str;
}

function test(str){
    console.log(str + " -> " + pallindromize(str));
}

test('horse'); // -> esrohorse
test('poopy'); // -> ypoopy
test('om'); // -> mom

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 ...