【发布时间】:2015-01-27 20:11:20
【问题描述】:
我正在制作一个程序,我必须生成具有随机数且不重复的 N*N 二维数组,这样一个元素就是一个字母表。
此外,如果矩阵大小为 3,则元素必须在 1 到 8 之间且不重复且只有一个字母。
类似地,对于大小为 4 的矩阵,元素必须在 1 到 15 之间且不重复且单个字母。
谁能帮忙?
[代码]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int i,j,b,c,n ;
char ar[100][100];
char temp,ch;
printf("enter the size of the matrix : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
scanf("%d",&ar[i][j]);
printf("\t");
}
}
ar[n-1][n-1] = 'E';
// for printing the array
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
if(i==(n-1)&&j==(n-1))
{
printf("%c",ar[n-1][n-1]);
}
else
printf("%d",ar[i][j]);
printf("\t");
}
}
printf("\n Press 'w' for shifting up 's' for down 'a' for left and 'd' for right : \n");
while(1) //infinite loop
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(ar[i][j]=='E')
{
b = i; //storing row
c = j; // storing column
printf("\t");
ch = getch();
switch(ch)
{
case 'w':
if((i-1)>=0)
{
system("CLS");
temp = ar[i-1][j];
ar[i-1][j] = ar[i][j];
ar[i][j] = temp;
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
if(i==(b-1)&&j==c)
{
printf("%c",ar[n-1][n-1]);
}
else
printf("%d",ar[i][j]);
printf("\t");
}
}
printf("\t");
}
else
{
printf("wrong move bro");
}
break;
case 'a':
if((j-1)>=0)
{
system("CLS");
temp = ar[i][j-1];
ar[i][j-1] = ar[i][j];
ar[i][j] = temp;
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
if(i==b&&j==(c-1))
{
printf("%c",ar[n-1][n-1]);
}
else
printf("%d",ar[i][j]);
printf("\t");
}
}
printf("\t");
}
else
{
printf("wrong move bro");
}
break;
case 's' :
if((i+1)<n)
{
system("CLS");
temp = ar[i+1][j];
ar[i+1][j] = ar[i][j];
ar[i][j] = temp;
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
if(i==(b+1)&&j==c)
{
printf("%c",ar[n-1][n-1]);
}
else
printf("%d",ar[i][j]);
printf("\t");
}
}
printf("\t");
}
else
{
printf("wrong move bro");
}
break;
case 'd' :
if((j+1)<n)
{
system("CLS");
temp = ar[i][j+1];
ar[i][j+1] = ar[i][j];
ar[i][j] = temp;
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
if(i==b&&j==(c+1))
{
printf("%c",ar[n-1][n-1]);
}
else
printf("%d",ar[i][j]);
printf("\t");
}
}
printf("\t");
}
else
{
printf("\n wrong move bro");
}
break;
} //switch end
} //if end
} //for end
} //for end
} //while end
} // main end
[/代码]
【问题讨论】:
-
您的代码在哪里,有问题的代码在哪里?有代码吗?
-
只是一点提示:您不想生成唯一随机数的 N x N 序列(我假设是整数),而是将其视为将数字从 1 改组到 N x N . 另外:请表现出一些主动性,一旦你有一些代码,我们很乐意提供帮助。
-
上传了代码,虽然我认为这与我的问题无关。
-
您是对的,该代码使用
scanf允许用户填充数组,这与问题完全无关。顺便说一句,洗牌意味着Fisher-Yates shuffle。