【发布时间】:2018-11-21 19:32:12
【问题描述】:
Assignment 希望我们创建一个 5x10 的矩阵,其中包含随机且非重复出现的英文字母。但由于矩阵中有 52 个字母和 50 个房间,我不得不把它们收起来。但是如果我可以随机生成它们,我仍然会丢失两个字母,但不是相同的。
到目前为止我的代码是这样的;
#include <iostream>
#include <ctime> //for srand (number randomize)
using namespace std;
int main()
{
srand(time(0)); // generates random number
const int ROWS = 5; //declaration of rows
const int COLUMNS = 10; //declaration of columns
//writing content of the matrix
//I took out two letter (v and V) because matrix limit was 50 but all letters were 52
char harf[ROWS][COLUMNS] = {
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'},
{'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'},
{'U', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e'},
{'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'},
{'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z'}
};
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; ++j)
{
//generates a random index number
int index1 = rand() % 5; //random numbers 0 to 5
int index2 = rand() % 10; //random numbers 0 to 10
//swaps harf [i][j] with harf [index1][index2] for it won't be repating itself
char temp = harf[i][j];
harf[i][j] = harf[index1][index2];
harf[index1][index2] = temp;
}
}
//printing header and random order matrix
cout << "Random and nonrecurring matrix" << endl << endl;
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLUMNS; ++j)
cout << harf[i][j] << " ";
cout << endl << endl;
}
我试图这样做;
char harf[ROWS][COLUMNS];
for (int i = 0; i
{ for (int j = 0; j
{
harf[i][j] = rand() % 25 + 65 && rand() % 25 + 97; } }
我也尝试过用“||”做同样的事情,但似乎没有用。
由于这是一个作业,我不能使用比这种表达式更高级的东西。有人可以告诉我如何将英文字母放入该矩阵吗?
【问题讨论】:
-
从一个单独的一维数组中的所有大写和小写字母列表开始。随机删除两个。然后,将该数组中的每个元素与从数组中任意位置选择的随机元素交换。 (这是纸牌游戏和 MP3 文件玩家都知道的“洗牌”随机化。)然后将结果放入您的二维数组中,
-
除了随机删除两个字母外,您的尝试似乎与我所说的差不多。你的方法有什么问题?
-
我必须使用 2d 数组,并且我必须根据分配只使用 1。我做了这样的事情:` for (int i = 0; i
-
顺便说一句,除了我的一直缺少 V 和 v 之外,没有任何问题,但它应该是随机的,就像每次 2 个字母会丢失但不同。但我不能创建两个单独的矩阵或其他一维数组。