Question

-Data Structure in C++ (Review for C++) -using vector and class In this assignment you’re going...

-Data Structure in C++ (Review for C++)

-using vector and class

In this assignment you’re going to build a simple “register machine”, a kind of minimal computer that only supports storing a fixed number of values (i.e., no randomly-accessible “main memory”).

Your machine will consist of an input loop that reads lines of input from the user and then executes them, stopping when the user quits (by executing the stop command). Each line of input consists of a command followed by 1 to 3 arguments. Arguments can be either:

Immediate integer values (positive or negative)

Register names a through d (I.e., this machine only supports four registers)

For some commands, a register name may be required in certain argument positions. Here’s a sample transcript from the official solution implementation (lines starting with > are user input; everything else is output printed by the program):

> store 1 a
> store 2 b
> print a
1
> print b
2
> add a b c
> print c
3
> comp a b d
No command with that name exists
> cmp a b d
> print d
-1
> stop
Command Description
store x r Store x into register r (a, b, c, or d)
print r Print the value in register r
add x y d Add x and y and store the result in d (x and y may be either, but d must be a register)
sub x y d Subtract y from x and store the result in d
mul x y d Multiply x and y and store the result in d
cmp x y d Compare x and y and store into d
0 if they are equal, -1 if a < b, or 1 if a > b

Note that the arithmetic (add, sub, mul) and comparison (cmp) commands can take either immediates or register names as their first two parameters. E.g., the following are all valid commands:

add 1 2 a
add a 2 b
add 1 b c
add b c d

Similarly, store’s first argument can be either an immediate or a register:

store a b
store 1 c

You may assume that command names and arguments are always separated by at least one space character.

You should bear in mind that we might want to add new commands later on, so think about how to make your program easily extensible in that way (e.g., a huge if-else chain is not very extensible).

Homework Answers

Answer #1

//registerMachine.cpp

#include<iostream>
#include<string>
#include<vector>
//presenly we have found commands, declare MAX as 6
#define MAX 6
using namespace std;

class register_machine
{
   //declare registers
   int a, b, c, d;
   vector<string> commands;
public:
   //initialize commands to impement while creating object
   register_machine(string command[],int );
   int getCommandIndex(string str);
   int getRegister(char a);
   void aasign_register(char c, int value);
   int get_value(char a);
   void set_value(char ch,int value);

};

register_machine::register_machine(string command[],int size)
{
   a = 0, b = 0, c = 0, d = 0;
   for (int i = 0; i < size; i++)
   {
       commands.push_back(command[i]);
   }
  
}

int register_machine::getCommandIndex(string str)
{
   //get index of the command in commands array of string
   for (int i = 0; i < MAX; i++)
   {
       if (str.compare(commands[i]) == 0)
       {
           return i;
       }
   }

   return -1;
}

int register_machine::getRegister(char ch)
{
   switch (ch)
   {
   case 'a':
       return 97;
       break;
   case 'b':
       return 98;

   case 'c':
       return 99;
       break;
   case 'd':
       return 100;
   default:
       return -1;
   }
}

void register_machine::aasign_register(char ch, int value)
{

   if (ch == 'a')
       a = value;
   if (ch == 'b')
       b = value;
   if (ch == 'c')
       c = value;
   if (ch == 'd')
       d = value;
}

int register_machine::get_value(char ch)
{
   if (ch == 'a')
       return a;
   if (ch == 'b')
       return b;
   if (ch == 'c')
       return c;
   if (ch == 'd')
       return d;
}
void register_machine::set_value(char ch,int value)
{
   if (ch == 'a')
       a = value;
   if (ch == 'b')
       b = value;
   if (ch == 'c')
       c = value;
   if (ch == 'd')
       d = value;

}

