[英]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.