Question

In: Computer Science

I want to understand how this can be solved in c++. Please send a screenshot also...



I want to understand how this can be solved in c++. Please send a screenshot also with your code so I can see how it is supposed to be formatted or indented.

Instructions:

Your program will read in a file of commands. There are three types of commands:

Warrior creates a new warrior with the specified name and strength. Battle causes a battle to occur between two warriors. Status lists all warriors, alive or dead, and their strengths.

A sample input file looks like:

"Warrior Jim 42
Warrior Lancelot 15
Warrior Arthur 15
Warrior Torvalds 20
Warrior Gates 8
Status
Battle Arthur Lancelot
Battle Jim Lancelot
Battle Torvalds Gates
Battle Gates Lancelot
Status"

The name of the input file will be "warriors.txt". Note that the commands do not have to appear in that order. The only requirement is that a Battle command cannot appear until the specified warriors have been seen.

The Status command displays how many warriors there, then displays each one with his strength. The Warrior command does not display anything. The Battle command displays one line to says who is fighting whom and a second line to report the results, as shown below.

The output (which would display on the screen) for this file should look like:

"There are: 5 warriors
Warrior: Jim, strength: 42
Warrior: Lancelot, strength: 15
Warrior: Arthur, strength: 15
Warrior: Torvalds, strength: 20
Warrior: Gates, strength: 8
Arthur battles Lancelot
Mutual Annihilation: Arthur and Lancelot die at each other's hands
Jim battles Lancelot
He's dead, Jim
Torvalds battles Gates
Torvalds defeats Gates
Gates battles Lancelot
Oh, NO! They're both dead! Yuck!
There are: 5 warriors
Warrior: Jim, strength: 42
Warrior: Lancelot, strength: 0
Warrior: Arthur, strength: 0
Warrior: Torvalds, strength: 12
Warrior: Gates, strength: 0"

For the sequence of commands, your output should looke exactly as shown above. Please don't exercise you creativity here. Use a struct. That means we do not want you to define classes or methods, or to use data hiding.

Make good use of functions. In this program, for example, when you determine that you are looking at a Warrior command then you should call a function to handle that command. Similarly with the other commands. Have useful comments explaining what each part of your code does. The code must be well formatted with good indentation. All structs, functions and variables should have good names. Function names should clearly identify what the function does. Follow the convention that structs begin with an uppercase letter, constants are all uppercase and functions and variables begin with a lowercase letter.

Each warrior starts out with a name and a certain amount of strength. Each time he fights, he loses some strength. (He gets to keep his name.) If his opponent is stronger than he is, then he loses all of his strength, in which case he is dead, or at the very least pretty useless as a fighter. Otherwise he loses as much strength as his opponent had. Of course, if he and his opponent had the same strength then they are both losers.

Even losers are allowed to pick a fight. It doesn't require having any strength in order to do battle with someone else. Not that you stand much of a chance of winning anything, but perhaps it's worth getting beaten (again) just to have those 15 seconds of fame.

The output, "He's dead, Jim", is because Jim is battling Lancelot but Lancelot, sadly, has already died. It is not meant as a phrase to be used whenever one of the participants is dead and the other is alive. Sure, in all such cases you would say "He's dead FILL_IN_THE_BLANK", where FILL_IN_THE_BLANK is the name of the person who is not dead.

Solutions

Expert Solution

First, we think about how we want to save the warriors. We start by creating a Warrior struct. This has the name, strength and the constructor for Warrior. Now we would like to have an array for adding all these warriors. We use a vector of Warriors to do this. Now over here I have also used an unordered_map to keep track of the index a warrior is saved in the array. Why? because in the battle commands we are given just the names of the warriors so to find these warriors in our array we would have to search it linearly. This is O(n) search. Using unordered_map we can do it in O(1) although we are using a little bit more space.

Next, we start by reading the file. We read the file line by line and tokenize each line. After tokenizing we check which command was given and the corresponding function is called.

The create_warrior function creates a new warrior, pushes it into our warrior vector and saves in which index the warrior is stored in the unordered_map. Note that we are using pass by reference to pass our vector in so changes made in the function to vector would reflect in our original vector in the main function.

Next, in the start_battle function, we get the indices of the warriors from the unordered_map then get the corresponding strength of these warriors from our array. We then apply the various conditional statements to check who wins and update their strengths accordingly.

