Exemplo n.º 1
0
        public int FeedHamsters(int foodSupplies, Hamster[] hamsters)
        {
            long consumedTotal = 0;
            long greedSoFar = 0;
            int hamstersCount = 0;
            Arrays.MergeSort(hamsters);

            // complexity: O(N * log N) because of heap remove, heap peek
            while (hamstersCount < hamsters.Length)
            {
                long currentHamsterWillConsume = hamsters[hamstersCount].GetConsumption(hamstersCount);
                long totallyConsumedlIfAdded = consumedTotal + greedSoFar + currentHamsterWillConsume;

                // check if adding next hamster will fit the food supplies
                if (totallyConsumedlIfAdded > foodSupplies)
                {
                    break;
                }

                consumedTotal = totallyConsumedlIfAdded;
                greedSoFar += hamsters[hamstersCount].Greed;
                hamstersCount++;
            }

            return hamstersCount;
        }
Exemplo n.º 2
0
        public void Run(string inputFileName, string outputFileName)
        {
            try
            {
                var lines = File.ReadLines(inputFileName).ToArray();

                // range: 0 <= S <= 1 000 000 000
                int foodSupplies = int.Parse(lines[0]);

                // range: 1 <= C <= 100 000
                int hamsterCount = int.Parse(lines[1]);

                var hamsters = new Hamster[hamsterCount];
                //_hamstersHeap = new BinaryHeap<Hamster>(BinaryHeapOrder.Minimum, hamsterCount);
                //_hamstersList = new List<Hamster>();

                // complexity: O(N * log N) because of heap insert
                for (int i = 2; i < hamsterCount + 2; i++)
                {
                    var numbers = lines[i].Split(' ');
                    int h = int.Parse(numbers[0]);
                    int g = int.Parse(numbers[1]);
                    var hamster = new Hamster(h, g, hamsterCount - 1);
                    hamsters[i - 2] = hamster;
                    //_hamstersHeap.Add(hamster);
                }

                var result = FeedHamsters(foodSupplies, hamsters);
                File.WriteAllText(outputFileName, result.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 3
0
 public void HamsterLeft()
 {
     _fieldController.CellAdded(this);
     _hamster.transform.SetParent(null);
     _hamster.SetCell(null);
     _hamster = null;
 }
Exemplo n.º 4
0
        public async Task <HamsterResponse> UpdateAsync(int id, Hamster hamster)
        {
            var existingHamster = await _hamsterRepository.FindByIdAsync(id);

            if (existingHamster == null)
            {
                return(new HamsterResponse("Hamster not found."));
            }

            existingHamster.Name = hamster.Name;
            existingHamster.Age  = hamster.Age;

            try
            {
                _hamsterRepository.Update(existingHamster);
                await _unitOfWork.CompleteAsync();

                return(new HamsterResponse(existingHamster));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new HamsterResponse($"An error occurred when updating the hamster: {ex.Message}"));
            }
        }
Exemplo n.º 5
0
        public void AddService_Should_Throw_ArgumentNullException_When_Service_Is_Null()
        {
            // Arrange
            var hamster = new Hamster("name", AnimalGenderType.male, 1);

            // Act & Assert
            Assert.ThrowsException <ArgumentNullException>(() => hamster.AddServices(null));
        }
Exemplo n.º 6
0
        public void Constructor_Should_Create_New_Instance_Of_Class_Hamster()
        {
            // Arrange & Act
            var hamster = new Hamster("name", AnimalGenderType.male, 1);

            // Assert
            Assert.IsNotNull(hamster);
            Assert.IsInstanceOfType(hamster, typeof(Hamster));
        }
Exemplo n.º 7
0
        public void Constructor_Should_Initialize_ListOfServices()
        {
            // Arrange & Act
            var hamster = new Hamster("name", AnimalGenderType.male, 1);

            // Assert
            Assert.IsNotNull(hamster.Services);
            Assert.IsInstanceOfType(hamster.Services, typeof(List <IService>));
        }
Exemplo n.º 8
0
        public void Constructor_Should_Set_Correct_AnimalGenderType()
        {
            // Arrange & Act
            var hamster      = new Hamster("name", AnimalGenderType.male, 1);
            var actualType   = hamster.Gender;
            var expectedType = AnimalGenderType.male;

            // Assert
            Assert.AreEqual(expectedType, actualType);
        }
Exemplo n.º 9
0
        public void GetHamsterAge()
        {
            var animal = new Hamster {
                Name = "hamster1", AgeInHumanYears = 3
            };
            var expected = 174;
            var actual   = animal.AgeInHamsterYears;

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 10
0
        //Metod som lägger till hamstrar genom en for loop, ändra på variablen AmountToSimulate om man vill köra en större eller mindre simulering
        public void AddHamster()
        {
            using (var hamsterDb = new HamsterDb())
            {
                //Datetime för att printa ut dagens datum i consolen
                DateTime dateAndTime = DateTime.Now;
                DateTime date        = dateAndTime.Date;


                Console.Write("\nLaddar Hamstrar till dagiset");
                Thread.Sleep(1000);
                Console.Write(".");
                Thread.Sleep(1000);
                Console.Write(".");
                Thread.Sleep(1000);
                Console.Write(".");
                Thread.Sleep(1000);
                Console.Write(".");
                Console.WriteLine("");
                Console.WriteLine($"Checkar in hamstrar...Dagens datum och tid är: {date.ToString("dd/MM/yyyy")} 07:00:00");
                Console.WriteLine();

                //var Patient = new Hamster(RandomLogic.GenerateIdentity(), RandomLogic.GenerateExerciseLevel());

                //var hamster = Program.ProcessHamstrar("Hamsterlista30.csv");
                //if (!db.Hamster.Any())
                //{
                //    foreach (var item in hamster)
                //    {
                //        db.Hamster.Add(item);
                //        CurrentQueue.HamsterIKö.Add(item);
                //    }
                //}

                for (int i = 0; i < AmountToSimulate; i++)
                {
                    //Blir dubbletter av hamster, vet ej varför (kolla med Paul/Adam för en eventuell lösning)
                    Thread.Sleep(200);
                    var hamster = new Hamster(RandomLogic.GenerateIdentity(), RandomLogic.GenerateExerciseLevel());
                    hamsterDb.Hamster.Add(hamster);
                    CurrentQueue.HamsterIKö.Add(hamster);
                }

                //Sorterar databasen med hjälp av hamsterID och Motionsnivå, just för att det ska bli lättare att följa under testning. Påverkar ej funktionerna i programmet
                CurrentQueue.HamsterIKö = CurrentQueue.HamsterIKö.OrderByDescending(x => x.hamsterID).ThenBy(x => x.MotionsNivå).ToList();
                //Nedanför lägger vi till data i alla avdelningarna i databasen för att göra det möjligt att ladda in dem senare
                hamsterDb.Kö.Add(CurrentQueue);
                hamsterDb.Bur.Add(CurrentCage);
                hamsterDb.Aktivitet.Add(CurrentActivity);
                hamsterDb.Hemfärd.Add(CurrentHomecoming);
                hamsterDb.ResterandeHamster.Add(CurrentExercise);

                hamsterDb.SaveChanges();
            }
        }
Exemplo n.º 11
0
        public ActionResult New()
        {
            Hamster hamster = new Hamster();

            hamster.BreedSizeList  = GetAllSizes();
            hamster.BreedColorList = GetAllColors();
            hamster.ToysList       = GetAllToys();
            hamster.FoodList       = GetAllFood();
            hamster.Food           = new List <Food>();
            return(View(hamster));
        }
Exemplo n.º 12
0
        public void ListAnimalServices_Should__Return_Correct_Value_When_No_Services_Performed()
        {
            // Arrange
            var    hamster  = new Hamster("name", AnimalGenderType.male, 1);
            string expected = "No services performed yet";

            // Act
            string actual = hamster.ListAnimalServices();

            // Assert
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 13
0
        public void AddService_Should_Add_Service_To_ListOfServices()
        {
            // Arrange
            var service = new Mock <IService>().Object;
            var hamster = new Hamster("name", AnimalGenderType.male, 1);

            // Act
            hamster.AddServices(service);

            // Assert
            Assert.IsTrue(hamster.Services.Contains(service));
        }
Exemplo n.º 14
0
        // Metoden hittar den hamstern som väntat längst / ej motionerat eller motionerat minst
        private static int FindHamster()
        {
            using (var hamsterDb = new HamsterDb())
            {
                var queue    = hamsterDb.Kö.Find(CurrentQueue.Id);
                var cage     = hamsterDb.Bur.Find(CurrentCage.Id);
                var activity = hamsterDb.Aktivitet.Find(CurrentActivity.Id);

                Hamster hamster1 = null;
                Hamster hamster2 = null;
                Hamster hamster3 = null;

                if (queue.HamsterIKö.Count > 0)
                {
                    hamsterDb.Entry(queue).Collection(p => p.HamsterIKö).Load();
                    queue.HamsterIKö = queue.HamsterIKö.OrderByDescending(x => x.hamsterID).ThenBy(x => x.MotionsNivå).ToList();
                    hamster1         = queue.HamsterIKö[0];
                }
                if (cage.BurHamster.Count > 0)
                {
                    hamsterDb.Entry(cage).Collection(p => p.BurHamster).Load();
                    cage.BurHamster = cage.BurHamster.OrderByDescending(x => x.hamsterID).ThenBy(x => x.MotionsNivå).ToList();
                    hamster2        = cage.BurHamster[0];
                }

                if (activity.AktivitetHamster.Count > 0)
                {
                    hamsterDb.Entry(activity).Collection(p => p.AktivitetHamster).Load();
                    activity.AktivitetHamster = activity.AktivitetHamster.OrderByDescending(x => x.hamsterID).ThenBy(x => x.MotionsNivå).ToList();
                    hamster3 = activity.AktivitetHamster[0];
                }

                // returnerar 0 för bur och 1 för aktivitet
                // hittar vi hamster från båda avdelningarna så kollar vi den som väntat längst/motionerat minst
                if (hamster2 != null && hamster3 != null)
                {
                    if (hamster2.MotionsNivå.CompareTo(hamster3.MotionsNivå) == 0)
                    {
                        return(hamster2.CheckIn < hamster3.CheckIn ? 0 : 1);
                    }
                    return(hamster2.MotionsNivå > hamster3.MotionsNivå ? 0 : 1);
                }
                // om aktivitet stationen inte är laddad med hamster så är hamster 3 null och vi gör därför ingen jämföring ovan och returnerar direkt 0 för bur
                else if (hamster2 != null)
                {
                    return(0);
                }
                else
                {
                    return(1);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// The run.
        /// </summary>
        protected override void Run()
        {
            Animal barsik   = new Cat();
            Animal sharik   = new Dog();
            Animal farshmak = new Monkey();
            Animal xom940K  = new Hamster();

            DoSomeAction(barsik);
            DoSomeAction(sharik);
            DoSomeAction(farshmak);
            DoSomeAction(xom940K);
        }
Exemplo n.º 16
0
        protected override void Seed(PetShop.Models.ApplicationDbContext ctx)
        {
            Hamster hamster1 = new Hamster
            {
                Id      = 1,
                HasCage = true,
                Breed   = new Breed
                {
                    Name  = "Rasa 1",
                    Size  = "Medium",
                    Color = "Red",
                    Image = File.ReadAllBytes("C: \\Users\\adria\\Desktop\\Facultate\\Anul 3\\Semestrul 1\\DAW\\PetShop\\PetShop\\Images\\1.jpg")
                },
                Food = new List <Food>
                {
                    new Food
                    {
                        ProductName = "ProHamster",
                        Diet        = false
                    }
                },

                Toys = new List <Toy> {
                    new Toy
                    {
                        ProductName = "Wheel"
                    }
                },

                Image = File.ReadAllBytes("C: \\Users\\adria\\Desktop\\Facultate\\Anul 3\\Semestrul 1\\DAW\\PetShop\\PetShop\\Images\\1.jpg")
            };

            ctx.Hamsters.Add(hamster1);



            ctx.Locations.Add(new Location
            {
                Id           = 1,
                LocationType = "Classic",
                Address      = new Address
                {
                    Id         = 1,
                    City       = "Bucharest",
                    Street     = "Ciobanasului",
                    Number     = 65,
                    PostalCode = 610192
                }
            });

            ctx.SaveChanges();
            base.Seed(ctx);
        }
Exemplo n.º 17
0
    void OnGUI()
    {
        GUI.depth = 1;
        GUI.skin.label.alignment = TextAnchor.MiddleCenter;
        GUI.skin.label.fontSize  = 48;
        GUI.skin.button.fontSize = 36;

        drawBar(0, battery.GetAmountFilled() / battery.GetCapacity());
        GUI.Label(new Rect(Screen.width / 15, 0, Screen.width * 13 / 15, Screen.height / 10),
                  string.Format("{0}/{1}", (int)battery.GetAmountFilled(), battery.GetCapacity()));

        float rateY = Screen.height * 3 / 20;

        drawBar(rateY, battery.GetAverageRate() / 5);
        GUI.Label(new Rect(Screen.width / 15, rateY, Screen.width * 13 / 15, Screen.height / 10),
                  string.Format("{0:F3}", battery.GetAverageRate()));

        float hamWidth  = Screen.width / Mathf.Max(10, caught.Count);
        float hamHeight = hamWidth * hamsterTex.height / hamsterTex.width;
        float top       = Screen.height * 3 / 10f;

        for (int i = 0; i < caught.Count; i++)
        {
            GUI.DrawTexture(new Rect(i * hamWidth, top, hamWidth, hamHeight), hamsterTex);
        }

        if (!touchEnabled)
        {
            return;
        }

        if (GUI.Button(new Rect(0, Screen.height * 15 / 16f, Screen.width / 2, Screen.height / 16f), "Playpen"))
        {
            caught.Clear();
            level   = 0;
            battery = new Battery(100);
            if (runner != null)
            {
                runner.Remove();
                runner = null;
            }
        }

        if (GUI.Button(new Rect(Screen.width / 2, Screen.height * 15 / 16f, Screen.width / 2, Screen.height / 16f), "Shop"))
        {
            gameObject.AddComponent <Shop>().Init(this);
        }
    }
Exemplo n.º 18
0
    public void BeginRun()
    {
        currentHamsters = new List <Hamster>();
        chosenHamsters  = hamsters; //todo loadouts
        int i = 0;

        foreach (HamsterData hamsterData in chosenHamsters)
        {
            hamsterData.status = HamsterStatus.Adult;
            Hamster hamObj = Instantiate(hamsterPrefab, null, false).GetComponent <Hamster>();
            hamObj.Initialize(hamsterData);
            currentHamsters.Add(hamObj);
            RunManager.Instance.HamsterLocations[i].Hamster = hamObj;
            i++;
        }
    }
Exemplo n.º 19
0
        public async Task <HamsterResponse> SaveAsync(Hamster hamster)
        {
            try
            {
                await _hamsterRepository.AddAsync(hamster);

                await _unitOfWork.CompleteAsync();

                return(new HamsterResponse(hamster));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new HamsterResponse($"An error occurred when saving the hamster: {ex.Message}"));
            }
        }
Exemplo n.º 20
0
        public ActionResult Delete(int id)
        {
            Hamster hamster = db.Hamsters.Find(id);

            if (hamster != null)
            {
                for (int i = 0; i < hamster.Toys.Count(); i++)
                {
                    Toy toy = db.Toys.Find(hamster.Toys[i].Id);
                    db.Toys.Remove(toy);
                }
                db.Hamsters.Remove(hamster);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(HttpNotFound("Couldn't find the hamster with id " + id.ToString()));
        }
        public void CheckHamsterOnCageArea()
        {
            if (Tick.simulatorDate.Hour != 17)
            {
                var activityLogs = activityLogService
                                   .GetById(a => a.ActivityId == (int)ActivityType.Cage)
                                   .Where(e => e.EndTime == null).OrderBy(s => s.StartTime).ToList();

                int capacity = areaService.GetById(a => a.AreaTypeId == (int)AreaType.Exercise).Capacity;

                for (int i = 0; i < capacity; i++)
                {
                    Hamster hamster = hamsterService.GetById(activityLogs[i].HamsterId);
                    MoveHamster(hamster, activityLogs[i], ActivityType.Exercise, AreaType.Exercise);
                }
            }
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            var cat1 = new Cat()
            {
                Name = "Tomas"
            };


            cat1.Breath();

            var cat2 = new Cat()
            {
                Name = "Viorel"
            };

            var cat3 = new Cat()
            {
                Name = "Garfield"
            };

            var dog1 = new Dog()
            {
                Name = "Totto"
            };

            var hamster = new Hamster()
            {
                Name = "Hamsty"
            };

            var animalList = new List <AnimalBase>();

            animalList.Add(cat1);
            animalList.Add(cat2);
            animalList.Add(cat3);
            animalList.Add(dog1);
            animalList.Add(hamster);


            foreach (var animal in animalList)
            {
                animal.Breath();
                animal.Bites();
            }
        }
Exemplo n.º 23
0
        private static int TimeWaitingForExercise(Hamster hamster, DateTime dateTime) // Method for calculate how long Hamsters have been waiting for exercise.
        {
            var logList     = hamster.Logs.Where(l => l.Activity == Activity.Exercise && l.TimeStamp.Day == dateTime.Day).ToList().OrderBy(l => l.TimeStamp);
            var checkInTime = new TimeSpan(7, 0, 0);

            if (logList.Any())
            {
                var timeWaited       = logList.First().TimeStamp.TimeOfDay - checkInTime;
                var totalTimeWaiting = timeWaited.TotalMinutes;
                return((int)totalTimeWaiting);
            }
            else
            {
                var timeStillWaiting      = dateTime.TimeOfDay - checkInTime;
                var totalTimeStillWaiting = timeStillWaiting.TotalMinutes;
                return((int)totalTimeStillWaiting);
            }
        }
Exemplo n.º 24
0
 void JjinbbangActivity()
 {
     // 스페이스바 상호작용
     if (Input.GetKeyDown(KeyCode.Space))
     {
         if (_ActObject == null)
         {
             Debug.Log("_ActObject null");
             return;
         }
         else if (_ActObject.tag == "Hamster")
         {
             _hamster = _ActObject.GetComponent <Hamster>();
             _hamster.BeFriend();
             _hamster = null;
         }
     }
 }
Exemplo n.º 25
0
        public static string TimeBeforeActivity(Hamster hamster, int day, Activity activity)
        {
            var dbContext     = new DaycareContext();
            var timeBefore    = new TimeSpan();
            var exerciseQuery = hamster.Logs.Where(l => l.Activity == activity && l.Date.Day == day).ToList().OrderBy(l => l.Date);

            if (exerciseQuery.Count() == 0)
            {
                var checkInTime = new TimeSpan(7, 0, 0);
                timeBefore = Simulator.Date.TimeOfDay - checkInTime;
            }
            else if (exerciseQuery.Count() > 0)
            {
                var checkInTime = new TimeSpan(7, 0, 0);
                timeBefore = exerciseQuery.First().Date.TimeOfDay - checkInTime;
            }
            return($"{timeBefore.TotalMinutes} min wait");
        }
        public int GetAreaId(Hamster hamster, AreaType areaType)
        {
            var areas = areaService.GetByAreaType((int)areaType);

            foreach (var area in areas)
            {
                var logs = area.ActivityLogs.Where(a => a.EndTime == null).ToList();
                if (logs.Count == 0)
                {
                    return(area.Id);
                }
                if (logs.Count < area.Capacity &&
                    hamsterService.GetById(logs.Last().HamsterId).Gender == hamster.Gender)
                {
                    return(area.Id);
                }
            }
            return(0);
        }
Exemplo n.º 27
0
 public ActionResult Details(int?id)
 {
     if (id.HasValue)
     {
         Hamster     hamster = db.Hamsters.Find(id);
         List <Food> food    = db.Food.ToList();
         ViewBag.Hamsters = new List <Hamster>()
         {
             hamster
         };
         ViewBag.Food = food;
         if (hamster != null)
         {
             return(View(hamster));
         }
         return(HttpNotFound("Couldn't find the hamster with id " + id.ToString() + "!"));
     }
     return(HttpNotFound("Missing hamster id parameter!"));
 }
        public void CheckHamsterOnSpaArea()
        {
            if (Tick.simulatorDate.Hour != 17)
            {
                var activityLogs = activityLogService
                                   .GetById(a => a.ActivityId == (int)ActivityType.Spa)
                                   .Where(e => e.EndTime == null);

                foreach (var activityLog in activityLogs)
                {
                    var startTime = activityLog.StartTime;
                    if ((Tick.simulatorDate.TimeOfDay - startTime.Value.TimeOfDay).TotalMinutes > 10)
                    {
                        Hamster hamster = hamsterService.GetById(activityLog.HamsterId);
                        MoveHamster(hamster, activityLog, ActivityType.Cage, AreaType.Cage);
                    }
                }
            }
        }
Exemplo n.º 29
0
    private IEnumerator BreedRoutine(Hamster h1, Hamster h2)
    {
        float startScore = GameManager.instance.CurrentScore;

        while (GameManager.instance.CurrentScore < startScore + ScoreToBreed)
        {
            if (!h1 || !h2 || h1 != _hamster1Location.Hamster ||
                h2 != _hamster2Location.Hamster)
            {
                yield break;
            }

            //TODO: Tick timer

            yield return(null);
        }

        Conceive();
    }
Exemplo n.º 30
0
    public void Breed(Hamster hamster, Hamster hamster1)
    {
        HamsterData child = hamster.Breed(hamster1);

        chosenHamsters.Add(child);
        Debug.Log("Child bred. Status is:  " + child.status);
        Hamster childObj = Instantiate(hamsterPrefab, null, false).GetComponent <Hamster>();

        childObj.Initialize(child);
        currentHamsters.Add(childObj);
        foreach (HamsterLocation location in RunManager.Instance.BabyLocations)
        {
            if (location.Hamster == null)
            {
                location.Hamster = childObj;
                break;
            }
        }
        //todo make these permanent/between runs
    }
Exemplo n.º 31
0
        public void PrintInfo_Should_Return_Correct_Value()
        {
            // Arrange
            var hamster = new Hamster("name", AnimalGenderType.male, 1);

            var sb = new StringBuilder();

            sb.AppendLine($"Pet Type: hamster");
            sb.AppendLine($"Name: name");
            sb.AppendLine($"Id: {hamster.Id}");
            sb.AppendLine($"Gender: male");
            sb.AppendLine("No services performed yet");
            string expected = sb.ToString();

            // Act
            string actual = hamster.PrintInfo();

            // Assert
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 32
0
    public virtual void OnEndDrag(PointerEventData eventData)
    {
        if (!Hamster || Hamster.HamsterData.status != HamsterStatus.Adult)
        {
            return;
        }

        Vector2         dropPos = Camera.main.ScreenToWorldPoint(eventData.position);
        HamsterLocation next    = GetClostestHamsterLocation(dropPos);

        if (next != null)
        {
            next.Hamster = Hamster;
            Hamster      = null;
        }
        else
        {
            Hamster = Hamster;
        }
    }