Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,231 questions

56,133 answers

573 users

How to shift letters in a string x times by giving an array of shifts in TypeScript

1 Answer

0 votes
/*

string = “aaa”
After Shifting the first 1 letter by 1 = “baa”
After shifting the first 2 letters by 2 = "dca"
After shifting the first 3 letters 3 = "gfd"
result = "gfd"

*/

function shifLetters(str: string, shifts: number[]) {
    const size: number = shifts.length;
    let arr: string[] = str.split('');
    
    for (let i: number = size - 1; i >= 0; i--) {
        if (i + 1 < size) {
            shifts[i] += shifts[i + 1];
        }
        
        shifts[i] = shifts[i] % 26;
        let asciicode: number = str.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0);
        asciicode = asciicode + shifts[i];
        
        if (asciicode > 25) {
            asciicode = asciicode - 26;
        }
        
        arr[i] = String.fromCharCode(('a'.charCodeAt(0) + asciicode));
    }
    
    return arr.join("");
}

let str: string = "aaa";
const shifts: number[] = [1, 2, 3];

str = shifLetters(str, shifts);

console.log(str);




/*
run:
 
"gfd" 
 
*/

 



answered Feb 28, 2024 by avibootz

Related questions

...