Algorithm


Hacker rank Problem Name: 10 Days of JavaScript - Day 5: Arrow Functions

Hacker rank Problem Link: https://www.hackerrank.com/challenges/js10-arrows/problem?isFullScreen=true

Day 5: Arrow Functions

 

Objective

In this challenge, we practice using arrow functions. Check the attached tutorial for more details.

 

Task

Complete the function in the editor. It has one parameter: an array, nums. It must iterate through the array performing one of the following actions on each element:

 

  • If the element is even, multiply the element by 2.
  • If the element is odd, multiply the element by 3.

 

The function must then return the modified array.

 

Input Format

The first line contains an integer, n, denoting the size of nums.

The second line contains n space-separated integers describing the respective elements of nums.

 

Constraints

  • 1 <= n <= 10
  • 1 <= nums[i] <= 100, where nums[i] is the ith element of nums.

 

Output Format

Return the modified array where every even element is doubled and every odd element is tripled.

 

Sample Input 0

1
2
5
1 2 3 4 5

 

Sample Output 0

1
3 4 9 8 15

 

Explanation 0

Given nums = [1,2,3,4,5], we modify each element so that all even elements are multiplied by 2 and all odd elements are multipled by 3. In other words, [1,2,3,4,5] => [13,22,33,42,5*3] -> [3,4,9,8,15]. We then return the modified array as our answer.

 

 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    
    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function modifyArray(nums) {
    const func = nums.map(function(num)
    {
        if (num%2==0)
        {
            return 2* num;
        }
        else
        {
            return 3*num;
        }
    });
    return func;
}

Copy The Code & Try With Live Editor

Input

x
+
cmd
5 1 2 3 4 5

Output

x
+
cmd
3 4 9 8 15
Advertisements

Demonstration


Previous
[Solved] #3 Day 3: Arrays in Javascript HackerRank - HackerRank Javascript in 10 days
Next
[Solved] #6 Day 6: Bitwise Operators in Javascript HackerRank - HackerRank Javascript in 10 days