gpt4 book ai didi

c++ - 零和一的二维数组

转载 作者:行者123 更新时间:2023-11-30 03:51:18 24 4
gpt4 key购买 nike

我想生成一个由 0 和 1 组成的二维数组,其中 25% 为 0,75% 为 1。

我知道我将使用 rand()%2 函数,但我如何将零限制为仅占数组的 25%?

最佳答案

用零创建大小为 N 的 vector 。将第一个 N*0.75 元素设置为一个。随机化 vector 。

示例代码:

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <iterator>

int main ()
{
std::srand ( unsigned ( std::time(0) ) );

const int N = 100;
const int zero_percent = 25;
const int one_percent = 100-zero_percent;

const int one_count = (N * one_percent)/100;


std::vector<int> v(N);
std::fill(v.begin(), v.begin()+one_count, 1);

std::random_shuffle (v.begin(), v.end());


std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));

return 0;
}

输出

1 0 1 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 1 0 0 1 0 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 

实例:http://ideone.com/CdlaMy

关于c++ - 零和一的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31346161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com