public void SetMatch(int i, GiftTicketMatch match, GiftTicket newTicket) { //如果是款号有匹配的优惠券则完成匹配,否则,设置为空,那么优惠券就保留。 if (String.IsNullOrEmpty(match.Retail.GiftTickets)) { match.Ticket = null; genes[i] = match; } else { //款号有匹配的优惠券 String[] retailMatchTickets = match.Retail.GiftTickets.Split(','); List <String> retailMatchTicketList = new List <string>(retailMatchTickets); if (newTicket != null) { if (retailMatchTicketList.Contains(newTicket.ID)) { //匹配到了 tickets.Add(match.Ticket); match.Ticket = newTicket; tickets.Remove(newTicket); genes[i] = match; } else { tickets.Add(match.Ticket); match.Ticket = null; genes[i] = match; } } } }
private void SetMatch(int i, RetailDetail retail, GiftTicket ticket) { if (ticket == null) { //优惠券不够用了 genes[i] = new GiftTicketMatch() { Retail = retail, Ticket = null }; retails.Remove(retail); } //如果是款号有匹配的优惠券则完成匹配,否则,设置为空,那么优惠券就保留。 else if (String.IsNullOrEmpty(retail.MatchGiftTickets)) { //该款号没有匹配的优惠券。 genes[i] = new GiftTicketMatch() { Retail = retail, Ticket = null }; retails.Remove(retail); } else { //款号有匹配的优惠券 String[] retailMatchTickets = retail.MatchGiftTickets.Split(','); List <String> retailMatchTicketList = new List <string>(retailMatchTickets); if (retailMatchTicketList.Contains(ticket.ID)) { //匹配到了 genes[i] = new GiftTicketMatch() { Retail = retail, Ticket = ticket }; retails.Remove(retail); tickets.Remove(ticket); } else { genes[i] = new GiftTicketMatch() { Retail = retail, Ticket = null }; retails.Remove(retail); } } }
public void SetGene(int index, GiftTicketMatch value) { List <GiftTicket> tickets = new List <GiftTicket>(); tickets.AddRange(TicketsOrg); //如果 for (int i = 0; i < genes.Length; i++) { if (index != i) { if (genes[i] != null) { tickets.Remove(genes[i].Ticket); } } } if (tickets.Exists(t => t.ID == value.Ticket?.ID)) { //优惠券没有被占用,可以使用 genes[index] = value; fitness = 0; } else { //重新查找新的优惠券匹配 GiftTicket ticket = null; if (tickets.Count > 0) { Random random = new Random(GetRandomSeed()); int pickTicket = random.Next(0, tickets.Count); // int pickTicket = (int)(new Random().NextDouble() * tickets.Count); //随机拿一张优惠券 ticket = tickets[pickTicket]; } SetMatch(index, value, ticket); fitness = 0; } }
// 变异 private static void Mutate(GiftTicketIndividual indiv) { // Console.WriteLine("变异"); // Loop through genes for (int i = 0; i < indiv.Size(); i++) { if (new Random().NextDouble() <= mutationRate) { //从剩余的优惠券中,随机一个优惠券 GiftTicketMatch gene = indiv.GetGene(i); GiftTicket ticket = null; if (indiv.tickets.Count > 0) { Random random = new Random(GetRandomSeed()); int pickTicket = random.Next(0, indiv.tickets.Count); // int pickTicket = (int)(new Random().NextDouble() * indiv.tickets.Count); ticket = indiv.tickets[pickTicket]; indiv.SetMatch(i, gene, ticket); } } } }