[英]C# How do I append the previous item in array to the next item in the array for unknown number of items?
[英]C# Adding previous number in array to the next
这是我的第一篇文章:)好吧我正在尝试创建一个程序,随机地将1或-1添加到起始值0.此过程以500步左右进行,然后最终结果需要添加到阵列。 这是我到达了多远:
using System;
using System.Collections.Generic;
namespace dimensionrandomwalk
{
class MainClass
{
public static void Main (string[] args)
{
Random rnd = new Random();
int[] x;
x = new int[500];
for (int i = 0; i < 500; i++){
int L = rnd.Next (0, 2);
int L1 = -1;
int L2 = 1;
if (L == 0) {
x [i] = L1;
} else if (L == 1) {
x [i] = L2;
}
x[i] = x[i+1]+x[i];
Console.WriteLine (x[i]);
}
}
}
}
我将制作两个阵列,一个包含500个步骤,另一个包含100个最终结果。 但我无法用x [2]添加x [1]等等直到x [500]。 谢谢:)
认为这是你想要的:
using System;
using System.Collections.Generic;
namespace dimensionrandomwalk
{
class MainClass
{
public static void Main (string[] args)
{
Random rnd = new Random();
int[] x;
x = new int[500];
for (int i = 0; i < 500; i++){
int L = rnd.Next (0, 2);
x[i] = (L==0) ? -1 : 1;
Console.WriteLine (x[i]);
}
int total_value = 0;
for (int i = 0; i < 500; i++
total_value += x[i];
Console.WriteLine ("Total: " + total_value);
}
}
}
或者,如果您不关心临时数组:
using System;
using System.Collections.Generic;
namespace dimensionrandomwalk
{
class MainClass
{
public static void Main (string[] args)
{
Random rnd = new Random();
int total_value = 0;
for (int i = 0; i < 500; i++){
int L = rnd.Next (0, 2);
total_value += (L==0) ? -1 : 1;
}
Console.WriteLine ("Total: " + total_value);
}
}
}
你可以使用LINQ来获得你想要的东西。 此代码生成100次随机游走,每次500次迭代+ 1 / -1:
var rand = new Random();
var walks = Enumerable.Range(1,100)
.Select(item => Enumerable.Range(1, 500)
.Select(i => rand.Next(0, 2) * 2 - 1)
.Aggregate((i, j) => i + j));
'walking'IEnumerable中的每个项目都包含500次迭代随机游走的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.