1

我目前正在做一个司机调度项目,它处于初始阶段。我决定使用 GA 为驾驶员生成优化的时间表,并且与大多数 GA 项目一样,人口应以二进制表示。

例如,如果司机被分配了两个小时的任务并且他的工作时间是 9 小时,那么该特定日期的可能人口看起来像 110000000、011000000、001100000 等等。

作为 GA 的初始化,我想用两个参数(驱动程序的工作持续时间和工作持续时间)动态生成像 000110000 这样的可能基因。

我设法在布尔列表中获得完全随机的二进制代码(见下文),但这不是我想要表示的初始化。

这是在列表中生成随机二进制字符串(技术上是一堆布尔值)的部分代码。

private Random Rnd = new Random();
        //initial data
    private List<bool[]> CreateInitialData()
    {
        //generate 4 random genes (might be more)
        return Enumerable.Range(0, 1).Select(_ =>
        {
            var array = new bool[GeneLength];
            for(int i = 0; i < GeneLength; i++)
            {
                array[i] = Rnd.Next(0, 2) == 1;
            }
            return array;
        }).ToList();
    }

如何实现初始化函数以生成满足要求(司机工作时间、预计工作时间)的二进制代码?如果除了布尔列表之外还有更好的方法来表示它,请也提出建议。

4

1 回答 1

0

基于 1 小时的任务,我想出了这个:

private static void Main(string[] args)
{
    var genes = GetGenes(9, 2);
}

private static List<bool[]> GetGenes(int workinghours, int estimateddutyduration)
{
    // get the base representation 
    var hours = GetHours(workinghours, estimateddutyduration);
    var list = new List<bool[]>();
    for (int i = 0; i < (workinghours-estimateddutyduration)+1; i++)
    {
        // add
        list.Add(hours);
        // switch
        hours = SwitchArray(hours);
    }
    return list;
}

private static bool[] SwitchArray(bool[] array)
{
    // copy the array to a list
    var temp = array.ToList();
    // insert the last element at the front
    temp.Insert(0, temp.Last());
    // remove the last
    temp.RemoveAt(temp.Count-1);
    // return as array
    return temp.ToArray();
}

private static bool[] GetHours(int totalhours, int taskduration)
{
    // initialise the list
    var hours = new List<bool>(totalhours);
    // fill the list for the number of working hours
    for (int i = 0; i < totalhours; i++)
    {
        hours.Add(false);
    }
    // iterate for the task duration and set the hours as working
    for (int i = 0; i < taskduration; i++)
    {
        hours[i] = true;
    }
    // return as array
    return hours.ToArray();
}

对于 9, 2 回报

110000000
011000000
001100000
000110000
000011000
000000110
000000011

对于 9, 9 回报

111111111

对于 9、4 回报

111100000
011110000
001111000
000111100
000011110
000001111

这段代码非常冗长,我毫不怀疑它可以优化。但这是我最想传达的想法。

编辑:如果你想在控制台上显示结果

private static void ShowGenes(List<bool[]> genes)
{
    foreach (var gene in genes)
    {
        foreach (var bit in gene)
        {
            Console.Write(bit ? "1" : "0");
        }
        Console.Write("\n");
    }
}
于 2017-04-04T13:30:20.250 回答