Beispiel #1
0
        public void TestRemovingFeedbackReceivers()
        {
            FieldSize fieldsize = new FieldSize {
                Xmin = 0, Xmax = 4, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
            };
            IParticleGenerator particleGenerator        = new RandomParticleGenerator(new ContinuousUniform());
            IResampler         resampler                = new MultinomialResampler();
            INoiseGenerator    noiseGenerator           = new RandomNoiseGenerator(new ContinuousUniform());
            ISmoother          smoother                 = new MovingAverageSmoother(200);
            ParticleFilter     filter                   = new ParticleFilter(250, 0.1f, fieldsize, particleGenerator, resampler, noiseGenerator, smoother);
            Mock <IOrientationFeedbackReceiver> orifeed = new Mock <IOrientationFeedbackReceiver>();

            filter.RegisterReceiver(orifeed.Object);
            filter.RegisterReceiver(orifeed.Object);
            filter.UnregisterReceiver(orifeed.Object);
            filter.UnregisterReceiver(orifeed.Object);
            Mock <IPositionFeedbackReceiver> posfeed = new Mock <IPositionFeedbackReceiver>();

            filter.RegisterReceiver(posfeed.Object);
            filter.RegisterReceiver(posfeed.Object);
            filter.UnregisterReceiver(posfeed.Object);
            filter.UnregisterReceiver(posfeed.Object);
            filter.CalculatePose(10);
            posfeed.Verify(f => f.NotifyPositionFeedback(It.IsAny <FeedbackData <Vector3> >()), Times.Never);
            orifeed.Verify(f => f.NotifyOrientationFeedback(It.IsAny <FeedbackData <Vector3> >()), Times.Never);
        }
Beispiel #2
0
        private void DataSort()
        {
            int row = 0;

            foreach (string line in iDataValidator.GetValidatedLines())
            {
                //**A**
                var coordinatesPair = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                //**B**
                if (row == 0)
                {
                    FieldSize.SetFieldSize(coordinatesPair[0], coordinatesPair[1]);
                }

                //**C**
                else if (row >= 1)
                {
                    Point newPoint = iPoint.CreatePoint();
                    newPoint.SetPoint(coordinatesPair[0], coordinatesPair[1]);
                    PointsByX.Add(newPoint);
                }
                row++;
            }
            //**D**
            PointsByX = PointsByX.OrderBy(o => o.X).ToList();
        }
Beispiel #3
0
        /// <summary>
        /// Gets a string representing the function call to reference the specified memory.
        /// </summary>
        public static string GetMemoryReference(uint address, FieldSize size)
        {
            var builder = new StringBuilder();

            AppendMemoryReference(builder, address, size);
            return(builder.ToString());
        }
Beispiel #4
0
        /// <summary>
        /// Gets a string representing the function call for retrieving the specified amount of memory.
        /// </summary>
        public static string GetSizeFunction(FieldSize size)
        {
            switch (size)
            {
            case FieldSize.Bit0: return("bit0");

            case FieldSize.Bit1: return("bit1");

            case FieldSize.Bit2: return("bit2");

            case FieldSize.Bit3: return("bit3");

            case FieldSize.Bit4: return("bit4");

            case FieldSize.Bit5: return("bit5");

            case FieldSize.Bit6: return("bit6");

            case FieldSize.Bit7: return("bit7");

            case FieldSize.LowNibble: return("low4");

            case FieldSize.HighNibble: return("high4");

            case FieldSize.Byte: return("byte");

            case FieldSize.Word: return("word");

            case FieldSize.DWord: return("dword");

            default: return(size.ToString());
            }
        }
Beispiel #5
0
        public MemoryAccessorFunction(string name, FieldSize size)
            : base(name)
        {
            _size = size;

            Parameters.Add(new VariableDefinitionExpression("address"));
        }
Beispiel #6
0
        public void TestSize(string func, FieldSize expectedSize)
        {
            var requirements = Evaluate(func);

            Assert.That(requirements.Count, Is.EqualTo(1));
            Assert.That(requirements[0].Left.Size, Is.EqualTo(expectedSize));
        }
