Using either your own C-string functions of Lab 7.1 or the ones from the standrd C++ cstring library, create a String class, which — while having minimal functionality — illustrates the use of and need for the canonical form.
Overview
Here is the .h file for the class (note the class name — String with a capital S; trying to force the use of the classname string was to much of an issue:
class String { friend std::ostream &operator <<(std::ostream &os, const String &s); friend String operator +(const String &s1, const String &s2); public: String(const char *cs=""); String(const String &s); ~String(); String &operator =(const String &rhs); char &operator [](int index); String &operator +=(const String &s); int length() const; private: char *cs; };
I've also supplied a String_Exception class and an app for testing your class (it will be the test driver once I get it all into Codelab).
Implementation Notes
String::String(const char *cs) : cs(new char[strlen(cs)+1) { // the +1 is for the null terminator
#ifndef MYSTRING_H #define MYSTRING_H #include <iostream> class String { friend std::ostream &operator <<(std::ostream &os, const String &s); // friend bool operator ==(const String &s1, const String &s2); friend String operator +(const String &s1, const String &s2); public: String(const char *cs=""); String(const String &s); ~String(); String &operator =(const String &rhs); char &operator [](int index); String &operator +=(const String &s); // int find(char c) const; int length() const; // void clear(); private: char *cs; }; #endif
mystring_app.cpp
#include <iostream> #include <sys/sysinfo.h> #include <cstdlib> #include "mystring.h" using namespace std; int main() { String s = "Hello"; cout << "s: " << s << " (" << s.length() << ")" << endl; cout << "s + \" world\": " << s + " world" << endl; cout << "s[1]: " << s[1] << endl; String s1 = s; // making sure copy constructor makes deep copy String s2; s2 = s; // making sure assignment operator makes deep copy s[0] = 'j'; cout << endl; cout << "s: " << s << " (" << s.length() << ")" << endl; cout << "s1: " << s1 << " (" << s1.length() << ")" << endl; cout << "s2: " << s2 << " (" << s2.length() << ")" << endl; cout << endl; for (int i = 0; i < 5; i++) { s += s; cout << "s: " << s << " (" << s.length() << ")" << endl; } cout << endl; for (int i = 0; i < 5; i++) s += s; cout << "s: " << s << " (" << s.length() << ")" << endl; return 0; } mystring_exception.cpp
#ifndef MYSTRING_EXCEPTION #define MYSTRING_EXCEPTION #include <string> // Note this is the C++ string class! class String_Exception { public: String_Exception(std::string what) : what(what) {} std::string getWhat() {return what;} private: std::string what; }; #endif
In: Computer Science
Effect on pipelining
We consider the transmission of a message between 2 host A and B via a router. We dispose of the following information :
- the distance between each host and the router is 1500m.
- the speed of propagation = 360.000 km/s(speed of light)
- the size of each message = 1500 octets.
- the speed of the link between host and router = 1Mb/s
- the delay of treatment of a message in the router = 10ms
1) What is is the total delay to send a message from A to B ?
2) If we use the Stop and Wait protocol to send a message from A to B and the message size ACK = 64 octets, what is the utilization rate ?
3) If we use the Go-back-N protocol, with a time frame of size N, what is the value of N that maximize the flow control?
In: Computer Science
Language:C++
Program:Visual basic
I have errors on line 102 "expression must have a constant value
line 107,108,123,124,127,128: array type int[n] not assignable
#include<iostream>
#include <fstream>
using namespace std;
#define size 10000
// Displays the current Inventory Data
void Display(int box_nums[],int nboxes[],double ppBox[],int n) //
Prints Box number , number of boxes and price per box.
{
cout<<"Box number Number of boxes in stock Price per
box"<<"\n";
cout<<"-------------------------------------------------------------\n";
for(int i=0; i<n; i++)
{
cout<<box_nums[i]<<" "<<nboxes[i]<<"
"<<ppBox[i]<<"\n";
}
}
// sort's the inventory data according to the price per box from
low to high
void sortByPrice(int box_nums[],int nboxes[],double priceBox[],int
n)
{
int i, j, min_idx , temp2;
double temp;
for (i = 0; i < n-1; i++)
{
min_idx = i; // min_idx is used to store data in ascending
order
for (j = i+1; j < n; j++) // used selection sort to sort the
data based on price per box
{
if (priceBox[j] < priceBox[min_idx])
min_idx = j;
}
temp = priceBox[min_idx];
priceBox[min_idx] = priceBox[i]; // temp is a variable to swap
data
priceBox[i] = temp;
temp2 = nboxes[min_idx];
nboxes[min_idx] = nboxes[i]; // temp2 is a variable to swap
data
nboxes[i] = temp2;
temp2 = box_nums[min_idx];
box_nums[min_idx] = box_nums[i];
box_nums[i] = temp2;
}
}
// sort's the inventory data according to Box number from low to
high
void sortByBoxNumber(int box_nums[],int nboxes[],double
priceBox[],int n)
{
int i, j, min_idx , temp2;
double temp;
for (i = 0; i < n-1; i++)
{
min_idx = i; // min_idx is used to store data in ascending
order
for (j = i+1; j < n; j++)
{
if (box_nums[j] < box_nums[min_idx]) // used selection sort to
sort the data based on price per box
min_idx = j;
}
temp2 = box_nums[min_idx];
box_nums[min_idx] = box_nums[i];
box_nums[i] = temp2;
temp = priceBox[min_idx];
priceBox[min_idx] = priceBox[i];
priceBox[i] = temp;
temp2 = nboxes[min_idx];
nboxes[min_idx] = nboxes[i];
nboxes[i] = temp2;
}
}
// Searches for the price per box of the corresponding box
number entered by user.
double lookUpByBoxNumber(int boxNumber,int box_nums[],double
priceBox[],int n)
{
int low =0, high = n-1;
int mid;
while(low <= high) // used binary search to search for the
corresponding box number and its price-per-box
{
mid = low + (high-low)/2;
if(box_nums[mid] > boxNumber)
{
high = mid - 1;
}
else if(box_nums[mid] == boxNumber)
{
return priceBox[mid];
}
else
{
low = mid + 1;
}
}
return -1;
}
//Reordered the data whose number of boxes are less than
100
void reorderReport(int box_nums[],int nboxes[],int n)
{
int reorderBoxNums[n],reorderBoxes[n],k=0;
for(int i=0; i<n; i++)
{
if(nboxes[i] < 100)
{
reorderBoxNums[k] = box_nums[i];
reorderBoxes[k] = nboxes[i];
k++;
}
}
int i, j, max_idx , temp2;
for (i = 0; i < k-1; i++) // sorts the data in reordered data
according to number of boxes in inventory from low to high
{
max_idx = i;
for (j = i+1; j < k; j++)
{
if (reorderBoxes[j] > reorderBoxes[max_idx])
max_idx = j;
}
temp2 = reorderBoxes[max_idx];
reorderBoxes[max_idx] = reorderBoxes[i];
reorderBoxes[i] = temp2;
temp2 = reorderBoxNums[max_idx];
reorderBoxNums[max_idx] = reorderBoxNums[i];
reorderBoxNums[i] = temp2;
}
cout<<"REORDERED REPORT IS: \n";
cout<<"The boxes in invetory whose stock are less than 100
are: \n";
cout<<"Box number Number of boxes in
stock"<<"\n";
cout<<"------------------------------------------"<<"\n";
for(int i=0 ; i<k; i++)
{
cout<<reorderBoxNums[i]<<"
"<<reorderBoxes[i]<<"\n";
}
}
int main()
{
std::fstream myfile("inventory.txt");
int box_number[size] , numberOfBoxes[size] ;
double pricePerBox[size],sp;
int bn ,nb,i = 0;
while(myfile >> bn >> nb >> sp) // fetch data
from file inventory.txt
{
box_number[i] = bn;
numberOfBoxes[i] = nb;
pricePerBox[i] = sp;
i++;
}
int n = i, bnumber ; // n stores number of records in file ,
bnumber is the box number which is to be searched for price-per-box
by user
double val; // val is variable used for value stored from lookup by
box-number
char option;
bool exit = true; // exit variable to exit the while loop
// Menu for the user
cout<<"\nChoose a option in the Menu a/b/c/d/e/f
:"<<"\n";
cout<<"a. Display the data"<<"\n";
cout<<"b. Sort data by price, low to high"<<"\n";
cout<<"c. Sort data by box number, low to
high"<<"\n";
cout<<"d. Look up the Price of the box given the box
number"<<"\n";
cout<<"e. Generate Reorder Report"<<"\n";
cout<<"f. Exit"<<"\n";
while(exit)
{
cout<<"Enter your choice a/b/c/d/e/f : ";
cin>>option;
switch(option)
{
case 'a':
Display(box_number,numberOfBoxes,pricePerBox,n);
break;
case 'b':
sortByPrice(box_number,numberOfBoxes,pricePerBox,n);
cout<<"Data has been Successfully sorted by
price"<<"\n";
cout<<"Please, choose option 'a' to display sorted
data"<<"\n";
break;
case 'c':
sortByBoxNumber(box_number,numberOfBoxes,pricePerBox,n);
cout<<"Data has been Successfully sorted by Box
Number"<<"\n";
cout<<"Please, choose option 'a' to display sorted
data"<<"\n";
break;
case 'd':
sortByBoxNumber(box_number,numberOfBoxes,pricePerBox,n);
cout<<"Enter the box number for which you want to search the
price : ";
cin>>bnumber;
val = lookUpByBoxNumber(bnumber,box_number,pricePerBox,n);
if(val < 0)
{
cout<<"There is no price of the box for the box number you
are searching for\n";
}
else
{
cout<<"The price-per-box of the Box-Number you searched is
"<<val<<"\n";
}
break;
case 'e':
reorderReport(box_number,numberOfBoxes,n);
break;
case 'f':
exit = false;
break;
default :
cout<<"Invalid options , enter a valid
option"<<"\n";
break;
}
}
return 0;
}
In: Computer Science
Please type, I will rate you well. Thank you.
In Linux:
In: Computer Science
Exercise 1. Rectangle, Circle and Square Write three Python
classes named Rectangle constructed by a length and width, a Circle
constructed by a radius and a Square constructed by a side length.
Both classes should have the methods that compute: - The area - The
diagonal - The perimeter Use as much abstraction as you can. At the
end of the file, use those classes to calculate the perimeter of a
circle with radius the half of the diagonal of a rectangle with
length 20 and width 10.
In: Computer Science
For the following problem, draw a flowchart, write a function and then execute the function with your choice of input parameter values:
For given two input parameters: If parameter 1 is smaller than parameter 2 return the remainder of parameter 1 by parameter 2 Otherwise, return the multiplication of two input parameters.
Python programming language
In: Computer Science
In: Computer Science
In this project you will create a basic console based calculator program. The calculator can operate in two modes: Standard and Scientific modes. The Standard mode will allow the user to perform the following operations: (+, -, *, /) add, subtract, multiply, and divide The Scientific mode will allow the user to perform the same functionality as the Standard add, subtract, multiply, and divide (+, -, *, / ) plus the following: sin x, cos x, tan x. (sin x, cos x, tan x) The calculator should be able to perform addition, subtraction, multiplication, and division of two or more numbers but perform sin x, cos x, and tan x of one number only (the number is in radians). 1. The calculator program will first ask the user for the mode to operate in (Standard or Scientific) Sample Output: Enter the calculator mode: Standard/Scientific? Standard 2. The program should then ask the user for the operation to execute (+, -, *, /, sin x, cos x, tan x) Sample Output for Scientific mode: Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: sin Sample Output for Scientific mode: Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: sin 2a. If the user enters an invalid operation, output a message telling the user the input is invalid and re-prompt the user for the operation again. Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: division Invalid operation entered Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: / 3. In order to know how many times the user will need to perform the operation, prompt the user for the number of double values they want to enter (All numbers in this program are double), then ask the user to enter the numbers. Sample Output: How many numbers do you want to subtract: 3 Enter 3 numbers: 4 35 9 In this example the calculator will calculate 4 + 35 + 9. The result will be 48. The calculator should be able to perform the following operations: 2+3 = 5 3+6+1+1+1 = 12 1-2-90 = -91 10*2*3 = 60 10/2/5 = 1 cos(0) = 1 sin(0) = 0 tan(0) = 0 Note: This calculator does NOT support multiple operations in the expressions like: 10+2-8 Note: Multiple numbers are only acceptable for the operations of (+, -, *, / ) not for (sin,cos,tan) 4. Display the result Sample Output: Result: 50.0 5. Finally, output the result to the user and ask the user if he/she want to start over. Sample Output: Start over? Y/N Y Full Sample Output: Enter the calculator mode: Standard/Scientific? Standard Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: addition Invalid operation entered Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: + How many numbers do you want to subtract: 3 Enter 3 numbers: 4 35 9 Result: 48.0 Start over? Y/N Y Enter the calculator mode: Standard/Scientific? Scientific Enter '+' for addition, '-' for subtractions, '*' for multiplication, '/' for division, 'sin' for sin x, 'cos' for cos x, 'tan' for tan x: sin Enter number in radians to find sin: 1.5708 Result: 1 Start over? Y/N N
In: Computer Science
2. RFID tags are being increasingly used by companies such as Macy's, Walmart, and Home Depot. Identify an additional company that uses RFIDs and describe the company’s specific application of RFIDs.
In: Computer Science
Write a C++ programm which
Please add comments next to the code, so I can learn from the solution. Also please use beginner coding, nothing too advance.
In: Computer Science
C++ question.
I want to write all output to the file "output.txt", but it will write just first character. Can you fix it?
#include
#include
#include
#include
#include
using namespace std;
using std::cin;
using std::cout;
using std::string;
// remove dashes convert letters to upper case
string normalize(const string &isbn) {
string ch;
for (char i : isbn) {
if (i == '-') {
continue; // if "-" then skip it
}
if (isalpha(i)) {
i = toupper(i); // Check uppercase
}
ch += i;
}
return ch;
}
// return the number of digits in to the string
size_t numDigits(string &str) {
size_t numDigits = 0;
for (char ch : str) {
if (isdigit(ch)) {
++numDigits;
}
}
return numDigits;
}
enum ValidationCode {
Ok, // validation passed
NumDigits, // wrong number of digits
ExtraChars,// extra characters in isbn
Done
};
enum ValidationCode validate(string &isbn) {
int Done = 4;
string normal = normalize(isbn);
size_t count = numDigits(normal);
if (normal.size() == Done)
exit(0);
if (count != 10) {
return NumDigits;
}
if (normal.size() == 10 || normal.size() == 11 && normal[10] == 'X') {
return Ok;
}
return ExtraChars;
}
int main() {
// open a file
ofstream file("output.txt");
//The following code is taken from (https://en.cppreference.com/w/cpp/io/basic_ios/fail)
// check if the file can open
if(!file) // operator! is used here
{
std::cout << "File opening failed\n";
return EXIT_FAILURE;
} //end of borrowed code
// read a file
//The following code is referenced from (https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c)
std::ifstream ifs("test_data.txt");
// check if the file can read
if (ifs.fail())
{
std::cerr << "test_data.txt could not read" << std::endl;
return -1;
} //end of referenced code
std::string str;
while (ifs >> str){
switch (validate(str)) {
case Ok:
cout << str << " is a valid isbn\n";
file << str << " is a valid isbn\n";
break;
case NumDigits:
cout << str << " doesn't have 10 digits\n";
file << str << " doesn't have 10 digits\n";
break;
case ExtraChars:
cout << str << " has extra characters\n";
file << str << " has extra characters\n";
break;
default:
cout << "ERROR: validate(" << str << ") return an unknown status\n";
file << "ERROR: validate(" << str << ") return an unknown status\n";
break;
}
}
ifs.close();
file.close();
}
test_data.txt
1-214-02031-3
0-070-21604-5
2-14-241242-4
2-120-12311-x
0-534-95207-x
2-034-00312-2
1-013-10201-2
2-142-1223
3-001-0000a-4
done
In: Computer Science
Using the sample code included at the end of the document to create the tables, Please write an anonymous PL/SQL program the following problems.
Problem 1. Print out estimated charge for rental ID 1 if the customer returns the tool in time. The charge is computed by the price in the price_tool table * number of units the customer plans to rent. E.g., if a customer rents a tool hourly for 5 hours, and the hourly rate for the tool is $6, the estimated charge should be $30. [30 points]
Problem 2. [30 points] Print out name of tools rented by Susan and their due time.
--------- Sample code
drop table rental cascade constraints;
drop table tool_price cascade constraints;
drop table tool cascade constraints;
drop table category cascade constraints;
drop table cust cascade constraints;
drop table time_unit cascade constraints;
create table cust(
cid int, -- customer id
cname varchar(50), --- customer name
cphone varchar(10), --- customer phone
cemail varchar(30), --- customer email
primary key(cid)
);
insert into cust values(1,'John','1234567888','[email protected]');
insert into cust values(2,'Susan','1235555555','[email protected]');
insert into cust values(3,'David','1237777777','[email protected]');
create table category(
ctid int, --- category id
ctname varchar(30), --- category name
parent int, --- parent category id
primary key(ctid),
foreign key (parent) references category
);
insert into category values(1,'mower',null);
insert into category values(2,'electric mower',1);
insert into category values(3,'gasoline mower',1);
insert into category values(4,'carpet cleaner',null);
create table tool
(tid int, --- tool id
tname varchar(50), -- tool name
ctid int, --- category id
quantity int,
primary key (tid),
foreign key (ctid) references category
);
insert into tool values(1,'21 inch electric mower',2,2);
insert into tool values(2,'30 inch large gasoline mower',3,2);
insert into tool values(3,'small carpet cleaner',4,2);
insert into tool values(4,'large carpet cleaner',4,2);
create table time_unit
(tuid int, --- time unit id
len interval day to second, --- length of unit, can be 1 hour, 1 day, etc.
min_len int, --- minimal number of units
primary key (tuid)
);
--- hourly minimal four hours.
insert into time_unit values(1, interval '1' hour, 4);
-- hourly minimal 1 day
insert into time_unit values(2, interval '1' day, 1);
--- weekly
insert into time_unit values(3, interval '7' day, 1);
create table tool_price
(tid int, --- too id
tuid int, --- time unit id
price number,
primary key(tid,tuid),
foreign key(tid) references tool,
foreign key(tuid) references time_unit
);
--- mower, $20 per 4 hours. $30 per day
insert into tool_price values(1,1,5.00);
insert into tool_price values(1,2,30);
insert into tool_price values(1,3,120);
insert into tool_price values(2,1,7.00);
insert into tool_price values(2,2,40);
insert into tool_price values(2,3,160);
insert into tool_price values(3,1,6.00);
insert into tool_price values(3,2,32);
insert into tool_price values(3,3,125);
insert into tool_price values(4,1,7.00);
insert into tool_price values(4,2,40);
insert into tool_price values(4,3,160);
create table rental
(
rid int, --- rental id
cid int, --- customer id
tid int, --- tool id
tuid int, --- time unit id
num_unit int, --- number of units, if unit = 1 hour, num_unit = 5 means 5 hours.
start_time timestamp, -- rental start time
end_time timestamp, --- suppose rental end_time
return_time timestamp,--- actual return time
credit_card varchar(20),
total number, --- total charge
primary key (rid),
foreign key(cid) references cust,
foreign key(tid) references tool,
foreign key(tuid) references time_unit
);
-- John rented a mower for 4 hours,
insert into rental values(1,1,1,1,4,timestamp '2019-08-01 10:00:00.00',null,null,'123456789',null);
-- susan rented a small carpet cleaner for one day
insert into rental values(2,2,3,2,1,timestamp '2019-08-11 10:00:00.00',null,null,'123456789',null);
--susan also rented a small mower for 5 hours, before 8 am case
insert into rental values(3,2,1,1,5,timestamp '2019-08-12 21:00:00.00',null,null,'123456789',null);
--david also rented a small carpet cleaner for 4 hours, after 10 pm case
insert into rental values(4,3,3,1,4,timestamp '2019-08-13 19:00:00.00',null,null,'12222828828',null);
commit;
In: Computer Science
Use the median of 3 partitioning algorithm (given in the next page) to implement quick sort. This algorithm chooses the pivot element as the median of the 3 elements namely: A[p], A[r], and A[(p+r)/2].(Java language)
Quicksort(A,p,r)
1 if p
2 N = r- p +1
3 m = Median3(A, p, p + N/2 , r)
4 exchange A[m] with A[r]
5 q = Partition (A,p,r)
6 Quicksort(A,p, q-1)
7 Quicksort(A,q+1,r)
In: Computer Science
Write a function of interest to you. It should that take at least 3 inputs from different types and return at least three different values.
Call your function from the main.
Print the resultant outputs in the main (not in the function).
In: Computer Science
Construct a DFA machine to recognize the language of all binary
numbers which are a multiple of 5.
L = { w belongs {0,1}* : w is a binary number and is a multiple of
5}
Example: 101 belongs to L; 1010 belongs to L; 110 doesn't belong to
L.
In: Computer Science