我想将网格和nextgrid数组转换为1d数组。因此,我可以在CUDA中更容易地实现每个单元格的线程化。目前,当从命令行传递特定维度时,会导致分段错误。例如。如果gridWidth = 6且gridHeight = 8。但是会在某些价值观上按预期工作。例如。如果他们都被传入6。
所以,我想知道如何使用pair值正确初始化1d数组,然后如何在嵌套for循环中实现它。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cstdlib>
int main (int argc, char *argv[])
{
using namespace std;
//delcare variables
int numIterate = atoi (argv[1]);
int gridWidth = atoi (argv[2]);
int gridHeight = atoi (argv[3]);
cout << "iterate: " << numIterate;
cout << " w: " << gridWidth;
cout << " h: " << gridHeight;
cout << endl;
//make grid
int grid[gridWidth][gridHeight];
int nextgrid[gridWidth][gridHeight];
int genCount=0;
//set all values in grid as 0
for(int i=0;i<gridHeight;i++){
for(int j=0;j<gridWidth;j++){
grid[i][j]=0;
}
}
//insert glider pattern
grid[2][3]=1;
grid[3][2]=1;
grid[4][2]=1;
grid[4][3]=1;
grid[4][4]=1;
for(int k=0; k< numIterate+1; k++){
cout << endl;
cout << endl;
cout << "GENERATION " << genCount <<endl;
for(int i=0;i<gridHeight;i++){
cout << endl;
for(int j=0;j<gridWidth;j++){
int count=0;
count+= grid[i][(j-1+gridWidth)%gridWidth] //left
+grid[i][(j+1+gridWidth)%gridWidth] //right
+grid[(i-1+gridHeight)%gridHeight][j] //up
+grid[(i+1+gridHeight)%gridHeight][j] //down
+grid[(i-1+gridHeight)%gridHeight][ (j-1+gridWidth)%gridWidth] //up-left
+grid[(i+1+gridHeight)%gridHeight][ (j+1+gridWidth)%gridWidth] //down-right
+grid[(i+1+gridHeight)%gridHeight][ (j-1+gridWidth)%gridWidth] //down-left
+grid[(i-1+gridHeight)%gridHeight][ (j+1+gridWidth)%gridWidth] ;//up-right
//return count;
//cout << count;
printf("%d", grid[i][j]);
// Cell is lonely and dies
if ((grid[i][j] == 1) && (count < 2)){
nextgrid[i][j] = 0;
}
// Cell dies due to over population
else if((grid[i][j] == 1) && (count > 3)){
nextgrid[i][j] = 0;
}
// A new cell is born
else if ((grid[i][j] == 0) && (count == 3)){
nextgrid[i][j] = 1;
}
// Remains the same
else{
nextgrid[i][j] = grid[i][j];
}
}
}
//assign current grid to be the next grid
for(int i=0;i<gridHeight;i++){
for(int j=0;j<gridWidth;j++){
grid[i][j] = nextgrid[i][j];
}
}
genCount++;
}
}
答案 0 :(得分:0)
说grid1d[z]
是grid[x][y]
的一维表示,其中x
,y
是二维矩阵的大小,z
是大小的z = x * y
1d数组(也是gird[x1][x2]
)。假设您要使用与0 <=x1 < x,0 <= y1 < y
(grid1d[z1]
)对应的元素,那么您z1 = x1 * y + y1
位于OLDJAVA=$(ssh -q $server "java -version 2>&1 | cut -s -d '\"' -f2")
。