Loading...
PlamenNeykov avatar PlamenNeykov 3 Точки

Въпрос за задача "Autumn Cocktails"

Здравейте,С нулевите тестове всичко е наред, но с три от останалите не е така и не разбирам защо. Моля за съдействие, къде може да е проблема?

ЗАДАЧАТА

Summer is over, autumn has come. For this purpose, we have prepared several cocktails that we think you will like.

First, you will receive a sequence of integers, representing the number of ingredients in a single bucket. After that, you will be given another sequence of integers - the freshness level of the ingredients.

Your task is to mix them so you can produce the cocktails, listed in the table below with the exact freshness level.

Cocktail

Freshness Level needed

Pear Sour

150

The Harvest

250

Apple Hinny

300

High Fashion

400

To mix a cocktail, you have to take the first bucket of ingredients and the last freshness level value. The total freshness level is calculated by their multiplication. If the product of this operation equals one of the levels described in the table, you make the cocktail and remove both buckets with ingredients and freshness value. Otherwise, you should remove the freshness level, increase the ingredient value by 5, then remove it from the first position and add it at the end. In case you have an ingredient with a value of 0 you have to remove it and continue mixing the cocktails.
You need to stop making cocktails when you run out of buckets with ingredients or freshness level values.

Your task is considered done if you make at least four cocktails - one of each type.

Input

  • The first line of input will represent the values of buckets with ingredients - integers, separated by a single space.
  • On the second line, you will be given the freshness values - integers again, separated by a single space.

Output

  • On the first line of output - print whether you've succeeded in preparing the cocktails
  • "It's party time! The cocktails are ready!".
  • "What a pity! You didn't manage to prepare all cocktails.".
  • On the next output line - print the sum of the ingredients only if they are left any
    • "Ingredients left: {sum of the left ingredients}".
  • On the last few lines, you have to print the cocktails you have made at least once, ordered alphabetically in the format:

" # {cocktail name} --> {amount}".

Constraints

  • All of the ingredients' values and freshness level values will be integers in the range [0, 100].
  • We can have more than one mixed cocktail of the types specified in the table above.

Examples

Input

Output

Comment

10 10 12 8 10 12

25 15 50 25 25 15

It's party time! The cocktails are ready!

 # Apple Hinny --> 2

 # High Fashion --> 1

 # Pear Sour --> 2

 # The Harvest --> 1

First, you take the first ingredient and the last freshness level value and multiply them - the result is 150 so we make a Pear Sour cocktail. Next, we have a product of 250 and The Harvest cocktail is ready. Then we mix the Apple Hinny cocktail by multiplying 12 and 25. The product of next ingredient value and freshness level value is 400 and we make High Fashion cocktail. The next pair is 10 and 15, we multiply them and mix one more Pear Sour. The last multiplication of 12 and 25 equals 300 and we make one more Apple Hinny. There are no more ingredients and freshness values so we stop mixing cocktails, but we have one of each cocktail types and print the proper message.

12 20 0 6 19

12 12 25

What a pity! You didn't manage to prepare all cocktails.

Ingredients left: 55

 # Apple Hinny --> 1

The first pair is 12 and 25, we mix the Apple Hinny cocktail and remove both of them.
Next, we take 20 and 12 - the product is 240 - we can't mix a cocktail, so we remove the freshness level value, increase the ingredient value with 5, remove it from the beginning of the buckets sequence and add it at the end.
The next ingredient has a value of 0 - we remove it and continue.
The next pair is 6 and 12 - again we can't make a cocktail. After that we don't have more freshness level values, so we stop mixing drinks.
The rest of the ingredients are 19, 25, 11 with the sum of 55.

 

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

package ExamPrep23October2021;

import java.util.*;
import java.util.stream.Collectors;

