Mah*_*Ali 5 javascript arrays algorithm
Consider an array whose length will be always product of two numbers. For below array l is 4 and w is 5.
There is also a given index. I want to get the two arrays containing elements which lie on the diagonal line which passes through that particular index.
[
0, 1, 2, 3, 4
5, 6, 7, 8, 9
10, 11, 12, 13, 14
15, 16, 17, 18, 19
]
index = 7 => [3, 7, 11, 15] and [1, 7, 13, 19]
index = 16 => [4, 8, 12, 16] and [10, 16]
index = 0 => [0, 6, 12, 18] and [0]
Run Code Online (Sandbox Code Playgroud)
I have tried following:
[
0, 1, 2, 3, 4
5, 6, 7, 8, 9
10, 11, 12, 13, 14
15, 16, 17, 18, 19
]
index = 7 => [3, 7, 11, 15] and [1, 7, 13, 19]
index = 16 => [4, 8, 12, 16] and [10, 16]
index = 0 => [0, 6, 12, 18] and [0]
Run Code Online (Sandbox Code Playgroud)
The code have two problems. Both the arrays in the result are same. And secondly they are not in order.
Note: I don't want to use sort() to reorder the array. And also I don't want loop through all 20 elements. Just want to get the elements of that diagonal row
尝试下面的代码
let arr = Array(20).fill().map((x,i) => i);
function getDias(arr, l, w, ind){
let arr1 = [];
let arr2 = [];
n = l*w;
lVal = Math.floor(ind/w);
rVal = ind%w;
temp1 = lVal;
temp2 = rVal;
while(temp1>=0 && temp2>=0){
val = ((w*temp1) + temp2);
arr1.unshift(arr[val]);
temp1--;
temp2--;
}
temp1 = lVal;
temp2 = rVal;
temp1++;
temp2++;
while(temp1<l && temp2<w){
val = ((w*temp1) + temp2);
arr1.push(arr[val]);
temp1++;
temp2++;
}
console.log(arr1);
temp1 = lVal;
temp2 = rVal;
while(temp1>=0 && temp2<w){
val = ((w*temp1) + temp2);
arr2.unshift(arr[val]);
temp1--;
temp2++;
}
temp1 = lVal;
temp2 = rVal;
temp1++;
temp2--;
while(temp1<l && temp2>=0){
val = ((w*temp1) + temp2);
arr2.push(arr[val]);
temp1++;
temp2--;
}
console.log(arr2);
}
getDias(arr, 4, 5, 7);
getDias(arr, 4, 5, 16);
getDias(arr, 4, 5, 0);Run Code Online (Sandbox Code Playgroud)
这个想法是计算 l_val 和 r_val。
l_val = index/w
r_val = index%w
Run Code Online (Sandbox Code Playgroud)
现在 arr[l_val][r_val] 标记由 l_val* w+ r_val 找到的矩阵中的位置
接下来是 4 个步骤:
1) 从arr[l_val][r_val]开始迭代。两者都减 1,直到到达终点。将其取消移动到 array_1 (以维持顺序)
2)从[l_val][r_val]开始迭代。两者都加1,直到到达终点。将其推入 array_1。
3) 从arr[l_val][r_val]开始迭代。从 l_val 中减去 1,并添加 1 t r_val 直到到达末尾。将其取消移动到 array_2 (以维持顺序)
4)从[l_val][r_val]开始迭代。l_val加1,r_val减1,直到迭代结束。将其推入 array_2。