Search code examples
javascriptarraysfunctiondata-conversionbinary-operators

Quiz: Convert into binary numbers, overlay arrays in JavaScript


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]));

Solution

  • What you call '1 overlays 0' is a binary operator. The | operator (pronounce 'OR') takes the binary representations of 2 decimal numbers and then compares each binary digit (= each bit) to produce a 1 if one of the bits or both of them is equal to 1.

    You were asking about a way to 'recall' or reuse the function that was used to convert arr1 to also convert arr2. But both conversions aren't really needed. To use the | operator no conversion of the decimal numbers is necessary because that's what the computer internally uses anyway.

    You can try this...

    function solution (n, arr1, arr2) {
    
        result = arr1.map(function (element, index) {
          // take the element and the relative element of the other array 
          // and use the binary OR operator
          return element | arr2[index];
        }).map(function (element) {
          // make a string of the required number of spaces ...
          // and add our binary pattern of replacements for 1's and 0's
          binary = " ".repeat(n) + element.toString(2).replace(/1/g,'#').replace(/0/g,' ');
    
          // truncate to return only the last n bits
          return binary.slice(-n);
    
        });
        return result;
    }
    
    console.log(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]));
    

    A lot happens to the same arr1 array. That's why I wrote the .mapcalls one right after the other. This is called method chaining. The first map method takes arr1 and then produces a new array. Of course that array also has a .map method we can call. The first map is used to combine arr1 and arr2. The second map call is used to convert the result into an array with our patterns of # and SPACE.

    In the first map call our callback function takes an extra parameter:

    arr1.map(function (element, index) {
          // take the element and the relative element of the other array 
          // and use the binary OR operator
          return element | arr2[index];
    })
    

    We need the index number of each element that is mapped over because we need the same element inside the arr2 array.