I have solved the following quiz in JavaScript, and attached the quiz and my solution below. I did not feel right solving the problem because I knew I was missing how to recall functions! Can anyone help me rewrite the code in a simpler way using the method of recalling functions? or any one of the simplest ways is welcome!
QUIZ :
Given three inputs : two arrays with the same length containing decimal numbers and the number of their lengths, convert the numbers in the two arrays into binary numbers, like so:
01001
10100
11100
10010
01011
11110
00001
10101
10001
11100
then, combine the two arrays by overlapping one over the other, making a new array having 1s from each array, (1 overlays 0), like so:
11111
10101
11101
10011
11111
as the last step, convert this array into a format having #s-and spaces under condition of (# = 1, space = 0) at last, you should get this as output >
[ '#####', '# # #', '### #', '# ##', '#####' ]
MY SOLUTION:
function solution(n, arr1, arr2) {
var convArr1 = arr1.map(function(numten) {
return numten.toString(2);
})
var convArr2 = arr2.map(function(numten) {
return numten.toString(2);
})
var newArr1 = convArr1.map(function(binNum) {
if (binNum.length != n) {
let zero = '0';
for (let i = 1; i < n - binNum.length; i++) {
zero = zero + 0;
}
binNum = zero + binNum;
return binNum;
} else {
return binNum;
}
})
var newArr2 = convArr2.map(function(biNum) {
if (biNum.length != n) {
var zero = '0';
for (let i = 1; i < n - biNum.length; i++) {
zero = zero + '0';
}
biNum = zero + biNum;
return biNum;
} else {
return biNum;
}
})
// console.log(newArr1, newArr2);
var answer = ["", "", "", "", ""];
var element = "";
function compare(a, b) {
for (var i = 0; i < a.length; i++) {
if (a[i] === '1' || b[i] === '1') {
answer[i] = answer[i] + '#';
} else {
answer[i] = answer[i] + ' ';
}
}
}
var compareArr = [];
for (var i = 0; i < n; i++) {
var numInArr1 = newArr1[i];
var numInArr2 = newArr2[i];
compare(numInArr1, numInArr2);
}
return answer;
}
console.log(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]));