Beispiel #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ParticleFilter"/> class.
 /// </summary>
 /// <param name="noiseGenerator">See noiseGenerator argument of the constructor of <seealso cref="AbstractParticleFilter"/></param>
 /// <param name="resampleNoiseSize">See resampleNoiseSize argument of the constructor of <seealso cref="AbstractParticleFilter"/></param>
 /// <param name="resampler">See resampler argument of the constructor of <seealso cref="AbstractParticleFilter"/></param>
 /// <param name="particleGenerator">See particleGenerator argument of the constructor of <seealso cref="AbstractParticleFilter"/></param>
 /// <param name="particleAmount">See particleAmount argument of the constructor of <seealso cref="AbstractParticleFilter"/></param>
 /// <param name="fieldSize">The dimensions of the area where the user can be.</param>
 /// <param name="smoother">See smoother argument of the constructor of <seealso cref="AbstractParticleFilter"/></param>
 public ParticleFilter(int particleAmount, float resampleNoiseSize, FieldSize fieldSize, IParticleGenerator particleGenerator, IResampler resampler, INoiseGenerator noiseGenerator, ISmoother smoother)
 {
     this.posReceivers      = new List <IPositionFeedbackReceiver>();
     this.oriReceivers      = new List <IOrientationFeedbackReceiver>();
     this.positionFilter    = new PositionParticleFilter(noiseGenerator, resampleNoiseSize, resampler, particleGenerator, particleAmount, fieldSize, smoother);
     this.orientationFilter = new OrientationParticleFilter(noiseGenerator, resampleNoiseSize, resampler, particleGenerator, particleAmount, smoother.Clone());
 }
Beispiel #8
0
 // tries to schedule the turnament through the scheduleAll function from the ScheduleManager class. It calls the algorithm with the minimum number of fields required at first
 // and increments this number if the algorithm fails. If the number of fields reaches the number of fields available for the tournament and the algorithm fails a json object
 // with an error is returned. if the algorithm is successfull, or the tournament doesnt contain any fields in the right size, a json object with success is returned. lastly
 // if an exception is throw it returns a json object with an error.
 public ActionResult Schedule(int tournamentID, FieldSize fs)
 {
     try
     {
         int minNumOfFields = 0;
         Tournament t = db.TournamentSet.Find(tournamentID);
         int numOfFields = t.Fields.Count(x => x.Size == fs);
         if (numOfFields > 0 && t.Divisions.Any(x => x.FieldSize == fs))
         {
             minNumOfFields = sm.MinNumOfFields(tournamentID, fs);
             for (int i = minNumOfFields; i <= numOfFields; i++)
             {
                 if (sm.scheduleAll(tournamentID, fs, i))
                 {
                     return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
                 }
             }
         }
         else
         {
             return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
         }
         return Json(new { status = "error", errorCode = 1, message = "algoritmen fandt ingen løsning", MinNumOfFields = minNumOfFields }, JsonRequestBehavior.AllowGet);
         }
     catch (Exception)
     {
         return Json(new { status = "error", errorCode = 2, message = "fejl i programmet" }, JsonRequestBehavior.AllowGet);
     }
 }
 public GameViewModel(GameContent content, FieldSize fieldSize)
 {
     this.Content   = content;
     this.FieldSize = fieldSize;
     InitGame();
     TurnOverAllFields(false);
 }
Beispiel #10
0
        public string GetString()
        {
            var fieldTypeString = FieldType.ToString().ToLower() + ".";
            var fieldSizeString = FieldSize.ToString().ToLower();
            var offsetString    = string.Empty;

            if (Offset < 0)
            {
                offsetString = " -0x" + Math.Abs(Offset).ToString("X");
            }
            else
            {
                offsetString = " 0x" + Offset.ToString("X");
            }
            var positionString = " " + Position.Item1.ToString() + ".";

            if (Position.Item2 != null)
            {
                positionString += "--" + Position.Item2.ToString() + ".";
            }
            var abbreviationString = " \"" + Abbreviation;
            var descriptionString  = "," + Description + "\"";
            var statesString       = " \"" + string.Join(",", States) + "\"";

            return(Indentation + fieldTypeString + fieldSizeString + offsetString + positionString +
                   abbreviationString + descriptionString + statesString);
        }