Finally, in the get_status function, we simply iterate over our warrior's vector and print out the names and strengths of the warriors.

Source Code and screenshots given below:

Source code:

#include <iostream>
#include <cstring>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

// Struct of warrior
struct Warrior {
   string name;
   int strength;
   // Constructor
   Warrior(string n, int s) {
       name = n;
       strength = s;
   }
};

// Function that tokenizes the given string and returns it as a vector
// Example: line = "Warrior Arthur 15"
// Return vector<string> = {"Warrior", "Arthur", "15"}
vector<string> tokenize_str(string line) {
   vector<string> v;
   string temp = "";
   for (int i = 0; i < line.size(); i++) {
       if (line[i] != ' ') {
           temp += line[i];
       } else {
           v.push_back(temp);
           temp = "";
       }
   }
   v.push_back(temp);
   return v;
}

// Function which creates a new warrior and pushes it into our warrior vector
// It also saves the index of the array in which the warrior has been added in the unordered_map
// This way we don't have to search for warriors during the battle command
void create_warrior(string name, string s, vector<Warrior> &warriors, unordered_map<string, int> &index) {
   // Converts string to int
   int strength = stoi(s);
   Warrior new_warrior = Warrior(name, strength);
   index[name] = warriors.size();
   warriors.push_back(new_warrior);
   return;
}

// Battle function
void start_battle(string name1, string name2, vector<Warrior> &warriors, unordered_map<string, int> &index) {
   // Get index of warriors in the vector using the unordered_map
   int i = index[name1];
   int j = index[name2];
   // Get the strengths of these warriors
   int s1 = warriors[i].strength;
   int s2 = warriors[j].strength;
   cout << name1 << " battles " << name2 << endl;
   if (s1 == 0 && s2 == 0) {
       cout << "Oh, NO! They're both dead! Yuck!" << endl;
   } else if (s2 == 0) {
       cout << "He's dead, " << name1 << endl;
   } else if (s1 == 0) {
       cout << "He's dead, " << name2 << endl;
   } else if (s1 > s2) {
       cout << name1 << " defeats " << name2 << endl;
       warriors[i].strength -= s2;
       warriors[j].strength = 0;
   } else if (s2 > s1) {
       cout << name2 << " defeats " << name1 << endl;
       warriors[j].strength -= s1;
       warriors[i].strength = 0;
   } else {
       cout << "Mutual Annihilation: " << name1 << " and " << name2 << " die at each other's hands" << endl;
       warriors[i].strength = 0;
       warriors[j].strength = 0;
   }
}

// Status function
// Prints the status using the warriors vector
void get_status(vector<Warrior> &warriors) {
   int num_warriors = warriors.size();
   cout << "There are: " << num_warriors << " warriors" << endl;
   for (int i = 0; i < num_warriors; i++) {
       cout << "Warrior: " << warriors[i].name << ", strength: " << warriors[i].strength << endl;
   }
   return;
}

int main() {
   // A vector which stores all our warriors
   vector<Warrior> warriors;

   // an unordered map to store the index in which the warrior is saved in the vector
   // This always us to get the warrior in O(1) time during battle
   // You have the option of not using this but then you would have to search the warrior vector every time
   // in the battle function
   unordered_map<string, int> index;
  
   // Open the warriors file
   ifstream myFile;
   myFile.open("warriors.txt");
  
   // Check if file has been opened properly
   if (!myFile) {
       cerr << "Unable to open file";
       // Exit the program if file did not open successfully
       exit(1);
   }

   // If file opened successfully
  
   // Variable which stores each line in the warriors.txt file
   string line;
   // Read the file till we reach the end
   while(getline(myFile,line)) {
       // Tokenize the line
       vector<string> tokens = tokenize_str(line);
      
       // The first word is the command
       string command = tokens[0];

       // Check what the command is and execute the corresponding function
       if (command == "Warrior") {
           create_warrior(tokens[1], tokens[2], warriors, index);
       } else if (command == "Battle") {
           start_battle(tokens[1], tokens[2], warriors, index);
       } else {
           get_status(warriors);
       }
   }
   return 0;
}


Related Solutions

