c - 生成随机不同数字的数组

标签 c arrays random

我想用 C 创建一个程序,它创建 N 对 (x,y) 随机数并遵守以下条件:

  • N 是 5 到 13 之间的随机数;
  • 所有对 (xi, yi) 都是不同的;
  • 所有 x 和 y 元素之间的绝对差值至少为 2。

为了解决这个问题,我有点绞尽脑汁。 我认为我应该创建三个函数:

  1. 一个函数,用于计算计算出的 x 或 y 元素与之前元素之间的差异;
  2. 另一个检查所有情侣是否不同的功能;
  3. 最后一个计算数组的函数。

现在我编写了这些函数:

int different (int i, int N, int adress)
{
// write something to get the array back from the address of first element      
int count = 0;
for (int k=0; k<i; k++)
    {
        if (array[k][0]=array[i][0] && array[k][1]=array[i][1])
        count++;
    }
    return count;
}

/

int distance (int x, int i, int N, int adress)
{   
// write something to get the array back from the address of first element
    int count=0;
    for (int k = 0; k < i; ++k)
    {
        if (abs(array[i][x]-array[k][x]) < 2)
            count++;
    return count;
    }
}

/

type coordinates (void)
{
    N = rand()%8 + 5;
    int array[N][2];
    for (int i = 0; i < N; ++i)
    {
        do
        {
            int x = rand()%60 - 30;
            int y = rand()%60 - 30;
        } while (different(i, N, adress)>0 || distance(x, i, N, adress) || distance (y, i, N, adress));
        array[i][0] = x;
        array[i][1] = y;
    }
}

实际上我不知道如何将一个函数的参数传递给另一个函数。我想我应该使用指针,但不知道如何使用。

如果有人能帮助我,我的大脑会很高兴。因为我试图改变我对这个问题的看法,但总有一些问题是我可以解决的。

提前谢谢您! :)

最佳答案

首先,我建议这样做(尽管这不是强制性的):

struct complex_number {
    int real;
    int img;
};

如果适合您的风格,请键入该结构。按照您已经执行的方式,一次生成一个复数值。然后,不要编写复杂的 while 条件,而是编写一个像

这样的函数

int is_candidate(结构复数*数组,size_t大小,结构复数候选)

您可以在其中收集确定数字是否为候选数字的所有逻辑。

在这个函数中,您可以坚持使用您的函数,但目前您似乎在正确的 C 语法方面遇到了一些问题。有两个主要问题:你永远不会传递实际的数组,并且你使用 = 进行比较,这是赋值,你应该使用 ==

举个例子:

//impelement your functions - left out
int is_same(struct complex_number c1, struct complex_number c2);
int check_distance(struct complex_number c1, struct complex_number c2);

int is_candidate(struct complex_number *array, size_t size, struct complex_number candidate){
   int i;
   for (i = 0; i < size; ++i){
      if (is_same(array[i], candidate) 
         || !(check_distance(array[i], candidate)){
          return false;
      }
   }
   return true;
}

您可以通过指针传递候选值,但在这种情况下,结构体非常小,可能不值得付出努力。如果您的候选有效,您可以将其附加到数组的后面。您可以在此示例(数组)中了解如何将数组声明为函数参数,以及如何需要传递大小。此信息与数组无关。 您可以将数组直接传递到此函数中,而无需获取其地址或类似内容。

关于c - 生成随机不同数字的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28160687/

相关文章:

c - 使用 MPI-IO 和笛卡尔拓扑编写分布式数组

c - 为什么权限参数会影响我的小型测试程序中写入文件的内容?

java - 如何从 ArrayList<ArrayList<String[]> 获取元素?

c - 在 C 中生成离散均匀分布

python - 多个二项式随机变量的向量化采样

java - 从 JAVA 中将数字四舍五入到 10^

c - gethostbyaddr : Success 上出现错误

不能包含这两个文件(WinSock2、Windows.h)

javascript - 删除数字数组中的所有重复数字

arrays - 将数组放入等长的 'n' 组中