Beispiel #11
0
        public string GetString()
        {
            var fieldTypeString = FieldType.ToString().ToLower() + ".";
            var fieldSizeString = FieldSize.ToString().ToLower();

            if (InnerFieldSize != null && InnerFieldSize != FieldSize.UNDEFINED)
            {
                fieldSizeString += "." + InnerFieldSize.ToString();
            }
            var offsetString = string.Empty;

            if (Offset < 0)
            {
                offsetString = " -0x" + Math.Abs(Offset).ToString("X");
            }
            else
            {
                offsetString = " 0x" + Offset.ToString("X");
            }
            var positionString = " " + Position.Item1.ToString() + ".";

            positionString += "--" + Position.Item2.ToString() + ".";
            var multiplierString   = " " + Multiplier.ToString() + ".";
            var abbreviationString = " \"" + Abbreviation;
            var descriptionString  = "," + Description + "\"";

            return(Indentation + fieldTypeString + fieldSizeString + offsetString + positionString +
                   multiplierString + abbreviationString + descriptionString);
        }
Beispiel #12
0
        public void TestGetSizeFromNote(string note, int expectedLength, FieldSize expectedFieldSize)
        {
            var n = new CodeNote(1, note);

            Assert.That(n.FieldSize, Is.EqualTo(expectedFieldSize));
            Assert.That(n.Length, Is.EqualTo(expectedLength));
        }
Beispiel #13
0
 public CodeNote(uint address, string note)
 {
     Address = address;
     Note = note;
     _length = 0;
     _fieldSize = FieldSize.None;
 }
Beispiel #14
0
 /// <summary>
 /// Initializes the world box, setting the localizer and the field size
 /// </summary>
 /// <param name="localizer">The used filter method</param>
 /// <param name="fieldSize">The size of the game field</param>
 public void Init(IUserLocalizer localizer, FieldSize fieldSize)
 {
     this.localizer = localizer;
     this.fieldSize = fieldSize;
     this.InitPlanes();
     this.metaFrame = GameObject.Find("MetaWorld/MetaFrame").transform;
 }
Beispiel #15
0
        public void Setup()
        {
            FieldSize fieldsize = new FieldSize
            {
                Xmax = 4,
                Ymax = 3,
                Xmin = 0,
                Ymin = 0,
                Zmax = 4,
                Zmin = -4
            };

            this.filter = new PositionParticleFilter(
                new RandomNoiseGenerator(new ContinuousUniform()),
                0.1f,
                new MultinomialResampler(),
                new RandomParticleGenerator(new ContinuousUniform()),
                200,
                fieldsize,
                new MovingAverageSmoother(500));

            this.posdist   = new Normal(0.1);
            this.posnoise  = new MathNet.Numerics.Distributions.Normal(0, 0.1);
            this.possource = new Mock <IPositionSource>();
            this.possource.Setup(foo => foo.GetPositionsClosestTo(It.IsAny <long>(), It.IsAny <long>())).Returns <long, long>((ts, range) => this.Pos(ts));
            this.filter.AddPositionSource(this.possource.Object);

            this.disdist   = new Normal(0.1);
            this.disnoise  = new MathNet.Numerics.Distributions.Normal(0, 0.1);
            this.dissource = new Mock <IDisplacementSource>();
            this.dissource.Setup(foo => foo.GetDisplacement(It.IsAny <long>(), It.IsAny <long>())).Returns <long, long>(this.Dis);
            this.filter.AddDisplacementSource(this.dissource.Object);
        }
Beispiel #16
0
        public void InitializeCellValuesOnFieldWithMinBoundOptionsShouldNotThrow()
        {
            var min   = FieldSize.MIN_XY;
            var size  = new FieldSize(min, min, FieldSize.GetMinMines());
            var field = new Field(size);

            field.InitializeCellValues(new PointI(0, 0));
        }
Beispiel #17
0
        public void InitializeCellValuesOnFieldWithMaxBoundOptionsShouldNotThrow()
        {
            var max   = FieldSize.MAX_XY;
            var size  = new FieldSize(max, max, FieldSize.GetMaxMines(max, max));
            var field = new Field(size);

            field.InitializeCellValues(new PointI(0, 0));
        }
Beispiel #18
0
        public void CreateFieldSizeWithValidOptionsShouldNotThrow()
        {
            var size = new FieldSize(X, Y, MINES);

            size.X.Should().Be(X);
            size.Y.Should().Be(Y);
            size.MinesTotal.Should().Be(MINES);
        }
