【发布时间】:2025-11-24 12:05:02
【问题描述】:
我刚开始学习 c#。我的 List 有问题,我无法解决: 如果“个人”,我需要生成一个列表。每个个体都是一个整数序列。 (我在这里使用遗传算法解决旅行商问题) 例如,我有一个单独的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace TravellingSalesman
{
public class individ
{
public int[] individSequence { set; get; }
public int fitnessFunction { set; get; }
public individ(int size)
{
individSequence = new int[size];
individSequence = RandomNumbers(size).ToArray(typeof(int)) as int[];
}
public ArrayList RandomNumbers(int max)
{
// Create an ArrayList object that will hold the numbers
ArrayList lstNumbers = new ArrayList();
// The Random class will be used to generate numbers
Random rndNumber = new Random();
// Generate a random number between 1 and the Max
int number = rndNumber.Next(1, max + 1);
// Add this first random number to the list
lstNumbers.Add(number);
// Set a count of numbers to 0 to start
int count = 0;
do // Repeatedly...
{
// ... generate a random number between 1 and the Max
number = rndNumber.Next(1, max + 1);
// If the newly generated number in not yet in the list...
if (!lstNumbers.Contains(number))
{
// ... add it
lstNumbers.Add(number);
}
// Increase the count
count++;
} while (count <= 10 * max); // Do that again
// Once the list is built, return it
return lstNumbers;
}
}
现在我想创建这个对象的列表: 列表列表; ... 在 c-tor 中: list = new List();
现在我正在尝试将对象添加到列表中并为将来的工作获取它们
private void createFirstGeneration()
{
for (int i = 0; i != commonData.populationSize; ++i)
{
individ newIndivid = new individ(commonData.numberOfcities);
list.Add(newIndivid);
for (int j = 0; j != commonData.numberOfcities; ++j)
System.Console.Write(((individ)list[i]).individSequence[j]);
System.Console.WriteLine();
}
for (int i = 0; i != commonData.populationSize; ++i)
{
for (int j = 0; j != commonData.numberOfcities; ++j)
System.Console.Write(((individ)list[i]).individSequence[j]);
System.Console.WriteLine();
}
}
commonData.populationSize 是人口中个体的数量。 但是这个例子的两个输出有不同的输出。
312
213
213
213
213
312
213
213
213
213
我是 C# 的新手,请问您能帮帮我吗?
【问题讨论】:
-
你想达到什么目的?
-
访问individualSequence没有问题。从列表中获取数据有问题
-
你可能想问这个:*.com/questions/767999/…
标签: c# .net list data-structures