Day 6: Let’s Review (30Days of Code)

Task:

Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).

Solution:

1)Javascript:

function processData(input) {
    //Enter your code here
    let strings=input.split("\n"),even_string=[],odd_string=[];
    forlet i=1;i<=parseInt(strings[0]);i++){
        even_string=[],odd_string=[];
        for(let j=0;j<strings[i].length;j++){
            j%2===0?even_string.push(strings[i][j]):odd_string.push(strings[i][j]);
        }
        console.log(even_string.join("")+" "+odd_string.join(""));
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

2)Java:

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

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    int size = myObj.nextInt();  // Read user input
    for(int i=0;i<size;i++){
        String str=myObj.next();
        StringBuilder even_list = new StringBuilder();
        StringBuilder odd_list = new StringBuilder();
        for(int j=0;j<str.length();j++){
           if(j%2==0)
            even_list.append(str.charAt(j));
           else odd_list.append(str.charAt(j));
        }
       System.out.println(even_list.toString()+" "+odd_list.toString());
    }
}
}

Leave a Reply