編寫一個程序,該程序跨10 x 10陣列生成「隨機遊走」。該數組將包含字符(最初爲'。')。程序必須從元素隨機「走」,總是向上,向下,向左或向右移動一個元素。程序訪問的元素將按照訪問的順序以字母A到Z進行標記。這裏的期望輸出的一個例子: 發現此程序中生成「隨機遊走」的錯誤
這是我的漂亮的代碼,有時工作太可怕了,有時候並不在所有的工作:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10//max 127 because of signed char array
#define DIRECTIONS 4//up, down, left, right
int main(void)
{
bool success0 = true, success1 = true, success2 = true, success3 = true;//to check if one path is available or not
int row, column, direction;
signed char array[SIZE][SIZE], letter;
//seeds the random number generator
srand((unsigned)time(NULL));
//INITIALIZES ARRAY
for(row = 0; row < SIZE; row++){
for(column = 0; column < SIZE; column++){
array[row][column] = '.';
}
}
//PATH OF THE ALPHABET
row = 0;
column = 0;
for(letter = 'A'; letter <= 'Z'; letter++){
direction = rand() % DIRECTIONS;
//Outer if checks that we are not in the boundary of the array, outer else applies the offset.
//Inner if checks that the element is "empty", inner else makes the letter loop to be repeated.
switch(direction){
case 0://up
if(row == 0){
letter--;
success0 = false;
}
else{
row--;
if(array[row][column] == '.'){
array[row][column] = letter;
success0 = true;
success1 = true;
success2 = true;
success3 = true;
}
else{
letter--;
success0 = false;
}
}
break;
case 1://right
if(column == SIZE - 1){
letter--;
success1 = false;
}
else{
column++;
if(array[row][column] == '.'){
array[row][column] = letter;
success0 = true;
success1 = true;
success2 = true;
success3 = true;
}
else{
letter--;
success1 = false;
}
}
break;
case 2://down
if(row == SIZE - 1){
letter--;
success2 = false;
}
else{
row++;
if(array[row][column] == '.'){
array[row][column] = letter;
success0 = true;
success1 = true;
success2 = true;
success3 = true;
}
else{
letter--;
success2 = false;
}
}
break;
case 3://left
if(column == 0){
letter--;
success3 = false;
}
else{
column--;
if(array[row][column] == '.'){
array[row][column] = letter;
success0 = true;
success1 = true;
success2 = true;
success3 = true;
}
else{
letter--;
success3 = false;
}
}
break;
default: printf("Error"); break;
}
//checks if all 4 directions are blocked
if(success0 == false && success1 == false && success2 == false && success3 == false){
printf("All four directions are blocked: program must terminate.\n");
return 0;
}
}
//PRINTS ARRAY
for(row = 0; row < SIZE; row++){
for(column = 0; column < SIZE; column++){
putchar(array[row][column]);
putchar(' ');
}
putchar('\n');
}
return 0;
}
提示:使用函數srand和RAND函數生成隨機數字。在執行移動之前,請檢查(a)它不會超出數組範圍,並且(b)它不會將我們帶到已分配字母的元素。如果違反任一條件,請嘗試向另一個方向移動。如果全部四個方向都被阻止,程序必須終止。
你想讓我們做你的功課嗎? – Loocid 2015-03-31 00:33:19
這不像一個問題。這對其他用戶來說更是一個挑戰。此外,描述你的代碼很漂亮,但也說它有時候工作可怕是有點混亂。 – Ben 2015-03-31 00:36:17
發現錯誤?怎麼樣告訴我們編譯器顯示的錯誤是什麼?如果它編譯那麼這就是你的錯誤,並有簡單的調試技術,可以很容易地找到所述的錯誤。 – DigitalNinja 2015-03-31 00:39:15