Answer to Question #310316 in HTML/JavaScript Web Application for vicky

Question #310316

squares of Array items

input

  • the input will be a single line containing an array myArray. the myArray consists of numbers and array.

output

  • the output should containig the square of each item.


input1

[[1,2],[3,4],[5,6]]

output1

[ [ 1,4],[9,16],[25,36]]


input2

[12,[24],36,[48,60]]

output2

[144,[576],1296,[2304,3600]]


"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((str) => str.trim());

 main();

});

function readLine() {

 return inputString[currentLine++];

}

function main() {

 let myArray = JSON.parse(readLine())


 /* Write your code here and log the output */

}



1
Expert's answer
2022-03-12T18:05:17-0500
       "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((str) => str.trim());
            main();
        });


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


        function main() {
            let myArray = JSON.parse(readLine())
            /* Write your code here and log the output */
            let res = [];


            myArray.forEach(item => {
                if (typeof item === 'number') {
                    res.push(item ** 2);
                } else {
                    let arr = [];


                    if (item.length < 2) {
                        arr.push(item ** 2);
                    } else {
                        item.forEach(n => arr.push(n ** 2));
                    }


                    res.push(arr);
                }
            })


            console.log(res);
        }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS