public IList<PatternStart> RandomizeColoring() { //original color Dictionary<PatternStart, IList<Color>> startToColor = new Dictionary<PatternStart, IList<Color>>(); //keep track of the active patterns. Will contain new color List<PatternStart> active = new List<PatternStart>(); foreach (var start in _patternStarts) { IList<Color> colors = EffectsToColors(start.SampleEffect.ColorEffects); startToColor[start] = colors; OrderedSet<Color> distinct = new OrderedSet<Color>(); distinct.AddAll(colors); IDictionary<Color, Color> oldToNew = OldToNew(startToColor, active); Color randBase = distinct.FirstOrDefault(oldToNew.ContainsKey); IList<Color> newColors = randBase == default(Color) ? ColorPicker.PickColors(distinct.Count) : ColorPicker.PickColors(randBase, distinct.Count); IEnumerator<Color> newEnum = newColors.GetEnumerator(); IEnumerator<Color> oldEnum = distinct.GetEnumerator(); while(oldEnum.MoveNext()) { newEnum.MoveNext(); if (!oldToNew.ContainsKey(oldEnum.Current)) { oldToNew[oldEnum.Current] = newEnum.Current; } } start.ApplyColors(colors.Select(c=>oldToNew[c]).ToList()); active.RemoveAll(s => s.EndTime <= start.StartTime); active.Add(start); } return _patternStarts; }
public Slot Park(Vehicle vehicle) { try { var freeSlots = repo.GetAll().Where(a => a.VehicleSlots.Count(vs => vs.EndTime == null) == 0 && a.SlotTypeId >= vehicle.SlotTypeId && a.ReservationTypeId <= vehicle.User.ReservationTypeId && (a.UserId == null || a.UserId == vehicle.UserId)).ToList(); var comparisionA = new Comparison <Slot>((slot1, slot2) => { int comparer = 0; if (slot1.ReservationTypeId == vehicle.User.ReservationTypeId) { comparer = 0; } if (slot1.ReservationTypeId <= slot2.ReservationTypeId) { comparer = 1; } return(comparer); }); var comparisionB = new Comparison <Slot>((slot1, slot2) => { int comparer = 0; if (slot1.UserId == vehicle.UserId) { comparer = 0; } if (slot1.ReservationTypeId == vehicle.User.ReservationTypeId) { comparer = 0; } if (slot1.ReservationTypeId <= slot2.ReservationTypeId) { comparer = 1; } return(comparer); }); OrderedSet <Slot> slotsA = new OrderedSet <Slot>(freeSlots, comparisionA); OrderedSet <Slot> slots = new OrderedSet <Slot>(slotsA, comparisionB); var slotMatched = slots.FirstOrDefault(); var isBooked = false; if (slotMatched == null) { return new Slot() { Id = -1 } } ; lock (slotLock) { //Dual check after lock var isOccupied = vehicleSlotRepo.GetAll().Any(vs => vs.SlotId == slotMatched.Id && vs.EndTime == null); if (!isOccupied) { var vs = vehicleSlotRepo.Create(); vs.SlotId = slotMatched.Id; vs.VehicleId = vehicle.Id; vs.StartTime = DateTime.Now; vehicleSlotRepo.Add(vs); context.SaveChanges(); isBooked = true; } } if (!isBooked) { Park(vehicle); } //Eager load return(slotMatched); } catch (Exception ex) { throw ex; } }