Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if Input: 8-e Expected Output: 2|4|6|8

Tags:

javascript

Question 2: The input consist of a string, "o" represents odd number, "e" represents even number to be printed

Example 1.

Input: 8-e

Expected Output: 2|4|6|8

Example 2.

Input: 6-o

Expected Output: 1|3|5

Example 3.

Input: 1-o

Expected Output: 1

if have tried with for loop, but I'am a beginner so I'am confused with(-e)

const evenOdd = (number) => {
let evenvalue = [];
let oddValue=[];
for(let i =0; i<=number; i++){
if(number%i==0)
    evenvalue.push(i);
console.log(evenvalue);
}if(number%i!=0){
    oddValue.push(i);
console.log(oddValue);
}

};

evenOdd(9);
like image 791
Sumit Joshi Avatar asked Jan 22 '26 10:01

Sumit Joshi


2 Answers

You could take a while statement and get a start value of one plus an offset of one if the wanted type is even. Then iterate and add the value to the result set until the value is greater than the maximum value.

function fn(request) {
    var [max, type] = request.split('-'),
        i = 1 + (type === 'e'),
        result = [];

    while (i <= max) {
        result.push(i);
        i += 2;
    }
    return result;
}

console.log(...fn('8-e'));
console.log(...fn('6-o'));
console.log(...fn('1-o'));
like image 199
Nina Scholz Avatar answered Jan 24 '26 01:01

Nina Scholz


You will need to extract the letter and the number from you string first. One easy way to do that :

const evenOdd = (s) => {
  let odd = s.length-1 ==='o';
  let number = Number(s.substring(0, s.length-2));
  let evenvalue = [];
  ...
  if(odd){...} else {...}
};

You could also use split() or if the pattern was more complicated, a Regex.

like image 35
Ricola Avatar answered Jan 24 '26 00:01

Ricola