Beispiel #19
0
        public void TestToString(FieldSize fieldSize, FieldType fieldType, double value, string expected)
        {
            var field = new Field {
                Size = fieldSize, Type = fieldType, Float = (float)value
            };

            Assert.That(field.ToString(), Is.EqualTo(expected));
        }
Beispiel #20
0
 public Field(ITetrominoSpawner _spawner, FieldSize _fieldSize, Vector3 _spawnPoint)
 {
     spawner    = _spawner;
     fieldSize  = _fieldSize;
     spawnPoint = _spawnPoint;
     grid       = new Transform[fieldSize.width, fieldSize.height];
     spawner.CreateTetrominoForField(this);
 }
Beispiel #21
0
        public void TestToString(FieldSize fieldSize, FieldType fieldType, int value, string expected)
        {
            var field = new Field {
                Size = fieldSize, Type = fieldType, Value = (uint)value
            };

            Assert.That(field.ToString(), Is.EqualTo(expected));
        }
    public void ParticleTest()
    {
        FieldSize fieldSize = new FieldSize()
        {
            Xmax = 4, Xmin = 0, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
        };

        Assert.True(LocalizerFactory.Get(Filters.Particle, fieldSize) is ParticleFilterCoupler);
    }
Beispiel #23
0
    public void Setup()
    {
        FieldSize fieldSize = new FieldSize()
        {
            Xmax = 4, Xmin = 0, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
        };

        this.coupler = new ParticleFilterCoupler(fieldSize);
    }
Beispiel #24
0
        public void TestDeserialize(string serialized, FieldSize fieldSize, FieldType fieldType, int value)
        {
            var field = Field.Deserialize(Tokenizer.CreateTokenizer(serialized));

            Assert.That(field, Is.Not.Null);
            Assert.That(field.Size, Is.EqualTo(fieldSize));
            Assert.That(field.Type, Is.EqualTo(fieldType));
            Assert.That(field.Value, Is.EqualTo(value));
        }
Beispiel #25
0
    private void GenerateSize()
    {
        int xSize = Random.Range(settings.SizeMin, settings.SizeMax);
        int ySize = Random.Range(settings.SizeMin, settings.SizeMax);

        field = new FieldSize(xSize, ySize);

        Debug.Log("Generate field with: x - " + xSize + ", y - " + ySize);
    }
Beispiel #26
0
 public void TestToStringCulture(FieldSize fieldSize, FieldType fieldType, double value, string expected)
 {
     using (var cultureOverride = new CultureOverride("fr-FR"))
     {
         var field = new Field {
             Size = fieldSize, Type = fieldType, Float = (float)value
         };
         Assert.That(field.ToString(), Is.EqualTo(expected));
     }
 }
Beispiel #27
0
    /// <summary>
    /// Initializes a new instance of the <see cref="ParticleFilterCoupler"/> class
    /// </summary>
    /// <param name="fieldSize">The preferred game field size</param>
    public ParticleFilterCoupler(FieldSize fieldSize)
    {
        int particleamount           = 300;
        IParticleGenerator prtclgen  = new RandomParticleGenerator(new ContinuousUniform());
        INoiseGenerator    noisegen  = new RandomNoiseGenerator(new ContinuousUniform());
        IResampler         resampler = new MultinomialResampler();
        ISmoother          smoother  = new MovingAverageSmoother(1000);

        this.localizer = new ParticleFilter(particleamount, 0.1f, fieldSize, prtclgen, resampler, noisegen, smoother);
    }
Beispiel #28
0
        public void TestSerialize(FieldSize fieldSize, FieldType fieldType, int value, string expected)
        {
            var field = new Field {
                Size = fieldSize, Type = fieldType, Value = (uint)value
            };
            var builder = new StringBuilder();

            field.Serialize(builder);
            Assert.That(builder.ToString(), Is.EqualTo(expected));
        }
Beispiel #29
0
        public void TestAppendStringHex(FieldSize fieldSize, int value, string expected)
        {
            var field = new Field {
                Size = fieldSize, Type = FieldType.Value, Value = (uint)value
            };
            var builder = new StringBuilder();

            field.AppendString(builder, NumberFormat.Hexadecimal);
            Assert.That(builder.ToString(), Is.EqualTo(expected));
        }
        private void UpdateMaxMines()
        {
            sldMines.Minimum = FieldSize.GetMinMines();
            var maxMines = FieldSize.GetMaxMines((int)sldWidth.Value, (int)sldHeight.Value);

            if (sldMines.Value > maxMines)
            {
                sldMines.Value = maxMines;
            }
            sldMines.Maximum = maxMines;
        }
