我是編程的初學者,我已經被分配了一個小型項目。教練對我應該做什麼非常不清楚。我所知道的是這是一個「隨機遊走」,我不應該使用一種方法,我只需要使用循環,分支和隨機數生成器(甚至不知道這個)。它也應該從用戶那裏收到一些步驟,並根據給定的數字進行步行。無論如何,我是一個初學者,對C#的知識非常有限。我在這裏和其他許多地方進行了很多研究,但都沒有成功。代碼要麼非常複雜,要麼用其他語言。 我寫了一些代碼。我不知道這是否正確。 請給我一些指點。 有沒有錯誤,但程序不起作用,有條件的問題。隨機遊走算法的條件
static void Main(string[] args)
{
int row = 100;
int col = 100;
int[,] matrix;
matrix = new int[row, col];
int n;
Console.WriteLine("Enter the number of steps:");
n = int.Parse(Console.ReadLine());
const int up = 1;
const int down = 2;
const int left = 3;
const int right = 4;
int number=0;
for (int i=0;i<100;i++)
{
for (int j = 0; j < 100; j++)
matrix[i, j] = number;
}
Random randomdirection = new Random();
for (int counter = 0; counter < n; counter++)
{
int direction = randomdirection.Next(1, 5);
while (direction == 1)
{
if ((++col) < 100 && matrix[row, ++col] == 0)
{
matrix[row, ++col] = ++number;
}
else
break;
}
while (direction == 2)
{
if ((--col) < 100 && matrix[row, --col] == 0)
{
matrix[row, --col] = ++number;
}
else
break;
}
while (direction == 3)
{
if ((--row) < 100 && matrix[--row, col] == 0)
{
matrix[--row, col] = ++number;
}
else
break;
}
while (direction == 4)
{
if ((++row) < 100 && matrix[++row,col] == 0)
{
matrix[++row,col] = ++number;
}
else
break;
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
Console.WriteLine(matrix[i, j]);
}
Console.ReadKey();
}
這是分配: 酒鬼開始行走漫無目的,起始於燈柱。在每一個時間步,酒鬼都會忘記他或她在哪裏,並隨機一步,無論是北部,東部,南部還是西部,概率爲25%。 N級後,酒鬼離開燈柱多遠? 這是非常不完整的。 我們沒有教過類和方法,所以我們不應該使用它們。我認爲這一點是使用數組和循環和分支。 我自己寫了代碼。這就是爲什麼它很混亂。
改成了這樣: 好像我沒有看到這個問題:((
static void Main(string[] args)
{
Random randomObject = new Random();
int randomDirection;
int[,] mainarray;
int row=10;
int col=10;
mainarray=new int[row,col];
int number=0;
for (int b=0;b<row;b++)
{
for (int c=0;c<col;c++)
mainarray[b,c]=number;
}
while (true)
{
int n;
Console.WriteLine("Enter the number of steps: ");
n = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < n; i++)
{
randomDirection = randomObject.Next(1, 5);
if (randomDirection == 1 && row < 0 && row < 10)
mainarray[++row, col] = ++number;
if (randomDirection == 2 && row < 0 && row < 10)
mainarray[--row, col] = ++number;
if (randomDirection == 3 && col < 0 && col < 10)
mainarray[row, ++col] = ++number;
if (randomDirection == 4 && col < 0 && col < 10)
mainarray[row, --col] = ++number;
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
Console.Write(mainarray[i,j]);
}
}
Console.ReadKey();
}
你會很好地解釋你想達到什麼 – 2013-05-13 13:55:34
你從哪裏得到這段代碼?因爲我100%肯定你沒有寫這段代碼,所以你真的更好。多麼混亂...... – Joetjah 2013-05-13 13:56:06
'我不應該使用一種方法'是你的解釋還是要求教師? 「條件有問題」什麼是條件,以及你的「隨機遊走」邏輯如何流動? – Fendy 2013-05-13 13:56:11