Question

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

Était-ce utile?

La 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;
        }
    }
});

Autres conseils

Just store current x and y in variables and also keep a "current direction" in dx and dy starting from (0, 0) and with direction (1, 0).

Now the algorithm is

  • store the current location y*width+x
  • if next spot x+dx, y+dy is not valid or already visited turn right t=dy; dy=dx; dx=-t;
  • move to next spot x+=dx; y+=dy;

and repeat this for width * height steps.

function a(quantity){
    var arr = new Array(quantity * quantity);
    var result = [];
    var start = false;

    for (var i = 0; i < arr.length; i++) {
      var step = i % quantity;

      if (step === 0) {
        result.push([]);

        start = !start;

      }

      if (start) {
        result[result.length - 1].push(i + 1);
      } else {
        result[result.length - 1].unshift(i + 1);
      }

    }

    return result;
}

console.log(a(3));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top