You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成指定1的数量的4元素0-1随机int数组?

生成指定数量1的随机0-1数组解决方案

问题分析

你当前的代码通过rand()%2随机生成每个元素,无法精准控制数组中1的数量。要实现固定数量1、其余为0的随机数组,需要换一种生成逻辑。

修改后的实现代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// 生成含指定数量1的4元素0-1数组,count取值为1、2、3
int *tableauDeLed(int count) {
    static int tableau[4];
    // 先初始化数组全为0
    for (int i = 0; i < 4; i++) {
        tableau[i] = 0;
    }

    // 方法1:随机选位置设为1(避免重复选中)
    int set = 0;
    while (set < count) {
        int idx = rand() % 4;
        if (tableau[idx] == 0) {
            tableau[idx] = 1;
            set++;
        }
    }

    // 方法2:洗牌法(更高效,无重复判断)
    // 先构造含count个1的有序数组
    // for (int i = 0; i < count; i++) {
    //     tableau[i] = 1;
    // }
    // for (int i = count; i < 4; i++) {
    //     tableau[i] = 0;
    // }
    // Fisher-Yates洗牌打乱顺序
    // for (int i = 3; i > 0; i--) {
    //     int j = rand() % (i + 1);
    //     int temp = tableau[i];
    //     tableau[i] = tableau[j];
    //     tableau[j] = temp;
    // }

    return tableau;
}

int main() {
    // 初始化随机数种子,确保每次运行随机序列不同
    srand((unsigned int)time(NULL));

    // 测试生成1个1的数组
    printf("生成1个1的数组:\n");
    for (int y = 0; y < 5; y++) {
        int *tableau = tableauDeLed(1);
        for (int i = 0; i < 4; i++)
            printf("%d, ", tableau[i]);
        printf("\n");
    }

    // 测试生成2个1的数组
    printf("\n生成2个1的数组:\n");
    for (int y = 0; y < 5; y++) {
        int *tableau = tableauDeLed(2);
        for (int i = 0; i < 4; i++)
            printf("%d, ", tableau[i]);
        printf("\n");
    }

    // 测试生成3个1的数组
    printf("\n生成3个1的数组:\n");
    for (int y = 0; y < 5; y++) {
        int *tableau = tableauDeLed(3);
        for (int i = 0; i < 4; i++)
            printf("%d, ", tableau[i]);
        printf("\n");
    }

    return 0;
}

代码说明

  1. 随机数种子初始化:main开头的srand((unsigned int)time(NULL))是必须的,否则每次运行程序会生成完全相同的随机序列。
  2. 两种实现思路:
    • 方法1:先把数组全设为0,循环随机选择索引,直到设置够指定数量的1。若选中已为1的位置则重新选择,保证不重复设置。
    • 方法2:先构造前count位为1、其余为0的有序数组,再用Fisher-Yates洗牌算法打乱顺序,无需重复判断,效率更高。
  3. static数组注意事项:函数中用static int tableau[4]意味着数组内存是全局的,多次调用会覆盖之前的结果。如果需要保留多组数组,建议改为让用户传入数组指针作为参数(如void tableauDeLed(int *tableau, int count)),避免数据覆盖。

测试效果

运行程序后,会分别输出5组含1个、2个、3个1的随机数组,每个数组的1的位置随机,且数量精准符合要求。

内容的提问来源于stack exchange,提问作者philippe82000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 20:17:32