4
    'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

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

// Complete the roadsAndLibraries function below.
function roadsAndLibraries(n, c_lib, c_road, cities) {
    console.log("roadsAndLibraries n--->", n);
    console.log("roadsAndLibraries c_lib--->", c_lib);
    console.log("roadsAndLibraries c_road--->", c_road);
    console.log("roadsAndLibraries cities--->", cities);
    var m = new Map();
    m.set('a', 2);
    m.set('b', 3);
    m.set('b', 3);
    m.set('b', 2);
    m.set('b', 1);

    console.log("map value--->", m);
        // Check that a root node exists.

    // if (rootNode === null) {
    //     return;
    // }

    // Check that a root node exists.
    if (n === null) {
        console.log("n root node--->", n);
        return;
    }

    // Create our queue and push our root node into it.
    // var queue = [];
    // queue.push(rootNode);

    // Create our queue and push our root node into it.
    var queue = [];
    queue.push(n);

    console.log(" queue.push--->", queue);


    while (queue.length > 0) {
        // Create a reference to currentNode, at the top of the queue.
        var currentNode = queue[0];

        // If currentNode has a left child node, add it to the queue.
        if (currentNode.left !== null) {
            queue.push(currentNode.left)
        }
        // If currentNode has a right child node, add it to the queue.
        if (currentNode.right !== null) {
            queue.push(currentNode.right)
        }
        // Remove the currentNode from the queue.
        queue.shift()
    }




}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
    console.log("ws--->", ws);


    const q = parseInt(readLine(), 10);
    console.log("q--->", q);

    for (let qItr = 0; qItr < q; qItr++) {
        const nmC_libC_road = readLine().split(' ');
        console.log("nmC_libC_road--->", nmC_libC_road);

        const n = parseInt(nmC_libC_road[0], 10);
        console.log("n--->", n);


        const m = parseInt(nmC_libC_road[1], 10);
        console.log("m--->", m);

        const c_lib = parseInt(nmC_libC_road[2], 10);
        console.log("c_lib--->", c_lib);

        const c_road = parseInt(nmC_libC_road[3], 10);
        console.log("c_road--->", c_road);

        let cities = Array(m);
        console.log("cities--->", cities);

        for (let i = 0; i < m; i++) {
            cities[i] = readLine().split(' ').map(citiesTemp => parseInt(citiesTemp, 10));
        }

        const result = roadsAndLibraries(n, c_lib, c_road, cities);
        console.log("result--->", result);

        ws.write(result + '\n');
    }

    ws.end();
}

after compilation

Input (stdin)Download
2
3 3 2 1
1 2
3 1
2 3
6 6 2 5
1 3
3 4
2 4
1 2
2 3
5 6
Your Output (stdout)
~ no response on stdout ~
Expected OutputDownload
4
12
Debug output
ws---> WriteStream {
  _writableState:
   WritableState {
     objectMode: false,
     highWaterMark: 16384,
     finalCalled: false,
     needDrain: false,
     ending: false,
     ended: false,
     finished: false,
     destroyed: false,
     decodeStrings: true,
     defaultEncoding: 'utf8',
     length: 0,
     writing: false,
     corked: 0,
     sync: true,
     bufferProcessing: false,
     onwrite: [Function: bound onwrite],
     writecb: null,
     writelen: 0,
     bufferedRequest: null,
     lastBufferedRequest: null,
     pendingcb: 0,
     prefinished: false,
     errorEmitted: false,
     emitClose: false,
     bufferedRequestCount: 0,
     corkedRequestsFree:
      { next: null,
        entry: null,
        finish: [Function: bound onCorkedFinish] } },
  writable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  path:
   '/tmp/submission/20190702/20/31/hackerrank-d27db21d31abaff7353d49d7e433da3a/0.userout',
  fd: null,
  flags: 'w',
  mode: 438,
  start: undefined,
  autoClose: true,
  pos: undefined,
  bytesWritten: 0,
  closed: false }
q---> 2
nmC_libC_road---> [ '3', '3', '2', '1' ]
n---> 3
m---> 3
c_lib---> 2
c_road---> 1
cities---> [ <3 empty items> ]
roadsAndLibraries n---> 3
roadsAndLibraries c_lib---> 2
roadsAndLibraries c_road---> 1
roadsAndLibraries cities---> [ [ 1, 2 ], [ 3, 1 ], [ 2, 3 ] ]
map value---> Map { 'a' => 2, 'b' => 1 }
 queue.push---> [ 3 ]

4 Answers4

2

Your immediate problem is that queue.push(currentNode.left) (and queue.push(currentNode.right)) is being executed as null and undefined are different in javascript. On the second time through the loop there will be two undefined elements in the queue, currentNode will now be undefined, and so of course you cannot access undefined's left or right property.

Why is this happening? Basically you haven't finished translating the Medium code's BFS implementation into what's needed for HackerRank. The BFS code is expecting the queue to contain node objects, and HackerRank's input is definitely not anything resembling a node. As it currently stands, the only item in your queue is a single number, which contains no left or right attributes. The exercise will involve, at the minimum, translating their input into a node structure suitable for BFS (if BFS is even an appropriate solution).

One possible solution might be to expand the null checks to also include undefined. Another might be to make sure everything that enters your queue is a proper node, with an initialized left and right value, even if that value is null. For intermediate testing, I'd expect replacing queue.push(n); with let aBoringNode = {left: null, right: null}; queue.push(aBoringNode); to at least get you past the current error and perform a valid (if exceedingly boring) BFS execution.

ojchase
  • 1,041
  • 1
  • 10
  • 22
  • hey updated the whole code in the question, can you guys update the code...so confusing :( –  Jul 01 '19 at 20:16
2
const n = parseInt(nmC_libC_road[0], 10);
console.log("n--->", n);

queue is a array contains n, n is a number, it cannot be used as an object. I think it's the problem.

So, I think you need to change n to m instead.

Le Khiem
  • 793
  • 6
  • 9
  • Others have pointed out that `n` is not a node, and how that leads to the error being thrown. `m` is also not a node with `left` and `right` attributes, so changing `n` to `m` isn't going to help. – ojchase Jul 05 '19 at 23:40
0

Just a guess, but remember in JavaScript undefined and null are not the same thing. So undefined !== null is truthy. In your loop you should add checks that currentNode.right and currentNode.left are not undefined

mercurial
  • 148
  • 5
  • hey updated the whole code in the question, can you guys update the code...so confusing :( –  Jul 01 '19 at 20:16
0

Just scanned the problem description, it says:

roadsAndLibraries has the following parameters:

n: integer, the number of cities

But obviously in your code, you are treating n as 'node'... It's truely a 'TypeError' as javascript indicates.

Community
  • 1
  • 1
Pu Guan
  • 76
  • 3
  • hey updated the whole code in the question, can you guys update the code...so confusing :( –  Jul 01 '19 at 20:16