Help needed with a problem (Solved) - Hackerrank Day 6

function processData(input) {
    //Enter your code here
    var number;
    var main = "";
    var eve;
    var odd;

    if (isNaN(input) == false) {
        return 1;
    }
    else {
    
        for (var i = 0; i < input.length; i++) {
            if (i == 0 || i % 2 == 0) {
                eve += input.charAt(i);
            }
            else {
                odd += input.charAt(i);
            }
        }
         main = eve + " " + odd + "\n";
    }
    
    console.log(main); 
}

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

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

If I input Hacker in this, I am supposed to get Hce akr
where the even index chars come first followed by a space and then the odd index chars
But somehow I am getting the following out :

  • "undefinedHce undefinedakr "

Any help is appreciated!

Thank you.

You perhaps forgot to assign your initial eve odd variables as strings to concatenate them in the loop.

  var eve = '';
  var odd = '';

A simple example for what is happening:

var vehicle; // undefined
vehicle +=  'Car'; 
console.log(vehicle) // "undefinedCar";

var name = '' // ""
name += 'John'
console.log(name) // "John";
1 Like

Thank you so much for the response!! It was a glaring error I somehow skipped.
However, I changed the code altogether and ended up with this.

function processData(input) {
    //Enter your code here
    var arr = input.split('\n');
    arr.shift(0);
    for(let i = 0; i < arr.length; i ++){
      if(arr[i].length < 2 || arr[i].length > 10000){
          console.log("Invalid");
      } else {
        console.log(even(arr[i]) +  odd(arr[i]));
      }
    }

    function even(str) {
        //for even
        var eve = "";
        for(let i = 0; i < str.length; i+=2){
            eve += str[i];
        }
        return eve + " ";
    }

    function odd(str) {
        //for odd
        var odd = "";
        for(let i = 1; i < str.length; i+=2){
            odd += str[i];
        }
        return odd + " ";
    }
}

In case, any one wants the final solution :smiley:
It was a part of day 6 of HackerRank’s 30 days of Code.

Thanks again for the response as well as the clear as day explanation.

Cheers!

1 Like