gpt4 book ai didi

C# 每次都用新值迭代 If 语句

转载 作者:行者123 更新时间:2023-11-30 12:59:17 25 4
gpt4 key购买 nike

是否可以在每次迭代时使用新值迭代嵌套的 if 语句?我正在尝试构建一维元胞自动机(对于家庭作业,我不能否认)并且我对 C# 完全陌生,因为以下代码无疑可以保证。我曾尝试使用最直接、最基本的 DIY 方法来创建这个程序,但我自己陷入了困境。

假设我有一串长度为 8 的 1 和 0

string y;
y = "11110000";

我想将此设置分解为 8 个子字符串集,每组 3 个子字符串,每个子字符串集包含 y 中的一个值及其两侧的单个值。所以从 0 开始计数,第 3 组是 110,第 7 组是 001。但是子字符串只会提供第 1 到第 6 组,因为我不能按照自己的喜好将它们围绕 y 循环,所以我定义了以下内容-

y1=y.Substring(7,1)+y+y.Substring(0,1);

使用 y1 我能够得到所有必要的子字符串。这些基本定义如下-

string a0, a1, a2, a3, a4, a5, a6, a7;
a0 = y1.Substring(0, 3);
a1 = y1.Substring(1, 3);
a2 = y1.Substring(2, 3);
a3 = y1.Substring(3, 3);
a4 = y1.Substring(4, 3);
a5 = y1.Substring(5, 3);
a6 = y1.Substring(6, 3);
a7 = y1.Substring(7, 3);

下一代元胞自动机的规则由该程序中的用户决定——也就是说用户可以选择子串是否为所有迭代,例如 111->0 或 1。我为每个子字符串使用了(非常多的)if 表,如下所示

                     {
if (a0=="000")
{
Console.Write(a);
}
else if (a0=="001")
{
Console.Write(b);
}
else if (a0 =="010")
{
Console.Write(c);
}
else if (a0 == "011")
{
Console.Write(d);
}
else if (a0 == "100")
{
Console.Write(e);
}
else if (a0 == "101")
{
Console.Write(f);
}
else if (a0 == "110")
{
Console.Write(g);
}
else if (a0 == "111")
{
Console.Write(h);
}
}

其中 a,b,c,d,e,f,g,h 是整数,是用户选择的规则。例如,用户决定每个集合 000 应该产生 1 值,然后 a=1。 b 对应于 {0,0,1},c 对应于 {0,1,0} 等等。但是,这种方法的一个相当明显的问题是,我最终只能得到 1 代我无法获得的整数。我很乐意用这个新一代(转换成字符串)替换 y1 。如果这不可能,请告诉我!

This link might also clear things up a bit

最佳答案

这就是您如何获得 A+ :D

  private static int[,] HipPriestsHomework()
{
string y = "11110000";
Console.WriteLine(y);
var rules = new[]
{
new {pattern = 0, result = 0},
new {pattern = 1, result = 1},
new {pattern = 2, result = 1},
new {pattern = 3, result = 1},
new {pattern = 4, result = 1},
new {pattern = 5, result = 0},
new {pattern = 6, result = 0},
new {pattern = 7, result = 0},
};
Dictionary<int, int> rulesLookup = new Dictionary<int, int>();
foreach(var rule in rules)
{
rulesLookup.Add(rule.pattern, rule.result);
}

int numGenerations = 10;
int inputSize = y.Length;
int[,] output = new int[numGenerations, inputSize];

int[] items = new int[y.Length];
for(int inputIndex = 0; inputIndex< y.Length; inputIndex++)
{
string token = y.Substring(inputIndex, 1);
int item = Convert.ToInt32(token);
items[inputIndex] = item;
}

int[] working = new int[items.Length];
items.CopyTo(working, 0);
for (int generation = 0; generation < numGenerations; generation++)
{
for (uint y_scan = 0; y_scan < items.Length; y_scan++)
{
int a = items[(y_scan - 1) % items.Length];
int b = items[y_scan % items.Length];
int c = items[(y_scan + 1) % items.Length];
int pattern = a << 2 | b << 1 | c;
var match = rules[pattern];
output[generation, y_scan] = match.result;
working[y_scan] = match.result;
Console.Write(match.result);
}
working.CopyTo(items, 0);
Console.WriteLine();
}

return output;
}

关于C# 每次都用新值迭代 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26341054/

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