Loading...
MartinPL avatar MartinPL 0 Точки

Feed The Animals - Demo programming Fundamentals finalExam JAVA

Здравейте, колеги. Може ли някой да ми напише с няколко реда как да оправя сортирането, като аз съм стигнал до някъде, но се иска ако някои от стойностите са равни по 'value' да ги сравним по 'key'.  Благодаря предаврително и съжалявам, че поста е толкова дълъг. 

Това ми е кодът :

https://pastebin.com/wSA94Ccy

Ето условието :

Feed the Animals

The sanctuary needs to provide food for the animals and feed them, so your task is to help with the process

Create a program that organizes the daily feeding of animals. You need to keep information about animals, their daily food limit and the areas of the Wildlife Refuge they live in. You will be receiving lines with commands until you receive the "Last Info" message.  There are two possible commands:

  • "Add:{animalName}:{dailyFoodLimit}:{area}":
    • Add the animal and its daily food limit to your records. It is guaranteed that the names of the animals are unique and there will never be animals with the same name. If it already exists, just increase the value of the daily food limit with the current one that is given.
  • "Feed:{animalName}:{food}:{area}":
    • Check if the animal exists and if it does, reduce its daily food limit with the given food for feeding. If its limit reaches 0 or less, the animal is considered successfully fed and you need to remove it from your records and print the following message:
      • "{animalName} was successfully fed"

You need to know the count of hungry animals there are left in each area in the end. If an animal has daily food limit above 0, it is considered hungry.

In the end, you have to print each animal with its daily food limit sorted in descending order by the daily food limit and then by its name in ascending order in the following format:

Animals:

{animalName} -> {dailyFoodLimit}g

{animalName} -> {dailyFoodLimit}g

Afterwards, print the areas with the count of animals, which are not fed in descending order by the count of animals. If an area has 0 hungry animals in it, don't print it. The output must be in the following format:

Areas with hungry animals:

{areaName} : {countOfUnfedAnimals}

{areaName} : {countOfUnfedAnimals}

Input / Constraints

  • You will be receiving lines until you receive the "Last Info" command.
  • The food comes in grams and is an integer number in the range [1...100000].
  • The input will always be valid.
  • There will never be a case, in which an animal is in two or more areas at the same time.

Output

  • Print the appropriate message after the "Feed" command, if an animal is fed.
  • Print the animals with their daily food limit in the format described above.
  • Print the areas with the count of unfed animals in them in the format described above.

Examples

Input

Output

Add:Maya:7600:WaterfallArea

Add:Bobbie:6570:DeepWoodsArea

Add:Adam:4500:ByTheCreek

Add:Jamie:1290:RiverArea

Add:Gem:8730:WaterfallArea

Add:Maya:1230:WaterfallArea

Add:Jamie:560:RiverArea

Feed:Bobbie:6300:DeepWoodsArea

Feed:Adam:4650:ByTheCreek

Feed:Jamie:2000:RiverArea

Last Info

Adam was successfully fed

Jamie was successfully fed

Animals:

Maya -> 8830g

Gem -> 8730g

Bobbie -> 270g

Areas with hungry animals:

WaterfallArea : 2

DeepWoodsArea : 1

Comments

First, we receive the "Add" command, so we add "Maya" to our records and we keep her daily food limit - 7600. We know that she is in WaterfallArea. We keep adding the new animals until we receive "Maya" again and we have to increase her food limit with 1230, so it becomes 8830. After that we receive "Jamie" and we need to increase his daily food limit with 560, after which it becomes 1850. Then we start receiving "Feed" commands. First, we must decrease Bobbie's food limit with 6300, so it becomes 270. Then, we need to decrease Adam's food limit with 4650. It becomes less than zero and we remove him from the collection – he is considered fed, respectively that is one less hungry animal in the area that he is in – ByTheCreek. Then we "Feed" Jamie with 2000 and his limit becomes less than zero, so we print "Jamie was successfully fed" and we remove him from our records and note that there is one less hungry animal in his area – RiverArea. In the end, we print the animals we still have in our collection, with their daily food limits in descending order by the food limits. Afterwards we print only the areas in which there are remaining hungry animals and their count in descending order.

 

Add:Bonie:3490:RiverArea

Add:Sam:5430:DeepWoodsArea

Add:Bonie:200:RiverArea

Add:Maya:4560:ByTheCreek

Feed:Maya:2390:ByTheCreek

Feed:Bonie:3500:RiverArea

Feed:Johny:3400:WaterFall

Feed:Sam:5500:DeepWoodsArea

Last Info

Sam was succesfully fed

Animals:

Maya -> 2170g

Bonie -> 190g

Areas with hungry animals:

RiverArea : 1

ByTheCreek : 1

Тагове:
0
Fundamentals Module
mark79 avatar mark79 639 Точки

Здравей,

малко промени по кода :

1. При декларирането на речниците

        Map<String, Integer> animalsFoodLimit = new HashMap<>();
        Map<String, Integer> hungryAnimalAreas = new LinkedHashMap<>();

2. При сортировката

        System.out.println("Animals:");
        animalsFoodLimit.entrySet().stream().
                sorted((f, s) -> {
                    if (s.getValue() - f.getValue() == 0) {
                        return f.getKey().compareTo(s.getKey());
                    } else {
                        return s.getValue() - f.getValue();
                    }
                }).
                forEach(entry -> {
                    System.out.printf("%s -> %dg%n", entry.getKey(), entry.getValue());
                });
        
        System.out.println("Areas with hungry animals:");
        hungryAnimalAreas.entrySet().stream().
                sorted((f, s) -> s.getValue() - f.getValue()).
                forEach(entry -> {
                    if (entry.getValue() > 0) {
                        System.out.printf("%s : %d%n", entry.getKey(), entry.getValue());
                    }
                });

Поздрави :)

0
29/07/2019 22:44:25
MartinPL avatar MartinPL 0 Точки

Благодаря!!!

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.