Tuesday 3 October 2017

TCS CodeVita 2015 Round 2 : Alpha Numeric Sorting

Given text comprising of words and numbers, sort them both in ascending order and print them in a manner that a word is followed by a number. Words can be in upper or lower case. You have to convert them into lowercase and then sort and print them.
Input Format:
First line contains total number of test cases, denoted by N
Next N lines, each contains a text in which words are at odd position and numbers are at even position and are delimited by space
Output Format:
Words and numbers sorted in ascending order and printed in a manner that a word is followed by a number.
Constraints:
1. Text starts with a word
2. Count of words and numbers are the same.
3. Duplicate elements are not allowed 
4. Words should be printed in lower case. 
5. No special characters allowed in text.
Solution in Java

import java.util.*;


public class StringAndNumeric {
public static void main(String []args){
   
    Scanner sc=new Scanner(System.in);
    String str=sc.nextLine();
    String [] str2=str.split(" ") ;
    int n=str2.length;
    String []str3=new String[n/2+1];
    String []str4=new String[n/2];
    int i,j=0,k=0;
for(i=0;i<n;i++){
    if(i%2==0){
    str3[j]=str2[i];
    j++;}
    else{
       
    str4[k]=str2[i];
    k++;}

}
Arrays.sort(str3);
Arrays.sort(str4);

k=0;int p=0;
for( int l=0;l<n;l++){
    if(l%2==0){
    str2[l]=str3[k];
    k++;}
    else{
        str2[l]=str4[p];p++;   
}}
for( i=0;i<n;i++)
System.out.println(str2[i]);
}}
Input: gghgh 67 asasa 34
Output:

asasa

34

gghgh

67

1 comment:

  1. i got the output 2 for your program ...i didn't get the correct output

    ReplyDelete