Name Game

John has recently learned about ASCII values. With his knowledge of ASCII values and character he has developed a special word and named it John's Magical word.

A word that consists of alphabets whose ASCII values is a prime number is a John's Magical word. An alphabet is john's Magical alphabet if its ASCII value is prime.

John's nature is to boast about the things he know or have learnt about. So just to defame his friends he gives few string to his friends and ask them to convert it to John's Magical word. None of his friends would like to get insulted. Help them to convert the given strings to John's Magical Word.

Rules for converting:

1.Each character should be replaced by the nearest John's Magical alphabet.

2.If the character is equidistant with 2 Magical alphabets. The one with lower ASCII value will be considered as its replacement.

Example:

Input: n = 8, s ="KINGKONG"
Output: IIOGIOOG

Approach

C++

#include <bits/stdc++.h>
using namespace std;
bool isprime(int n)
{
    if (n <= 1)
        return false;
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            return false;
    return true;
}

string nameGame(int nstring s)
{

    for (int i = 0; i < n; i++)
    {
        int x = s[i];
        if (x < 65)
            s[i] = 'C';
        else
        {
            if (!isprime(x))
            {
                int flag1 = 0, flag = 0, x1, x2, res;
                for (int j = x + 1; j <= 122; j++)
                {
                    if (isprime(j))
                    {
                        x1 = j;
                        flag = 1;
                        break;
                    }
                }
                for (int j = x - 1; j >= 65; j--)
                {
                    if (isprime(j))
                    {
                        x2 = j;
                        flag1 = 1;
                        break;
                    }
                }
                if (flag1 == 1 && flag == 1)
                {
                    if (x - x2 <= x1 - x)
                        res = x2;
                    else
                        res = x1;
                }
                else if (flag == 1)
                    res = x1;
                else if (flag1 == 1)
                    res = x2;
                char c = res;
                s[i] = c;
            }
        }
    }
    return s;
}
int main()
{

    int n = 8;
    string s = "KINGKONG";

    cout << nameGame(n, s) << "\n";

    return 0;
}


No comments:

Post a Comment