Beispiel #31
0
        /// <summary>
        ///  Initializes the coupler
        /// </summary>
        /// <param name="localizer">Enum of the user filter name</param>
        /// <param name="fieldSize">The preferred size of the game field</param>
        /// <returns>The localizer coupler</returns>
        public static AbstractLocalizerCoupler Get(Filters localizer, FieldSize fieldSize)
        {
            switch (localizer)
            {
            case Filters.Particle:
                return(new ParticleFilterCoupler(fieldSize));

            default:
                throw new ArgumentException(string.Format("{0} is not an existing localizer filter", localizer), "filter");
            }
        }
Beispiel #32
0
 // finds the minimum number of fields with the same field size that are needed to schedule the turnament by calling MinNumOfFields from the ShceduleManager class and
 // returns a json object with the values to the frontend if successfull or an error if something went wrong
 public ActionResult MinNumOfFields(int tournamentID, FieldSize fs)
 {
     try
     {
         Tournament t = db.TournamentSet.Find(tournamentID);
         int numOfAllFields = t.Fields.Count(x => x.Size == fs);
         int numOfMinFields = sm.MinNumOfFields(tournamentID, fs);
         return Json(new { status = "success", FieldsCount = numOfMinFields, AllFieldsCount = numOfAllFields }, JsonRequestBehavior.AllowGet);
     }
     catch(Exception)
     {
         return Json(new { status = "error" }, JsonRequestBehavior.AllowGet);
     }
 }
