切片方法无法按预期工作

时间:2014-08-18 11:37:16

标签: javascript node.js

我正在尝试解决这个问题(https://www.hackerrank.com/challenges/service-lane)。我写了一段代码

'use strict';

function processData(input) {
    var lines = input.split('\n');
    var nFreeLane = lines[0].split(' ')[0];
    var nTestCase = lines[0].split(' ')[1];
    nFreeLane = parseInt(nFreeLane);
    nTestCase = parseInt(nTestCase);
    var nFreeWidth = lines[1].split(' ').map(function(num) {
        return parseInt(num);
    });
    for (var i = 2; i < nTestCase + 2; i++) {
        var xx = lines[i].split(' ');
        var entryPoint = xx[0];
        var exitPoint = xx[1];
        var nAr;
        if (exitPoint == nFreeWidth.length - 1) {
            nAr = nFreeWidth.slice(entryPoint);
        } else {
            console.log('coming here');
            console.log('exit point is' + exitPoint);
            console.log(nFreeWidth.length);
            nAr = nFreeWidth.slice(entryPoint, exitPoint + 1);
            console.log('nAr is' + nAr);
        }
        if (Math.min.apply(null, nAr) >= 3) process.stdout.write('3\n');
        if (Math.min.apply(null, nAr) == 2) process.stdout.write('2\n');
        if (Math.min.apply(null, nAr) == 1) process.stdout.write('1\n');
    }
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
var _input = "";
process.stdin.on("data", function(input) {
    _input += input;
});
process.stdin.on("end", function() {
    processData(_input);
});

当我运行此代码输入

5 5    
1 2 2 2 1
2 3
1 4
2 4
2 4
2 3

预期产出

2
1
1
1
2

但我的输出是

1
1
1
1
1

当我使用切片方法

if (exitPoint == nFreeWidth.length - 1) {
    nAr = nFreeWidth.slice(entryPoint);
} else {
    console.log('coming here');
    console.log('exit point is' + exitPoint);
    console.log(nFreeWidth.length);
    nAr = nFreeWidth.slice(entryPoint, exitPoint + 1);
    console.log('nAr is' + nAr);
}

nAr给出2,3是[2,2,1],但预期是[2,2]。任何人都可以告诉它为何表现出这种行为。请解释。谢谢

1 个答案:

答案 0 :(得分:0)

var exitPoint = xx[1];

是一个字符串。当你在

exitPoint + 1
nAr = nFreeWidth.slice(entryPoint, exitPoint + 1);

你实际上正在进行字符串连接:"2"+1 == "21"slice很乐意接受(将其转换为数字)并返回一个数量级太长的数组...


这是您的代码的固定,简化和有效版本:

function processData(input) {
    var lines = input.split('\n');
    lines.shift(); // uninteresting stats, might simplify parsing in other languages
    var widths = lines.shift().split(' ').map(Number);
    // console.log("passed widths: ", widths.length);
    for (var i = 0; i < lines.length; i++) {
        var parts = lines[i].split(' ');
        var entryPoint = +parts[0]; // "+" casts to number
        var exitPoint = +parts[1];
        // console.log('in: '+entryPoint+', out: ' + exitPoint);
        var sectionWidths = widths.slice(entryPoint, exitPoint + 1);
        // console.log('sections is ' + sectionWidths);
        var minWidth = Math.min.apply(null, sectionWidths);
        process.stdout.write(Math.min(minWidth, 3)+'\n');
    }
}