int main()
{
   //declare command set, u can add other commands when you are extending the command set here
   string commands[MAX] = { "store", "print", "cmp", "add", "mul", "store" };

   //initialize the object
   register_machine machine(commands,MAX);
  
   int choice,ret;
   string input;

   //loop for user inpute and exit when user press 0
   do
   {
       cout << "Enter command to process commands 2. stop to exit" << endl;
       string command[5];
       getline(cin ,input);
       //process command entered by user
       int j = 0, k = 0, entered_loop;
       if (input.compare("stop") == 0)
       {
           cout << "Exiting the application..." << endl;
           break;
       }
      
       while( j < input.length())
       {
           entered_loop = 0;
           while (!isspace(input[j]) && input[j] != '\n' && j < input.length())
           {
                   //command[i][j++]= input[i];
                   //cout << input[j] << endl;
               command[k]+=input[j++];
               entered_loop = 1;
           }
           if (entered_loop)
               k++;
           j++;
       }
       ret = machine.getCommandIndex(command[0]);
       switch (ret)
       {
           case 0:
                   //strore command
               if (command[2][0] == 'a')
                   machine.set_value('a',stoi(command[1]));
               if (command[2][0] == 'b')
                   machine.set_value('b', stoi(command[1]));
               if (command[2][0] == 'c')
                   machine.set_value('c', stoi(command[1]));
               if (command[2][0] == 'd')
                   machine.set_value('d', stoi(command[1]));
                   break;
           case 1:
           //print command
               if (command[1][0] == 'a')
                   printf("%d\n", machine.get_value('a'));
               if (command[1][0] == 'b')
                   printf("%d\n", machine.get_value('b'));
               if (command[1][0] == 'c')
                   printf("%d\n", machine.get_value('c'));
               if (command[1][0] == 'd')
                   printf("%d\n", machine.get_value('d'));
                   break;
           case 2:
                   //cmp command
               int r1, r2, r3;
               r1 = machine.getRegister(command[1][0]);
               r2 = machine.getRegister(command[2][0]);
               r3 = machine.getRegister(command[3][0]);
               if (machine.get_value(r1) == machine.get_value(r2))
                   machine.aasign_register(r3, 0);
               if (machine.get_value(r1) < machine.get_value(r2))
                   machine.aasign_register(r3, -1);
               else
                   machine.aasign_register(r3, 1);
                  
               break;
           case 3:
                   //add command
               int num1, num2,r;
              
               r1 = machine.getRegister(command[1][0]);
               r2 = machine.getRegister(command[2][0]);
               r3 = machine.getRegister(command[3][0]);
               machine.aasign_register(r3, machine.get_value(r1) + machine.get_value(r2));
              
               break;
           case 4:
                   //multiply
               int n1, n2, reg1;
              
               reg1 = machine.getRegister(command[3][0]);
               r1 = machine.getRegister(command[1][0]);
               r2 = machine.getRegister(command[2][0]);
               r3 = machine.getRegister(command[3][0]);
               machine.aasign_register(r3, machine.get_value(r1) * machine.get_value(r2));
               break;
           default :
               cout << "No command found" << endl;

           }
          
      
   } while (input.compare("stop")!=0);
}

-----------------------------------------------------------------------------------------------------------------------

Enter command to process commands 2. stop to exit
store 2 b
Enter command to process commands 2. stop to exit
print a
1
Enter command to process commands 2. stop to exit
print b
2
Enter command to process commands 2. stop to exit
add a b c
Enter command to process commands 2. stop to exit
print c
3
Enter command to process commands 2. stop to exit
comp a b d
No command found
Enter command to process commands 2. stop to exit
cmp a b d
Enter command to process commands 2. stop to exit
print d
-1
Enter command to process commands 2. stop to exit
stop
Exiting the application...

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
For this assignment you need to write a parallel program in C++ using OpenMP for vector...
For this assignment you need to write a parallel program in C++ using OpenMP for vector addition. Assume A, B, C are three vectors of equal length. The program will add the corresponding elements of vectors A and B and will store the sum in the corresponding elements in vector C (in other words C[i] = A[i] + B[i]). Every thread should execute approximately equal number of loop iterations. The only OpenMP directive you are allowed to use is: #pragma...
2. Consider the data set has four variables which are Y, X1, X2 and X3. Construct...
2. Consider the data set has four variables which are Y, X1, X2 and X3. Construct a multiple regression model using Y as response variable and other X variables as explanatory variables. (a) Write mathematics formulas (including the assumptions) and give R commands to obtain linear regression models for Y Xi, i =1, 2 and 3. (b) Write several lines of R commands to obtain correlations between Xi and Xj , i 6= j and i, j = 1, 2,...
C++ PROGRAMMING Assignment: For this assignment, you will construct a program which is capable of taking...
C++ PROGRAMMING Assignment: For this assignment, you will construct a program which is capable of taking a user-given number, and adding up all of the numbers between 1 and the given number. So if someone inputs 12, it should add 1 + 2 + 3 + 4 + … 9 + 10 + 11 + 12, and return the answer. However, you’ll be using two different methods to do this. The first method should utilize either a for loop or...
UNIX COMMANDS Task B Create a one-line command, using the famous.dat file, to add the word...
UNIX COMMANDS Task B Create a one-line command, using the famous.dat file, to add the word " STREET" to the address, for all who live on 2nd or 3rd. For example: "2nd" becomes "2nd STREET" and "3rd" becomes "3rd STREET". Display only the first 9 lines. Hint: Use 2 sed statements with pipes. Task C Display all lines in famous.dat that end in 0 or 1, and have a 1 in the 3rd from the last column. For example lines...
1. By convention, how are configuration files separated from regular files? (NOTE: A practical effect of...
1. By convention, how are configuration files separated from regular files? (NOTE: A practical effect of the separation is that they are not displayed by the default version of the ls command)                         a. the prefix "rc" (rc.filename)               c. the extension .cfig                         b. a dot (.) at the beginning                    d. by having the SUID bit set 2. The IP address which is reserved for local loopback (equivalent to "localhost") is:                         a. 255.255.255.0                                   c. 192.168.70.1...
For this assignment, you will be creating a simple “Magic Number” program. When your program starts,...
For this assignment, you will be creating a simple “Magic Number” program. When your program starts, it will present a welcome screen. You will ask the user for their first name and what class they are using the program for (remember that this is a string that has spaces in it), then you will print the following message: NAME, welcome to your Magic Number program. I hope it helps you with your CSCI 1410 class! Note that "NAME" and "CSCI...
Answer the correlation questions using the data below. Use α = 0.05. x y 9 6...
Answer the correlation questions using the data below. Use α = 0.05. x y 9 6 8 3 7 4 7 1 0 1 0 1 0 0 a) Compute the correlation. r = ____ b) Compute the appropriate test statistic(s) for H1: ρ > 0. critical value = ____ ; test statistic = ____ Decision:  ---Select--- Reject H0 or Fail to reject H0 c) Compute the corresponding effect size(s) and indicate magnitude(s). If not appropriate, input and/or select "na" below....
Curve-Fit Function USING MATLAB Using the top-down design approach, develop a MATLAB function A8P2RAlastname.m that reads...
Curve-Fit Function USING MATLAB Using the top-down design approach, develop a MATLAB function A8P2RAlastname.m that reads data from a file and performs regression analysis using polyfit and polyval. The function shall have the following features: The input arguments shall include the file name (string), a vector of integers for the degrees of polynomial fits to be determined, and an optional plot type specifier (‘m’ for multiple plots, ‘s’ for a single plot - default). The data files will be text...
a/b x c/dy Let's design a class and explore more on object reference: A fraction with...
a/b x c/dy Let's design a class and explore more on object reference: A fraction with two private fields: a for representing numerator and b for representing denominator. Define a constructor Fraction() accept two integers to represent the numerator and denominator. Define a public instance method named printString() which returns a String in form of "a/b". Define a public instance method named multiplyBy() which accepts one argument of class type Fraction, calculates the multiplication between self and the receiving Fraction,...
Subject- ( App Development for Web) ( language C#, software -visual studio) Exact question is-Firstly the...
Subject- ( App Development for Web) ( language C#, software -visual studio) Exact question is-Firstly the console calculator is created which perform multiply,divide,sub and add, operation and it accept all type of data (divide by 0 case as well ).Now the main motive is to create the library project from the console calculator project .Than we have to create a unit test project which test the functionality of added library.Make test like Test 1. multiply two positive number,Test 2. Add...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT