Search code examples
javascriptjqueryspiral

How can i get the spiral direction number


How can i get the spiral direction number of below image by javascript

spiral direction number

How can i get the spiral direction number of above image by javascript or jquery

please help me

I hope get the index number of 2d array by spiral direction

I hope get the number sequence as this

3X3 -> 0,1,2,5,8,7,6,3,4

4X5 -> 0,1,2,3,4,9,14,19,18,17,16,15,10,5,6,7,8,13,12,11


Solution

  • jsFiddle Demo

    From your question it isn't enitrely clear what form your grid is stored in; I assumed an HTML table. Assuming that your rule for spiraling is to go right as far as possible, then down, then left, then up, repeating as needed, the following (admittedly simplistic) algorithm implemented in jQuery/JS should find the correct path for you:

    $.getCellAtIndex = function (row, col) {
        return $("table tr")
            .filter(":nth-child(" + row + ")")
            .find("td")
            .filter(":nth-child(" + col + ")")
            .not(".highlight")
            .first();
    }
    
    $(function () {
        var path = [];
        var row = 1;
        var col = 1;
    
        while (true) {
            var nextCell = $.getCellAtIndex(row, col);
            nextCell.addClass("highlight");
            path.push(nextCell);
    
            // Move right, if possible
            if ($.getCellAtIndex(row, col + 1).length > 0) {
                col++;
            }
            // Otherwise move down
            else if ($.getCellAtIndex(row + 1, col).length > 0) {
                row++;
            }
            // Otherwise move left
            else if ($.getCellAtIndex(row, col - 1).length > 0) {
                col--;
            }
            // Otherwise move up
            else if ($.getCellAtIndex(row - 1, col).length > 0) {
                row--;
            }
            // Can't spiral anymore:
            // Output path as comma-separated string
            else {
                $("span").text(function () {
                    return path.map(function (elem) {
                        return $(elem).text();
                    }).join(', ');
                });
                break;
            }
        }
    });