Breaking

Saturday 30 September 2017

Decode

                 Accolite Java Hiring Challenge
                           Decode

Given an encrypted message, Erwin encodes it the following way:
Removes the median letter of the word from the original word and appends it to the end of the encrypted word and repeats the process until there are no letters left.
A median letter in a word is the letter present in the middle of the word and if the word length is even, the median letter is the left one out of the two middle letters.
Given an encoded string, write a program to decode it.
Input Format:
The first line of input contains T, the number of test cases.
Each test case contains a String S, denoting the encoded word.
Output Format:
Print the decoded word for each test case in a separate line.
Constraints
1T100
1|S|100000

Sample Input

2
wrien
reen

Sample Output

erwin
eren
Explanation
In the first test case, Erwin encoded the String "erwin". At first, he wrote down the letter 'w' after which the string became "erin", he then wrote down 'r' and the remaining string was "ein", he then wrote 'i' and the string became "en" and so on he wrote down 'e' and 'n' to get the encoded string as "wrien".
Note: Your code should be able to convert the sample input into the sample output. However, this is not enough to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement.

Code:


import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int k;
for(k=0;k<n;k++)
{
   
String s=sc.next();
        int len=s.length();
        int mid,i,x=0,c=1;
        if(len%2==0)
            mid=len/2;
        else
            mid=len/2+1;
        char ch[]=new char[len+1];
       
        if(len%2==0)
        {
            ch[mid]=s.charAt(0);
            for(i=1;i<len;i++)
            {
               if(i%2==0)
                    ch[mid-c]=s.charAt(i);
                else
                    ch[mid+c]=s.charAt(i);
                x++;
                if(x==2)
                    {
                        c++;
                        x=0;
                    }
                   
            }
        }
        else
        {
            ch[mid]=s.charAt(0);
            for(i=1;i<len;i++)
            {
               if(i%2==1)
                    ch[mid-c]=s.charAt(i);
                else
                    ch[mid+c]=s.charAt(i);
                x++;
                if(x==2)
                    {
                        c++;
                        x=0;
                    }
              }      
        }
        String str=new String(ch);
        System.out.println(str.trim());
}
        }
    }

Please do comment If u have any Queries!

No comments:

Post a Comment

Like