Beispiel #33
0
        public ActionResult Create(string name, int tournamentId, int MatchDuration, FieldSize FieldSize)
        {
            try
            {
                Tournament t = db.TournamentSet.Find(tournamentId);

                sm.DeleteSchedule(t.Id, db);

                Division d = db.DivisionSet.Add(new Division() { Name = name, FieldSize = FieldSize, MatchDuration = MatchDuration, Tournament = t });

                db.SaveChanges();

                return Json(new { status = "success", message = "New division added", id = d.Id }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { status = "error", message = "New division not added", details = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
Beispiel #34
0
        //calculates the minimum number of fields needed for every single match to be scheduled within the timeIntervals of a tournament
        public int MinNumOfFields(int tournamentID, FieldSize fs)
        {
            CupDBContainer db = new CupDBContainer();
            Tournament t = db.TournamentSet.Find(tournamentID);
            int duration = 0;
            foreach (Division d in t.Divisions)
            {
                if (d.FieldSize == fs)
                {
                    foreach (TournamentStage ts in d.DivisionTournament.TournamentStage)
                    {
                        duration += (d.MatchDuration * ts.Matches.Count());
                    }
                }

            }
            double tDuration = 0;
            foreach (TimeInterval ti in t.TimeIntervals)
            {
                tDuration += (ti.EndTime - ti.StartTime).TotalMinutes;
            }
            return (int)Math.Ceiling((duration / tDuration));
        }
Beispiel #35
0
        // tries to schedule every match in a tournament that is to be played on a field with size = fSize.
        // it is also restricted to numberOfFields number of fields
        public bool scheduleAll(int tournamentID, FieldSize fSize, int numberOfFields)
        {
            CupDBContainer db = new CupDBContainer();
            MatchGeneration mg = new MatchGeneration();
            Validator validator = new Validator();
            Tournament t = db.TournamentSet.Find(tournamentID);
            //set op a list of every tournamentStage, a list of all group stage tournamentStages and a list of all matches
            List<TournamentStage> TournamentStages = db.TournamentStageSet.Where(x => x.DivisionTournament.Division.Tournament.Id == t.Id && x.DivisionTournament.Division.FieldSize == fSize).ToList();
            List<TournamentStage> TournamentStagesToSchedule = TournamentStages.Where(x => !x.Pool.IsAuto).ToList();
            List<Match> allMatches = db.MatchSet.Where(x => x.TournamentStage.DivisionTournament.Division.Tournament.Id == t.Id && x.TournamentStage.DivisionTournament.Division.FieldSize == fSize).ToList();

            //selector is used to get the next tournamentStages in the list if the previous one was not usable
            int selector = 0;
            //dayCount restricts the number of days available for the algorithm at the start. it will be incremented as the algorithm goes on
            int dayCount = 1;
            //indicator is used to select either the first or the last match from a tournamentStage
            int indicator = 1;
            //IsScheduled is used to see if the algorithm is successfull
            bool IsScheduled = false;
            while (!IsScheduled)
            {
                //list of all unscheduled tournamentStages ordered by number of matches, in decending order
                List<TournamentStage> unscheduledTournamentstages = TournamentStagesToSchedule.Where(x => !x.IsScheduled).OrderByDescending(x => x.Matches.Count(y => !y.IsScheduled)).ToList();

                //if there is no more unscheduled tournamentStages, we are either done with the groupstages of done with the shole schedule
                if (unscheduledTournamentstages.Count == 0)
                {
                    if (TournamentStagesToSchedule.All(x => !x.Pool.IsAuto))
                    {
                        TournamentStagesToSchedule.Clear();
                        TournamentStagesToSchedule = TournamentStages.Where(x => x.Pool.IsAuto).ToList();
                        continue;
                    }
                    else
                    {
                        IsScheduled = true;
                        continue;
                    }
                }
                //if after an update to the number of unscheduled tournamentstages the selector is out of range, reset it
                if (selector >= unscheduledTournamentstages.Count)
                {
                    selector = 0;
                }
                // select the first tournamentStage in the list unless it is not usable use the next, if that is not usable select the next and so on.
                TournamentStage ts = unscheduledTournamentstages.ElementAt(selector);
                {
                    //check if any teams has a previous pool that is not scheduled yet
                    bool isReady = true;
                    foreach (Team team in ts.Pool.Teams)
                    {
                        if (team.PrevPool == null)
                        {
                            continue;
                        }
                        else if (team.PrevPool.TournamentStage.IsScheduled)
                        {
                            if (ts.TimeInterval.StartTime < team.PrevPool.TournamentStage.TimeInterval.EndTime)
                            {
                                ts.TimeInterval.StartTime = team.PrevPool.TournamentStage.TimeInterval.EndTime;
                            }
                        }
                        else
                        {
                            isReady = false;
                            break;
                        }
                    }
                    if (!isReady)
                    {
                        selector++;
                    }
                    else
                    {
                        //get all uncheduled matches in the tournamentStage
                        List<Match> unscheduledMatches = ts.Matches.Where(x => !x.IsScheduled).ToList();
                        Match matchToSchedule;
                        //set the tournamentStage to scheduled in there are no unscheduled matches
                        if (unscheduledMatches.Count == 0)
                        {
                            DateTime lastMatchStart = ts.Matches.Max(x => x.StartTime);
                            ts.TimeInterval.EndTime = lastMatchStart.AddMinutes(ts.DivisionTournament.Division.MatchDuration * 2);
                            ts.IsScheduled = true;
                            continue;
                        }
                        //select the first or last match
                        else if (indicator > 0)
                        {
                            matchToSchedule = unscheduledMatches.First();

                        }
                        else
                        {
                            matchToSchedule = unscheduledMatches.Last();
                            //if we get the last match increment selector. this is done such that we go to the next tournamentStage if this match is not schedule in the following code
                            selector++;
                        }

                        //list of all fields
                        List<Field> fields = matchToSchedule.TournamentStage.DivisionTournament.Division.Tournament.Fields.Where(x => x.Size == fSize).Take(numberOfFields).ToList();
                        List<Field> fieldsNotChecked = new List<Field>();
                        fieldsNotChecked.AddRange(fields);
                        //goes through each day available so far
                        for (int i = 0; i < dayCount; i++)
                        {
                            //order the fields by number of matches on the particular day
                            fieldsNotChecked = fieldsNotChecked.OrderBy(x => x.Matches.Count(y => y.StartTime.Date == x.NextFreeTime.ElementAt(i).FreeTime.Date)).ToList();
                            //check is the match can be scheduled at any fields nextFreeTime
                            foreach (Field field in fieldsNotChecked)
                            {

                                if (validator.areTeamsFree(matchToSchedule, field.NextFreeTime.ElementAt(i).FreeTime))
                                {
                                    matchToSchedule.StartTime = field.NextFreeTime.ElementAt(i).FreeTime;
                                    matchToSchedule.Field = field;
                                    field.NextFreeTime.ElementAt(i).FreeTime = field.NextFreeTime.ElementAt(i).FreeTime.AddMinutes(matchToSchedule.Duration);
                                    matchToSchedule.IsScheduled = true;
                                    db.Entry(field).State = System.Data.Entity.EntityState.Modified;
                                    break;
                                }

                            }

                            if (matchToSchedule.IsScheduled)
                            {
                                break;
                            }

                        }
                        // if the match is scheduled reset our selector and indicator
                        if (matchToSchedule.IsScheduled)
                        {
                            indicator = 1;
                            selector = 0;
                            db.Entry(matchToSchedule).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                }
                // if we got through every tournamentStage and all of the where not usable, this will force a match into the schedule by adding minutes to the fields nextFreeTimes untill a mach will fit
                if (selector >= unscheduledTournamentstages.Count )
                {
                    List<Match> allUnscheduledMatches = allMatches.Where(x => !x.IsScheduled).ToList();
                    //newDayCount to force a match in at the first day possible
                    int newDayCount = 1;
                    // viriable to increase the nextFreeTimes for the fields
                    int k = 0;
                    //shile loop that keeps going untill a new match is scheduled or the algorithm fails
                    bool done = false;
                    List<Field> fields = allUnscheduledMatches.First().TournamentStage.DivisionTournament.Division.Tournament.Fields.Where(x => x.Size == fSize).Take(numberOfFields).ToList();
                    while (!done)
                    {
                        k += 10;
                        //if every fields nextFreeTime added k minutes is passed the endtime of the tournament each give this part of the algorithm an extra day, give the shole algorithm an extra day or
                        // return false
                        if (fields.All(x => x.NextFreeTime.ElementAt(newDayCount - 1).FreeTime.AddMinutes(k) > t.TimeIntervals.ElementAt(newDayCount - 1).EndTime))
                        {
                            if (newDayCount < dayCount)
                            {
                                newDayCount++;
                                k = 0;
                                continue;
                            }
                            else if (dayCount < t.TimeIntervals.Count())
                            {
                                dayCount++;
                                done = true;
                                continue;
                            }
                            else
                            {
                                return false;
                            }
                        }

                        // go through each match and see if it can be scheduled at any field with the added k minutes
                        foreach (Match match in allUnscheduledMatches.Where(x => x.TournamentStage.TimeInterval.StartTime != DateTime.MinValue))
                        {

                            List<Field> fieldsNotChecked = new List<Field>();
                            fieldsNotChecked.AddRange(fields);
                            fieldsNotChecked = fieldsNotChecked.OrderBy(x => x.Matches.Count(y => y.StartTime.Date == x.NextFreeTime.ElementAt(newDayCount - 1).FreeTime.Date)).ToList();
                            foreach (Field field in fieldsNotChecked)
                            {
                                if (field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime.AddMinutes(k) >= t.TimeIntervals.ElementAt(newDayCount - 1).EndTime)
                                {
                                    continue;
                                }
                                if (validator.areTeamsFree(match, field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime.AddMinutes(k)))
                                {
                                    field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime = field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime.AddMinutes(k);
                                    match.StartTime = field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime;
                                    match.Field = field;
                                    field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime = field.NextFreeTime.ElementAt(newDayCount - 1).FreeTime.AddMinutes(match.Duration);
                                    match.IsScheduled = true;
                                    db.Entry(field).State = System.Data.Entity.EntityState.Modified;
                                    break;
                                }
                            }
                            if (match.IsScheduled)
                            {
                                selector = 0;
                                done = true;
                                break;
                            }
                        }
                    }
                }
                // get the indicator to the other side of 0 so we get the other end of the tournamentStages
                indicator *= -1;
            }
            db.SaveChanges();
            return true;
        }
Beispiel #36
0
 private bool Equals(FieldSize other)
 {
     return Height == other.Height && Width == other.Width;
 }
 private string MapSize(FieldSize size)
 {
     switch (size)
     {
         case FieldSize.ElevenVsEleven:
             return "11 v 11";
         case FieldSize.EightVsEight:
             return "8 v 8";
         case FieldSize.SixVsSix:
             return "6 v 6";
     }
     return "Unknown";
 }