Please in C++ thank you! Please also include the screenshot of the output. I have included...
Please in C++ thank you! Please also include the screenshot of the output. I have included everything that's needed for this. Pls and thank you! Write a simple class and use it in a vector. Begin by writing a Student class. The public section has the following methods: Student::Student() Constructor. Initializes all data elements: name to empty string(s), numeric variables to 0. bool Student::ReadData(istream& in) Data input. The istream should already be open. Reads the following data, in this order:...
**please put the solution in easy to understand letters because I also want to learn how...
**please put the solution in easy to understand letters because I also want to learn how to solve it, thanks 1) On a particular production line, the likelihood that a light bulb is defective is 10%. Seven light bulbs are randomly selected. What is the probability that at most 4 of the light bulbs will be defective? 2) Patients scheduled to see their primary care physician at a particular hospital wait, on average, an additional seven minutes after their appointment...
please do this in C++! I want to understand it, it must be done before the...
please do this in C++! I want to understand it, it must be done before the evening or nightime. Follow instructions exactly as it says. Please send a screenshot also with your code so I can see how it is supposed to be formatted. Since typing it a chegg answer, makes it look a bit messy. Your program will read in a file of commands. There are three types of commands: Warrior creates a new warrior with the specified name...
Please explain your answer thoroughly because I want to understand it well and also please include...
Please explain your answer thoroughly because I want to understand it well and also please include a diagram if possible Two objects which have mass: m1 = 10kg and m2 = 20kg. Both of them are moving at the velocity of: v1 = 20^i ms and v2 = 10^j ms and then the two objects collide completely inelastically. In what direction do the two objects go after the collision? After the collision, how much kinetic energy was lost?
Please use c++ and follow the instruction, I really want to fully understand this question and...
Please use c++ and follow the instruction, I really want to fully understand this question and I will use your code to check where I made mistake (Do not skip steps). I have written my own code which has tons of errors, and I am so confused about this lab. I need help. Lab 6.4 – C++ and Functions – Math Test Critical Review A value-returning function is a function that returns a value back to the part of the...
I want this to be solved using R studio or R software, please. Here is the...
I want this to be solved using R studio or R software, please. Here is the example: The data in stat4_prob5 present the performance of a chemical process as a function of sever controllable process variables. (a) Fit a multiple regression modelrelating CO2product (y) to total solvent (x1) and hydrogen consumption (x2) and report the fitted regression line. (b) Find a point estimatefor the variance term σ2. (c) Construct the ANOVA tableand test for the significance of the regression using...
please I don't understand this code. Can you put comments to explain the statements. Also, if...
please I don't understand this code. Can you put comments to explain the statements. Also, if there any way to rewrite this code to make it easier, that gonna help me a lot. import java.io.*; import java.util.*; public class State {    private int citi1x,citi1y; private int pop1; private int citi2x,citi2y; private int pop2; private int citi3x,citi3y; private int pop3; private int citi4x,citi4y; private int pop4; private int plantx,planty; public int getCity1X(){ return citi1x; } public int getCity1Y(){ return citi1y;...
Please show work so I can learn how the problem was solved Cost of Production Report...
Please show work so I can learn how the problem was solved Cost of Production Report The debits to Work in Process—Roasting Department for Morning Brew Coffee Company for August, together with information concerning production, are as follows: Work in process, August 1, 500 pounds, 60% completed $2,300* *Direct materials (500 X $3.7) $1,850 Conversion (500 X 60% X $1.5) 450 $2,300 Coffee beans added during August, 16,000 pounds 58,400 Conversion costs during August 25,280 Work in process, August 31,...
Can someone please explain how to calculate this? I truely do not understand how to do...
Can someone please explain how to calculate this? I truely do not understand how to do theoretical yield... calculate theoretical yield and percent yield for anthracene-9-methylmalemide and N-methylmalemide in water amounts used were 0.070 g of anthracene-9-methanol and 50 mL of water and 0.103 g of N-methylmaleimide. the weight of the product was 0.043 g
No sloppy writing, please! I want to be able to see and understand each step :)...
No sloppy writing, please! I want to be able to see and understand each step :) The three polarizing filters are bundled so that the polarizing axes of the second and third filters are 33 ° and 71 °, respectively, relative to the polarizing axis of the first filter. Intensity of unpolarized light hitting the bundle after passing through the bundle is 53 W / cm^2. If the intensity of the incoming light is kept constant, what is the intensity...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT