Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the middle letter among the specified letters?

I’ve created a function that accepts 2 parameters to find the middle value between those parameters in an Alphabet variable.

Example:

the middle part between Q and U is S,
the middle part between R and U is ST,
the middle part between T and Z is W,

What I’m confused about is how do I take the value one by one starting at index 1 in the Alphabet variable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function letterMiddleValue(a, b) {
    let alpha1 = Alphabet.indexOf(a);
    let alpha2 = Alphabet.indexOf(b);
    let center = (alpha1 + alpha2) / 2;
    let letterLength;

    if (center % 2 == 1) {
        letterLength = 1;
    } else {
        letterLength = 2;
    }
    return Alphabet.substring(center, center + letterLength);
}

var Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

console.log(letterMiddleValue("Q", "U"));
console.log(letterMiddleValue("R", "U"));
console.log(letterMiddleValue("T", "Z"));

>Solution :

Center for r & u is 18.5. 18.5 % 2 is 0.5 so you need to check for 0.5 condition:

function letterMiddleValue(a, b) {
    let alpha1 = Alphabet.indexOf(a);
    let alpha2 = Alphabet.indexOf(b);
    let center = (alpha1 + alpha2) / 2;
    let letterLength;

    if (center % 2 == 0.5) {
        letterLength = 2;
    } else {
        letterLength = 1;
    }

    return Alphabet.substring(center, center + letterLength);
}

var Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

console.log(letterMiddleValue("Q", "U"));
console.log(letterMiddleValue("R", "U"));
console.log(letterMiddleValue("T", "Z"));

That’s because how you calculate center.
(7 + 5) / 2 = 6.5
(6 + 10) / 2 = 8
and modulo gives back what’s not dividable by 2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading