Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > JavaScript: Общие вопросы > Spiral matrix


Автор: CrasyMen 8.1.2017, 11:10
Пытаюсь решить задачу https://www.hackerrank.com/contests/coding-test-1-bits-hyderabad/challenges/spiral-matrix-1
Скриншот: https://drive.google.com/open?id=0BzPbn-GsU-Z4c2taeDVUSXVDZ1k

Проблема: Не проходит все тесты при сабмите. Я внимательно прочитал условия и попробовал на разных наборах входных данных. По-моему, сделал все что написано в условии. Подскажите что я упускаю.


Код моего решения

Код

function processData(input) {
    const [size, ...matrixAsLine] = input.trim().split(/[\s]/);
    
    // prepare matrix as 2-dimensional array
    const matrix = [];
    for(let rowIndex = 0; rowIndex < size; rowIndex++) {
        const start = size * rowIndex;
        const end = start + size;
        matrix.push(matrixAsLine.slice(start, end));
    }

    // perform size/2 iterations to collect spiral
    let spiral = [];
    for(let circleIndex = 0; circleIndex < size/2; circleIndex++) {
        const firstRowIndex = firstColIndex = circleIndex;
        const lastRowIndex = lastColIndex = size - circleIndex - 1;
        
        const firstRow = matrix[firstRowIndex].slice(firstColIndex, lastColIndex + 1);
        const lastRow = firstRowIndex != lastRowIndex 
                        ? matrix[lastRowIndex].slice(firstColIndex, lastColIndex + 1) 
                        : [];
        
        const firstCol = [];
        const lastCol = [];
        for(let rowIndex = firstRowIndex + 1; rowIndex < lastRowIndex; rowIndex++) {
            const row = matrix[rowIndex];
            firstCol.push(row[firstColIndex]);
            lastCol.push(row[lastColIndex]);
        }
 
        const circle = [...firstRow, ...lastCol, ...lastRow.reverse(), ...firstCol.reverse()];
        
        spiral = spiral.concat(circle);
    }
    
    console.log(spiral.join(' '));


process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Или можна в гисте посмотреть https://gist.github.com/cwayfinder/06a58715c4bbb0abac6548b1ff761497

Добавлено через 8 минут и 56 секунд
Не понимаю как тема попала в этот раздел. Переместите пожалуста в http://forum.vingrad.ru/forum/javascripts-firststeps.html

Автор: CrasyMen 8.1.2017, 16:47
поправил регулярку с /[\s]/ на /[\s]+/ и все тесты прошли

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)