gpt4 book ai didi

c++ - 如何在一维元胞自动程序中随机化字符串?

转载 作者:太空狗 更新时间:2023-10-29 20:42:21 25 4
gpt4 key购买 nike

我正在研究一个一维细胞自主程序,它需要一个由 20 个 1 和 0 组成的字符串。现在,我有一个常量字符串,每次都以相同的方式启动程序。我的问题:如何随机化字符串,以便每次运行程序时都能得到不同的结果?任何帮助将不胜感激。

到目前为止,这是我的代码:

#include <iostream>
#include <bitset>
#include <string>
#include <ctime>

using namespace std;

const int arrSize = 20;
int numGen = 10;
string Initial = "1001101010110100010";

int main()
{
bitset<arrSize + 2> array(Initial);

for(int i = 0; i < numGen; i++)
{
bitset<arrSize + 2> tempArr(array);

for(int k = arrSize; k >= 1 ; k--)
{
if(array[k])
cout << "1";
else
cout << "0";

int number = (int)array[k-1] << 2 | (int)array[k] << 1 | (int)array[k+1];

tempArr[k] = (number == 3 || number == 5 || number == 6);

}

array = tempArr;
cout << endl;
}
}

最佳答案

你可以在开始你的程序之前构建一个随机字符串。

string generateRandomString(){
string s = "";
for(int i=0;i<20;i++){
if(rand()%2==0) s+="0";
else s+="1";
}
return s;
}

然后把它作为你的主线的第一行 -

int main(){
srand(time(NULL));//Dont forget to seed your randoms!
Initial = generateRandomString();// btw making the variable Initial capitalzied does not follow convention.
....

还要确保添加以下内容 -

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

关于c++ - 如何在一维元胞自动程序中随机化字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19013589/

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