[英]My method doesn't work as expected
我正在開發一個程序,該程序可以全天分配人員執行任務。
8個小時以來,我一直在努力找出方法的問題。 它應該使用一個名稱列表,一個任務列表和一個24小時計數器,並在X個小時將每個人分配給一個任務。如果該任務需要一個以上的人員,它也會嘗試分配下一個(如果沒有任何條件可以阻止該人被指派執行任務。
在分配了列表中的所有人員之后,程序應重置要分配的人員列表,然后重新開始分配他們。
當我運行代碼時,只有1輪分配,表的其余部分留為空白。
我試圖弄清楚邏輯上有什么問題,但我只是做不到,這太令人沮喪了! 所以請在這里幫助我!
編碼:
public string[,] AssignPersonsToMission()
{
bool containCondition; // any item of Person.Conditions is in mission.Conditions?
int assignedCounter = 0; // how many people assigned to a mission at given hour
string[,] table = new string[missions.Count, 24]; // columns = missions, rows = hour of day
List<Person> personsToAssign = persons; // filling list with people to assign
List<Person> assignedPersons = new List<Person>(); // a list of people that have been assigned
for (int mission = 0; mission < missions.Count; mission++) //go throught columns
{
for (int hour = 0; hour < 24; hour++) //go through rows
{
if (personsToAssign.Count == 0) //if all the people have been assigned to missions
{
personsToAssign = persons; // refill personsToAssign list with original list of people
assignedPersons.Clear(); // reset assigned Persons list
}
assignedCounter = 0; // reset assignedCounter
foreach (Person person in personsToAssign.ToList()) //go through each person that can be assigned
{
containCondition = missions[mission].Conditions.Intersect(person.Conditions).Any(); // is there any condition in mission that the person has?
//if yes - that person cannot be assigned to the mission
if (!containCondition)
{
table[mission, hour] += person.Name + "|"; //put person in mission at a given hour
assignedPersons.Add(person); //add the person to a list of assigned people
personsToAssign.Remove(person);//remove the person from the list of people to assign
assignedCounter++;//increament how many people assigned to this mission at this hour
if (assignedCounter < missions[mission].NumOfPeople) //if not enough people have been assigned to the mission
{
continue; //go to the next person to assign
}
else { break; }//go the the next hour
}// END OF if (!containCondition)
}//END OF foreach (Person person in personsToAssign.ToList())
}//END OF for (int hour = 0; hour < 24; hour++)
}//END OF for (int mission = 0; mission < missions.Count; mission++)
return table;
}
問題是您要更改原始列表persons
更改此:
List<Person> personsToAssign = persons;
至:
List<Person> personsToAssign = new List<Person> (persons);
您不是在復制列表,而是對其設置引用。 因此,如果您從personsToAssign
刪除一個人,由於兩個變量都指向內存中的同一列表,因此您也將其從persons
刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.