0

I'll try to ask as clearly as possible, but please comment if some part is not clear to you.

I'm trying to develop a formula to determine the position of an element based on that element's value in a sequence. More specifically, I am using JavaScript to split a string of this nature: c-c c-c-c c into an array and iterate over that array using an interval of 2i to extract the c values. For example, let's say my string is as previously posted (6 c values in length). I wish to place these c values in the following manner where the number refers to the value of i in my loop (I prepended an extra 0 to make it symmetrical due to the 10):

00 ## 02
      ##
06 ## 04
##
08 ## 10

I'm trying to find a pattern/formula using the value of i which will result in the above positioning. For simplicity's sake, let's assume an x,y coordinate system such that the position of the c value at 00 is (0,0), 02 is (1,0), 04 is (1,1), 06 is (0,1), 08 is (0,2), and 10 is (1,2).

Can anyone help in developing a pattern/formula/algorithm to determine the positioning using i values? I'm trying not to have to write (in this example) six different if statements.

4

1 回答 1

2

使用您的 x,y 坐标系:

y = Math.floor(i / 2);
x = y % 2 == 0 ? i % 2 : (i + 1) % 2;

或者,如果您希望它更简洁(但非常不清楚):

y = Math.floor(i / 2);
x = (i + y % 2) % 2;

上面的代码是基于假设代码是这样的:

for (var i = 0; i < theString.length / 2; i++) {
    var character = theString.charAt(2 * i);
    // work out the coordinates
}

如果代码更像这样:

for (var i = 0; i < theString.length; i += 2) {
    var character = theString.charAt(i);
    // work out the coordinates
}

然后我们需要对其进行一些修改,使其如下所示:

j = i / 2;
y = Math.floor(j / 2);
x = y % 2 == 0 ? j % 2 : (j + 1) % 2;

或者,如果您希望它更简洁(但非常不清楚):

j = i / 2;
y = Math.floor(j / 2);
x = (j + y % 2) % 2;
于 2013-05-02T00:43:18.177 回答