public class P1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // ingredients - integers Queue
        // freshness values - integers Stack


        String[] ingredientsInput = scanner.nextLine().split("\\s+");
        ArrayDeque<Integer> ingredients = new ArrayDeque<>();
        for (String e : ingredientsInput) {
            int value = Integer.parseInt(e);
            ingredients.offer(value);
        }

        String[] freshnessInput = scanner.nextLine().split("\\s+");
        ArrayDeque<Integer> freshness = new ArrayDeque<>();
        for (String e : freshnessInput) {
            int value = Integer.parseInt(e);
            freshness.push(value);
        }

        Map<String, Integer> coctailsLevels = new LinkedHashMap<>();

        coctailsLevels.put("Pear Sour", 150);
        coctailsLevels.put("The Harvest", 250);
        coctailsLevels.put("Apple Hinny", 300);
        coctailsLevels.put("High Fashion", 400);

        Map<String, Integer> coctailsquantity = new TreeMap<>();

        while (!ingredients.isEmpty()&&!freshness.isEmpty()) {
            int a = ingredients.poll();
            int b = freshness.pop();
            int mix = a*b;
            String name = "";
            for (Map.Entry<String, Integer> entry : coctailsLevels.entrySet()) {
                if (entry.getValue()==mix) {
                    name = entry.getKey();
                }
            }
            if (coctailsLevels.containsValue(mix)) {

                if (coctailsquantity.containsKey(name)) {
                    int newQuantity = coctailsquantity.get(name) + 1;
                    coctailsquantity.replace(name,newQuantity);
                } else {
                    coctailsquantity.put(name,1);
                }
            } else {
                a = a+5;
                ingredients.offer(a);
            }
        }

      //  System.out.println("A");

       if (coctailsquantity.size()==4) {
           System.out.printf("It's party time! The cocktails are ready!%n");
           for (Map.Entry<String, Integer> entry : coctailsquantity.entrySet()) {
               System.out.printf("# %s --> %d%n",entry.getKey(),entry.getValue());
           }
       } else {
           System.out.printf("What a pity! You didn't manage to prepare all cocktails.%n");

           int sum = 0;
           for (Integer element : ingredients) {
               sum = sum+element;
           }
           System.out.printf("Ingredients left: %d%n",sum);

           for (Map.Entry<String, Integer> entry : coctailsquantity.entrySet()) {
               System.out.printf("# %s --> %d%n",entry.getKey(),entry.getValue());
           }
       }
    }
}

Благодаря предварително.

Тагове:
0
Java Advanced
MartinBG avatar MartinBG 4803 Точки

Има 4 проблема в решението:

1. Не е изпълнено това условие: "In case you have an ingredient with a value of 0 you have to remove it and continue mixing the cocktails". 

Примерен фикс:

int a = ingredients.poll();
if (a == 0) {
  continie;
}

2. "Ingredients left: ..." трябва да се отпечатва само ако има такива (т.е. сумата трябва да е над 0):

if (sum > 0) {
  System.out.printf("Ingredients left: %d%n",sum);
}

3. Не е спазен формата при отпечатването на коктейлите - трябва да има един space в началото: " # %s --> %d%n"

4. При "coctailsquantity.size()==4" няма да се отпечата "Ingredients left: ..."

Примерен фикс:

if (coctailsquantity.size()==4) {
   System.out.printf("It's party time! The cocktails are ready!%n");
} else {
    System.out.printf("What a pity! You didn't manage to prepare all cocktails.%n");
}

int sum = 0;
for (Integer element : ingredients) {
   sum = sum+element;
}

if (sum > 0) {
  System.out.printf("Ingredients left: %d%n",sum);
}

for (Map.Entry<String, Integer> entry : coctailsquantity.entrySet()) {
   System.out.printf(" # %s --> %d%n",entry.getKey(),entry.getValue());
}

 

 

Опростено алтернативно решение.

1
IrennaStoyneva avatar IrennaStoyneva 3 Точки

Здравейте, колеги! И аз се нуждая от малко помощ относно тази задача. Два от тестовете не ми минават..

https://pastebin.com/Xu54RNxV -> Това е решението ми, какво ли не правих и пак не успявам.

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