Loading...
razihanna avatar razihanna 7 Точки

Treasure Hunt Mid Exam C# Fundamentals

Hello,

I got 70/100 , I can't find why, please advsie

Thank you in advance

using System;using System.Collections.Generic;using System.Linq;namespac - Pastebin.com

 

Programming Fundamentals Mid Exam Retake - 6 August 2019 - SoftUni Judge

The pirates need to carry a treasure chest safely back to the ship. Looting along the way.

Create a program that manages the state of the treasure chest along the way. On the first line you will receive the initial loot of the treasure chest, which is a string of items separated by a '|'.

"{loot1}|{loot2}|{loot3}… {lootn}"

The following lines represent commands until "Yohoho!" which ends the treasure hunt:

  • Loot {item1} {item2}…{itemn} – pick up treasure loot along the way. Insert the items at the beginning of the chest. If an item is already contained don't insert it.
  • Drop {index} – remove the loot at the given position and add it at the end of the treasure chest. If the index is invalid skip the command.
  • Steal {count} – someone steals the last count loot items. If there are less items than the given count remove as much as there are. Print the stolen items separated by ', ':
  •  

In the end output the average treasure gain which is the sum of all treasure items length divided by the count of all items inside the chest formatted to the second decimal point:

"Average treasure gain: {averageGain} pirate credits."

If the chest is empty print the following message:

"Failed treasure hunt."

Input

  • On the 1st line you are going to receive the initial treasure chest (loot separated by '|')
  • On the next lines, until "Yohoho!", you will be receiving commands.

Output

  • Print the output in the format described above.

Constraints

  • The loot items will be strings containing any ASCII code.
  • The indexes will be integers in the range [-200200]
  • The count will be an integer in the range [1….100]

Examples

Input

Output

Gold|Silver|Bronze|Medallion|Cup

Loot Wood Gold Coins

Loot Silver Pistol

Drop 3

Steal 3

Yohoho!

Medallion, Cup, Gold

Average treasure gain: 5.40 pirate credits.

Comments

The first command "Loot Wood Gold Coins" adds Wood and Coins to the chest but omits Gold since it is already contained. The chest now has the following items:

Coins Wood Gold Silver Bronze Medallion Cup

The second command adds only Pistol to the chest

The third command "Drop 3" removes the Gold from the chest, but immediately adds it at the end:

Pistol Coins Wood Silver Bronze Medallion Cup Gold

The fourth command "Steal 3" removes the last 3 items Medallion, Cup, Gold from the chest and prints them.

In the end calculate the average treasure gain which is the sum of all items length Pistol(6) + Coins(5) + Wood(4)  + Silver(6) + Bronze(6) = 27 and divide it by the count 27 / 5 = 5.4 and format it to the second decimal point.

 

Input                                                                                            Output

Diamonds|Silver|Shotgun|Gold

Loot Silver Medals Coal

Drop -1

Drop 1

Steal 6

Yohoho!

Coal, Diamonds, Silver, Shotgun, Gold, Medals

Failed treasure hunt.

 

 

0
Fundamentals Module 28/02/2021 08:23:09
Axiomatik avatar Axiomatik 2422 Точки

The main-problem was that basically your code is correct, but you forgot in clearing out your steal collection during the Steal command. When you use the Steal command for a second time in your input, the console output will also contain the stolen items from the last command.

Best,

using System;
using System.Linq;
using System.Collections.Generic;

namespace Treasure_Hunt
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> treasure = Console.ReadLine()
                .Split("|", StringSplitOptions.RemoveEmptyEntries)
                .ToList();

            List<string> steal = new List<string>();

            while (true)
            {
                string command = Console.ReadLine();

                if (command == "Yohoho!")
                {
                    break;
                }

                string[] token = command.Split();
                string word = token[0];

                if (word == "Loot")
                {
                    for (int i = 1; i < token.Length; i++)
                    {
                        if (!treasure.Contains(token[i]))
                        {
                            treasure.Insert(0, token[i]);
                        }
                    }
                }

                else if (word == "Drop")
                {
                    int index = int.Parse(token[1]);
                    if (index >= 0 && index < treasure.Count)
                    {
                        string removedItem = treasure[index];
                        treasure.RemoveAt(index);
                        treasure.Add(removedItem);
                    }

                }

                else if (word == "Steal")
                {
                    int count = int.Parse(token[1]);

                    //if (count <= treasure.Count) // Check to see if gives Error in judge !!!
                    if (count < treasure.Count)
                    {
                        for (int i = treasure.Count - count; i < treasure.Count; i++)
                        {
                            steal.Add(treasure[i]);
                        }

                        Console.WriteLine(string.Join(", ", steal));

                        steal.Clear(); // !!! Clear the list

                        treasure.RemoveRange(treasure.Count - count, count);
                    }

                    else
                    {
                        for (int i = 0; i < treasure.Count; i++)
                        {
                            steal.Add(treasure[i]);
                        }
                        Console.WriteLine(string.Join(", ", steal));

                        steal.Clear(); // !!! Clear the list

                        treasure.RemoveRange(0, treasure.Count);
                    }

                }

            }

            double sum = 0;
            double avg = 0;

            foreach (var item in treasure)
            {
                sum = sum + item.Length;
            }


            if (treasure.Count != 0)
            {
                avg = sum / treasure.Count;

                Console.WriteLine($"Average treasure gain: {avg:f2} pirate credits.");
            }

            else
            {
                Console.WriteLine("Failed treasure hunt.");
            }

        }
    }
}

 

1
Elena123456 avatar Elena123456 235 Точки

@ Axiomatik ,

sorry, I have missed your solution, because I spend 30 minutes to found the mistake. I was rushing and I forgot to write how I added a new List initialisation after every Steal command.

Have a nice evening! smiley

0
28/02/2021 20:55:09
Axiomatik avatar Axiomatik 2422 Точки

Thanks.

All the best,

1
razihanna avatar razihanna 7 Точки

Thank you very much , I did not know about "clear" . Now I've learned something new

Thank for all of the answers!

Best regards

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