Monday, September 4, 2017

Four Strings Square

Four strings all having the same length L are passed as the input to the program. The four strings must be printed in a L*L square matrix shape as shown in the example input/output. The string which is on the top will always be the first string in the input. Other three strings can occur in a random order in the input. The sequence of the string can be identified by the fact that the last letter of a string will be the first letter of another string (and you can safely assume the last letter will not occur more than once).

Input Format:
The first line contains the string which represents the top of the square matrix. The next three lines will contain the remaining the three string values which can represent the right, left and bottom side of the squares, but not necessarily in the same order.

Output Format:
The L*L square matrix with these four strings as it's sides as described in the Example Input/Output.

Boundary Conditions:
3 <= L <= 100

Example Input/Output 1:
Input:
TIGER
YACHT
RANGE
EVERY
Output:
TIGER
H***A
C***N
A***G
YREVE

Example Input/Output 2:
Input:
MAN
DOT
NOD
TIM
Output:
MAN
I*O
TOD

Solution:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    string s1,s2,s3,s4;
    cin>>s1>>s2>>s3>>s4;
    int n=s1.length();
    if(s1[0]==s3[n-1])
        swap(s2,s3);
    else if(s1[0]==s4[n-1])
        swap(s2,s4);
    if(s1[n-1]==s4[0])
        swap(s3,s4);
    cout<<s1<<endl;
    for(int i=1;i<=n-2;i++)
    {
        cout<<s2[n-1-i];
        for(int j=1;j<=n-2;j++)
            cout<<'*';
        cout<<s3[i]<<endl;
    }
    for(int i=n-1;i>=0;i--)
        cout<<s4[i];
    return 0;
}
Share: