Please use R studio
Dataset: IBM HR Analytics Employee Attrition & Performance dataset (you can download the dataset from kaggle)
Name
Description
ATTRITION
Employee leaving the company (0=no, 1=yes)
BUSINESS TRAVEL
(1=No Travel, 2=Travel Frequently, 3=Tavel Rarely)
DEPARTMENT
(1=HR, 2=R&D, 3=Sales)
EDUCATION FIELD
(1=HR, 2=LIFE SCIENCES, 3=MARKETING, 4=MEDICAL SCIENCES, 5=OTHERS, 6= TEHCNICAL)
GENDER
(1=FEMALE, 0=MALE)
JOB ROLE
(1=HC REP, 2=HR, 3=LAB TECHNICIAN, 4=MANAGER, 5= MANAGING DIRECTOR, 6= REASEARCH DIRECTOR, 7= RESEARCH SCIENTIST, 8=SALES EXECUTIEVE, 9= SALES REPRESENTATIVE)
MARITAL STATUS
(1=DIVORCED, 2=MARRIED, 3=SINGLE)
OVERTIME
(0=NO, 1=YES)
The Variable Attrition is what we plan to use as our dependent variable. The variable contains a Yes if they stay with IBM and 'No' if they do not. We need to creat into a binary dummy variable with 0 if they do not stay with IBM (Attrition = 'No') and 1 if they do stay with IBM (Attrition = 'Yes'). This will also need to be done to the variable Gender and OverTime. Gender we can assign "Male" to zero and "Female" to one. For OverTime we will assign 0 for "No" and 1 for "Yes".
Make Pivot tables instead of correlation matrixes for categorical variables and do the data analysis.
For data analysis:
In: Computer Science
What are the System Requests in this project?
System Request
Introduction
Northern Ontario Recreational Vehicle Storage (NORVS) specializes
in supply of local storage as a convenient and safe alternative to
pulling a trailer up and down the highways, and a seasonal storage
facility to protect valuable items from the elements in the off
season. The type of vehicles that they store are snowmobiles, All
Terrain Vehicles (ATVs), boats, Recreational Vehicles (RVs) and
camper trailers (see examples at the end of this document).
The type of customers that use this service are people who own such vehicles for seasonal activities and need somewhere to store then during the off season.
Your responsibility will be to take the information in the Business Summary section and create the deliverable documentation.
Business Summary
Existing System
NORVS current system is completely manual. If a customer needs to store something at the facility, they call in and either the owner, or an employee will take down details for the client’s desired storage on their intake form. When the customer arrives to drop off their vehicle(s), an employee must be available to meet them in order to permit access to the secured site. The customer makes payment at this time if they did not leave a credit card number when the booking was initially arranged. Vehicle pickups follow the same process since the site is not manned on a full-time basis.
The storage facility consists of indoor and outdoor space. Storage spaces have been configured in the following sizes to accommodate the most common vehicles.
To meet larger requirements, individual spaces are combined to suit the needs of the specific vehicle. Each space has an ID which locates it on the property for both internal and external locations. Space allocations by client are maintained on a large magnetic whiteboard layout of the property. Red magnetized cards are placed in occupied spaces with the client’s name written on them. This allows staff to keep track of space utilization, however, it is not always up to date. Vehicles are often relocated to either consolidate space or improve access and the changes are not always made to the whiteboard. New vehicle arrivals are frequently not listed on the board. When discovered, it requires an extensive amount of work to bring the whiteboard up to date.
This issue has caused some embarrassments to the owners as they have committed space to new clients based on the whiteboard information only to discover that spaces have already been filled.
The owners also find it difficult to compile monthly reports of revenues and to follow up with their clients for future repeat bookings. Contact information is misplaced or not correctly captured during the initial contact. Other storage facilities are now moving into the area offering competition and in order to compete and grow their business they must upgrade their system.
Proposed New System
The owners have decided to implement a new internet-based system. This system will provide the required functionality to support both desktop/laptop and mobile phone access using the internet.
One of the main features of the new system will be an integrated storage space management component that tracks space availability based on “reservation commitments” and “contracted commitments”. When spaces are vacated, reservations cancelled or converted to a contract, the system will be automatically updated to ensure space availability status for new client enquiries. There will also be an administrative function built into the storage space management component to allow the owner and employees to adjust the spaces should they decide to move vehicles from one spot to another for convenience. The administrator will also be permitted to add, drop, and merge spaces depending on needs. This administrative feature would only be available to management.
When clients complete a reservation request, they must supply all their contact information along with specific details of the vehicle(s) to be stored. This will include make, model, color, year of manufacture of the vehicle and approximate value. A photo image would also be uploaded, attached to the application. In addition, the width, height and length of the vehicle(s) will also be required to confirm storage space needs. Finally, indoor or outdoor storage will be specified on the client request. When the request is approved it then becomes the Rental Agreement. If the request is denied, it is deleted.
In order to permit clients 7X24X365 access to the site, the owners would like to install a biometric security gate. Clients would be able to drive up to the gate and scan their finger print or eyes (iris recognition) and activate the gate to allow them to enter and leave the storage facility at their convenience. This would also allow management to have a log of exactly who entered and exited the facility, and at what time. The initial biometric registration would take place after the reservation has been confirmed. i.e., payment has been received.
The new system will directly interface to a third-party credit card authorization service, such as PayPal, to handle all payment transactions.
The system will also provide monthly statements in hard or soft copy depending on client preferences. This preference will be identified in the client registration process and can be modified at any time by the client through the client profile management component which would be secured by username and password authentication. Client profile management will allow clients to access and change their contact information at any time.
Finally, the owners would like to have a built-in management reporting feature as part of the system which would allow them to track all business activity including;
In: Computer Science
3.1
What are the shared characteristics of different agile methods of software development?
2. For what types of system are agile approaches to development particularly likely to be successful?
3. List the 5 principles of agile methods.
4. List 4 questions that should be asked when deciding whether or not to adopt an agile method of software development.
5. Name three important agile techniques that were introduced in extreme programming?
6. What is test-first development?
7. What are the possible problems of test-first development?
8. Why has the Scrum agile method been widely adopted in preference to methods such as XP?
9. What is a Scrum sprint?
10. What are the barriers to introducing agile methods into large companies?
In: Computer Science
When the user enters 4 at the menu prompt, your program will access all objects in the array to calculate and display only the largest number of coin denomination, and the total number of coins for the largest denomination. If there are more than one coin denominations having equal amount, you will need to list down all of them. After processing the output for menu option 4, the menu is re-displayed.
Menu option 4 should return as follows.
The largest number of coin denomination is: $1 5 cent
The total number of $1 coin is: 2 The total number of 5 cent coin is: 2
i'm stuck with the returnDenomination() method
===
// import Scanner class to take user input
import java.util.Scanner;
// Client class
public class Client {
// for display colored terminal output
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_GREEN = "\u001B[32m";
// scanner object
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// declare and initialise variables
char yesNo = ' ';
String name;
boolean newPerson;
int menuInput;
int coinAmount;
int personNum = 0;
// declar array of object, Change type
Change person[] = new Change[10];
// for the purpose of testing the program by tutor, hard-coded data
personNum = 9;
person[0] = new Change("Abel", 10);
person[1] = new Change("Belle", 25);
person[2] = new Change("Chanel", 235);
person[3] = new Change("Desmond", 240);
person[4] = new Change("Elaine", 55);
person[5] = new Change("Farah", 60);
person[6] = new Change("Gabriel", 170);
person[7] = new Change("Hazel", 285);
person[8] = new Change("Iris", 190);
// display recommendation msg
System.out.print(ANSI_YELLOW);
System.out.print("\n[System Msg] ");
System.out.print(ANSI_RESET);
System.out.println("Recommendation: Please enter at least 9 records to test the program.");
// loop while userInput is not 'N' for new person
do {
newPerson = true;
System.out.println("\nCurrent record: " + personNum + "/9");
// userInput for name & coinAmount
System.out.print("\nPlease enter the name of the person: ");
name = userInput.nextLine();
System.out.print("Please enter coin value for the person (range 5 to 95, a multiple of 5): ");
coinAmount = userInput.nextInt();
userInput.nextLine();
// verify if useInput amount is valid (range 5 to 95, multiple of 5)
if(coinAmount < 5 || coinAmount > 95 || (coinAmount % 5) !=0) {
System.out.print(ANSI_YELLOW);
System.out.print("\n[System Msg] ");
System.out.print(ANSI_RESET);
System.out.println("Incorrect coin value. Must be in the range 5 to 95, multiple of 5");
continue;
}
// verify person in record
for (int i = 0; i < personNum; i++) {
// update total amount if name matches exisiting record
if (person[i].getName().equalsIgnoreCase(name)) {
person[i].setAmount(person[i].getAmount() + coinAmount);
newPerson = false;
break;
}
}
// add to record if the person is new
if (newPerson)
person[personNum++] = new Change(name, coinAmount);
// break when number of person in record greater/equals 9
if (personNum >= 9)
break;
System.out.print("\nDo you have more person to enter (Y/N): ");
yesNo = Character.toUpperCase(userInput.nextLine().charAt(0));
// verify only Y or N userInput
while (yesNo != 'Y' && yesNo != 'N') {
System.out.print(ANSI_YELLOW);
System.out.print("\n[System Msg] ");
System.out.print(ANSI_RESET);
System.out.print("Invalid! Do you have more person to enter (Y/N): ");
yesNo = Character.toUpperCase(userInput.nextLine().charAt(0));
}
} while(yesNo != 'N'); // end of newPerson do-while loop
// loop until userInput 5 to exit
do {
// display menu
System.out.println("\n1. Enter a name and display change to be given for each denomination");
System.out.println("2. Find the name with the smallest amount and display change to be given for each denomination");
System.out.println("3. Find the name with the largest amount and display change to be given for each denomination");
System.out.println("4. Calculate and display the largest number of coin denomination, and the total number of the coin");
System.out.println("5. Exit");
// wait for userInput
System.out.print("\nWhat would you like to do? Enter your choice: ");
menuInput = userInput.nextInt();
userInput.nextLine();
// display according to userInput
switch (menuInput) {
// display changes based on name of person entered
case 1:
returnIndividual(person, personNum);
break;
// display person with smallest amount and changes
case 2:
returnSmallest(person, personNum);
break;
// display person with largest amount and changes
case 3:
returnLargest(person, personNum);
break;
// display total of largest numer of coin denomination
case 4:
returnDenomination(person, personNum);
break;
// display farewell message and exit program
case 5:
System.out.print(ANSI_YELLOW);
System.out.print("\n[System Msg] ");
System.out.print(ANSI_RESET);
System.out.println("Have a good day ahead. Bye!\n");
System.exit(0);
break;
// default for no case match
default:
System.out.print(ANSI_YELLOW);
System.out.print("\n[System Msg] ");
System.out.print(ANSI_RESET);
System.out.println("Invalid! Please enter your choice again: \n");
}
} while (menuInput != 5); // end of menu do-while loop
} // end of main()
// method to find individual person by name and display denomination
public static void returnIndividual(Change person[], int personNum) {
// declare variable to store array of denomination
int denomination[] = new int[4];
// prompt userInput for name
System.out.print("Enter name: ");
String name = userInput.nextLine();
boolean nameNotFound = true;
// verify display name and coinAmount in record
for (int i = 0; i < personNum; i++) {
if (person[i].getName().equalsIgnoreCase(name)) {
// calculate and return count of each denomination
denomination = person[i].calDenomination();
System.out.println(ANSI_GREEN);
System.out.println("\n" + person[i].getName() + " has an account of: " + person[i].getAmount() + " cents\n");
// display count of each denomination
System.out.println("Change:");
if (denomination[0] != 0)
System.out.println("$1 : " + denomination[0]);
if (denomination[1] != 0)
System.out.println("50¢: " + denomination[1]);
if (denomination[2] != 0)
System.out.println("20¢: " + denomination[2]);
if (denomination[3] != 0)
System.out.println("10¢: " + denomination[3]);
if (denomination[4] != 0)
System.out.println("5¢ : " + denomination[4] + "\n");
System.out.println(ANSI_RESET);
// set flag to false since name is in record
nameNotFound = false;
break;
}
}
// display error msg if name not in record
if (nameNotFound) {
System.out.print(ANSI_YELLOW);
System.out.print("\n[System Msg] ");
System.out.print(ANSI_RESET);
System.out.println(name + " not found in record!\n");
}
} // end of returnIndividual()
public static void returnDenomination(Change person[], int personNum) {
// for menu 4
} // end of returnDenomination
} // end of Client class
In: Computer Science
What is a growth function? How does it relate to the efficiency of an algorithm? Explain with example.
In: Computer Science
1. What are the fundamental activities that are common to all software processes?
2. List 3 generic process models that are used in software engineering?
3. Why are iterations usually limited when the waterfall model is used?
4. What are the three benefits of incremental development, compared to the waterfall model?
5. What are the development stages in integration and configuration?
6. What are the principal requirements engineering activities?
7. Why is it increasingly irrelevant to distinguish between software development and evolution?
8. What are the advantages of using incremental development and delivery?
9. What are the two different approaches to process improvement and change that have been proposed?
10. What are the identified levels in the SEI’s Capability Maturity Model
In: Computer Science
Functional & non-functional requirements document
The following document has gathered from various sources, including engineers working in our company, interviews, contacts with the client, etc., all the requirements for a project described below. You are strongly advised to read the following document multiple times, and keep notes. Don’t bother searching on the internet, you will not find anything helpful. Instead, you have to be the chief Software Engineer, and your mission is to describe functional and non-functional requirements, as good and detailed as possible. When you are missing data, you have to make assumptions (sometimes wild ones). No one can really answer your questions, and you have a presentation to the higher management in 45 min sharp. By then, you have to construct a document, with a very small ( no more than 10 lines) executive description, and no more than two A4 pages (1.25 space, font 12) text. Good luck.
INFORMATION ABOUT THE PROJECT
Our company is seriously considering of bidding for the following project, and we ask you, the lead Software Engineer, to construct a draft document, with the functional and non-functional requirements. The better your document, the better job will do our business development team to construct a proposal.
Project abstract description
The project is about monitoring the two gates of the University, automate the entry of authorized personnel, plus record all car license plates, if they left at night, and also raise alarms if a car is in the parking for more than 5 days. Also the system needs to report cars that are still at the parking, or during any holiday, or when the University is closed officially (e.g., during summer holidays). During those periods, only high-ranking personnel is automatically allowed to enter (e.g., Deans). All others need to be stopped at the gate, and call their supervisor. For that purpose, the following descriptions have been gathered.
Notes
• Each security room next to each gate, will be equipped with the necessary hardware, in order for the guards to see the license plate camera, plus another camera facing the car driver. Also each car will be equipped with electronic id device. The entry bar will be connected to the system, and will be automatically raised, if the car and driver are both authorized.
The license plate cameras have to have a good false positive rate. The driver-side camera will not do face recognition at the beginning, but the client wants this to be an option for the near future.
The time it takes for one car to enter, is of great importance. The client needs to know this in detail.
There should be a “manual override” button on the screen, but the system should keep all details possible, guard details, time, date, car & license picture, etc.
The client will accommodate all data into their own facilities and infrastructure, but they will not provide any hardware/software for this project.
The guards will be trained accordingly if desired.
The data gathered should not be used for other purposes.
The staff, students, faculty, are really worried about their personal data, and how those
are going to be used. Some even claim that the data will be used to monitor their
working time.
Our company, is worried about the cost of this project, and we want to find innovative
ways to keep the cost low, so we can bid a lower price, and get a competitive advantage
against other bidders.
Our company also is not very experienced in such projects, and they hired you to “make
the difference”
(no specific language nor coding needed )
In: Computer Science
Hands-On Project 19-2 Print in the Cloud
To practice cloud printing using Google Cloud Print, you’ll need a computer with an installed printer and another computer somewhere on the Internet. For the easiest solution to using Google Cloud Print, both computers need Google Chrome installed. You’ll also need a Google account. On the computer with an installed printer, do the following:
1. If you don’t already have Google Chrome, go to google.com/chrome/browser/desktop, download, and install it.
2. Open Google Chrome and enter chrome://devices in the address box. Click Add printers. Sign in to Google with your Google account. If you don’t already have an account, you can click Create account to create one.
3. The list of installed printers appears. Uncheck all printers except the one you want to use for cloud printing. Click Add Printer(s). On a computer anywhere on the Internet, do the following:
4. If necessary, install Google Chrome.
5. Open Google Chrome and sign in with your Google account. Navigate to a webpage you want to print. Click the menu icon in the upper-right corner of the Chrome window and click Print.
6. On the Print page, click Change and select the printer, which is listed in the Google Cloud Print group. Click Print. The page prints over the web to your printer.
In: Computer Science
Question?
Identify the relationships of Player and Player fields including PKs, CKs, and FDs. While using the entities and fields found in Player, create a DBDL example of tables, fields, and key fields that are in third normal form.
Instructions: Convert this table to an equivalent collection of tables, fields, and keys that are in the third normal form. Represent your exercise answers in DBDL design from the database normalization phases.
The player contains information about players and their teams.
Player has attributes PlayerId, First, Last, Gender, TeamId, TeamName, TeamCity where PlayerId is the only CK and the FDs are:
PlayerId → First
PlayerId → Last
PlayerId →Gender
PlayerId → TeamId
PlayerId → TeamName
PlayerId → TeamCity
TeamId → TeamName
TeamId → TeamCity
Figure 1: Player – Sample Data
PlayerID | First | Last | Gender | TeamID | TeamName | TeamCity |
1 | Jim | Jones | M | 1 | Flyers | Winnipeg |
2 | Betty | Smith | F | 5 | OilKings | Calgary |
3 | Jim | Smith | M | 10 | Oilers | Edmonton |
4 | Lee | Mann | M | 1 | Flyers | Winnipeg |
5 | Samantha | McDonald | F | 5 | OilKings | Calgary |
6 | Jimmy | Jasper | M | 99 | OilKings | Winnipeg |
In: Computer Science
A local client needs to take his static web page for ordering organic vegetables and build a dynamic page. He doesn't have much money to spend, so we are going to write orders to a flat file. He is also going to need a page that he can go to that will display his orders.
He has already met with Sharron, so we've got a specification already assembled. Here are the details:
The customer will go to a form page where they can enter an order for vegetables. The file will be called orderVegetables.php. Here are products a customer can order:
The customer should be able choose a quantity of items beside any of the vegetable options. Only allow orders where there is at least one thing ordered. Also, if the total price is over $50 then they qualify for free delivery, otherwise delivery cost is $5.00. (You can apply the delivery fee after tax, or before). Be sure to also capture the customers name, email and phone number on the form so the client can contact them to setup delivery. Make sure each order has the date and time of the order as well. Don't forget to use \r\n for a new line at the end of each record.
When the user clicks 'submit,' a POST request is made to processVeggies.php where the order is written to the file veggie-orders.txt. The text file should be simply a storage place in lieu of using a proper database. Some would call it a 'flat-file' storage system. Make sure to lock the file before appending, and to unlock it afterwards. Display a thank you message to the client and print their order details to the screen. Let them know that they will be contacted within the next business day.
Of course the client would like a page to view all the orders. This file will be called viewOrders.php. The client would like a link on this page to reset the orders (reset the veggie-orders.txt file) called Reset Orders. This link will call a file resetOrders.php. The client will typically print off a days worth of orders and then reset the form for the next day. Don't worry about locking the file on your reset page.
Good luck! We need this prototype soon!
- Ima Plant
Senior Consultant,
Acme International Inc.
====
The order form also needs to capture customer name, phone number, and email.
What to expects
1. The input page (named orderVegetables.php) needs to have the following fields:
a. Select drop-down fields should be used to allow users to choose a quantity for each item. Limit the options to 0-30.
b.We also need fields for name, email, and phone number.
2. Look and Feel: Use bootstrap or not, your choice. The header of each page should contain a masthead/header image that would befit an upscale veggie shop. Please use GIMP, MS PAINT or some other editor to create this header image for the top of your page. Or better yet, set your header text using <h1> or <h2> and set the image you create as a background-image in your CSS. As well, all formatting should be done using CSS in an external stylesheet. Please use a div with an id of 'container' to hold your content. Ensure that this simple theme is present for ALL of your pages!
3. The processing page (named processVeggies.php) needs to include the following:
a. Order details gathered from input form.
b. Whether or not delivery is free - display a message to the user one way or the other (include dollar sign and two decimal places - that is, format for currency)
c. Assume a provincial tax rate of 15%
d. Calculate and display the details of their order, net amount before tax, tax amount, delivery amount, and total amount.
e. Include the time, date, and year (for Atlantic Canada) that the order was processed.
f. Ensure that there is some type of validation on the processing page. If someone tried to run it without accessing the form page first, it should give the user a link back to the order page.
4. The processing page (processVeggies.php) should also write this order to a file.
a .Ensure file is accessible to your script, but hidden from public browsing. Please note that veggie-orders.txt MUST be stored one directory behind your publishing directory. "$DOCUMENT_ROOT/../veggie-orders.txt" would be an example.
b. Orders file should be delimited by a "\t" or some other delimiter. " \r\n" at the end of each line.
5. The viewOrders.php page should open the file for reading only and display, in html, all of the pending orders for the day. The look and feel of this page should follow the store's theme. Though this page would be used only by administrators of the site, we will not lock it down. For now, assume it will be live for all to view. Please create a table to hold all of the pending orders. Each line of the order file could be a table row. You can keep this simple, no need to use explode() or list() if you don't want to. As well on this page, create a hyperlink to resetOrders.php (see below). If there are no pending orders, ensure there is a message to the user stating the fact.
6. Create another page called resetOrders.php. This page should reset the orders file (delete the file contents), give the user confirmation that the file has been cleared and give them a link/instructions on what to do next.
7. All pages should be accessible via links. So there should be some sort of menu. I DON'T need a link to process orders as that would be silly. Remember menus should go at the top of your pages.
8.Comments, Code Formatting, Submission Packaging (variable naming, page naming).
In: Computer Science
Given an integer named area which represents the area of a rectangle, write a function minPerimeter that calculates the minimum possible perimeter of the given rectangle, and prints the perimeter and the side lengths needed to achieve that minimum. The length of the sides of the rectangle are integer numbers. For example, given the integer area = 30, possible perimeters and side-lengths are: (1, 30), with a perimeter of 62 (2, 15), with a perimeter of 34 (3, 10), with a perimeter of 26 (5, 6), with a perimeter of 22 Thus, your function should print only the last line, since that is the minimum perimeter. Some example outputs: >>>minPerimeter(30) 22 where rectangle sides are 5 and 6. >>>minPerimeter(101) 204 where rectangle sides are 1 and 101. >>>minPerimeter(4564320) 8552 where rectangle sides are 2056 and 2220.
In: Computer Science
PYTHON!
Exercise 3 - Total Line length
Write a python function that will return the total length of line that passes through any number of provided points ( (x,y) ). The points should be passed as individual tuples or lists. The function should also have a parameter (True or False) to indicate whether the line should start from the origin, and that parameter should default to False. If True, the returned value should include the distance from the origin to the first point, otherwise start adding distances from the first point. So a function call could look something like this:
dist = lineLength((1,2), (2,3), (7,4), start=False)
Demonstrate it in your main program by calculating the length of
line going through the following 5 points (with and without the
origin option set to True):
(1,1), (-2,4), (-3,-2), (2,-1), (1,1)
PreviousNext
In: Computer Science
Task 1. Consider the following scenarios
Last week we discussed in the class, the threats posed by each of the above scenarios and explain what its effect may be if a web application is compromised. One of the software strategies to cover the emergent security threat to an application is to build abuse cases. The result I expect is a report which integrates the software development lifecycle with security in every step of it for the abuse case described for any one of the scenarios mentioned above. You can also attempt the exercise for any scenario which interests you . (5 points)
In: Computer Science
In: Computer Science
In C++, dealing with Binary Search trees. Implement search, insert, removeLeaf, and removeNodeWithOneChild methods in BST.h. BST.h code below. CPP code also provided for reference, nothing to be changed on cpp code.
#include #include "BSTNode.h" using namespace std; #ifndef BST_H_ #define BST_H_ class BST { public: BSTNode *root; int size; BST() { root = NULL; size = 0; } ~BST() { if (root != NULL) deepClean(root); } BSTNode *search(int key) { // complete this method } BSTNode *insert(int val) { // complete this method } bool remove(int val) { // complete this method } private: void removeLeaf(BSTNode *leaf) { // complete this method } void removeNodeWithOneChild(BSTNode *node) { // complete this method } static BSTNode *findMin(BSTNode *node) { if (NULL == node) return NULL; while (node->left != NULL) { node = node->left; } return node; } static BSTNode *findMax(BSTNode *node) { if (NULL == node) return NULL; while (node->right != NULL) { node = node->right; } return node; } void print(BSTNode *node) { if (NULL != node) { node->toString(); cout << " "; print(node->left); print(node->right); } } static int getHeight(BSTNode *node) { if (node == NULL) return 0; else return 1 + max(getHeight(node->left), getHeight(node->right)); } static void deepClean(BSTNode *node) { if (node->left != NULL) deepClean(node->left); if (node->right != NULL) deepClean(node->right); delete node; } public: int getTreeHeight() { return getHeight(root); } void print() { print(root); } int getSize() { return size; } }; #endif
testCorrectness.cpp #include #include #include #include #include #include #include #include "BST.h" #include "Hashing.h" using namespace std; int arrayIns[] = { 11, 12, 15, 17, 12, 19, 4, 5, 11, 19, 20, 32, 77, 65, 66, 88, 99, 10, 8, 19, 15, 66, 11, 19 }; const int numInsert = sizeof(arrayIns) / sizeof(int); int searchArray[] = { 29, 3, 19, 27, 12, 34, 4, 5, 19, 20, 32, 45, 37, 25, 99, 25, 8, 24, 12, 16 }; const int numSearch = sizeof(searchArray) / sizeof(int); int deleteArray[] = { 16, 12, 15, 5, 17, 19, 4, 5, 19, 20, 32, 17, 19, 39, 99, 10, 8, 19, 15, 21 }; const int numDelete = sizeof(deleteArray) / sizeof(int); const int cleanUp[] = { 11, 77, 65, 66, 88 }; const int numCleanUp = sizeof(cleanUp) / sizeof(int); const int TABLE_SIZE = 7; void printArray(int *A, int len) { if (0 == len) cout << "[]"; else { cout << "["; for (int i = 0; i < len - 1; i++) { if (A[i] == INT_MAX) cout << "infty, "; else cout << A[i] << ", "; } if (A[len - 1] == INT_MAX) cout << "infty]"; else cout << A[len - 1] << "]"; cout << endl; } } void printList(list &A) { if (0 == A.size()) cout << "[]" << endl; else { list::iterator it; cout << "["; for (it = A.begin(); next(it) != A.end(); ++it) cout << *it << ", "; cout << *it << "]"; cout << endl; } } void printList(list *A) { if (0 == A->size()) cout << "[]" << endl; else { list::iterator it; cout << "["; for (it = A->begin(); next(it) != A->end(); ++it) cout << *it << ", "; cout << *it << "]"; cout << endl; } } //HASHING ------------------------------------------- Hashing *testHashing() { cout << "****************** Test Hashing Correctness ******************" << endl << endl; Hashing *hChain = new Hashing(TABLE_SIZE); cout << "Inserting the following numbers: "; printArray(arrayIns, numInsert); for (int i = 0; i < numInsert; i++) { hChain->insert(arrayIns[i]); } cout << endl << "*** Hash Table Structure (after insertion) ***" << endl; int size = 0; for (int i = 0; i < TABLE_SIZE; i++) { cout << "Slot " << i << ": "; printList(hChain->getList(i)); size += hChain->getList(i)->size(); } cout << endl << "Size of hash table: " << size << endl; cout << "\n*** Searching Hash Table ***" << endl; list foundList; list notFoundList; for (int i = 0; i < numSearch; i++) { int val = searchArray[i]; bool found = hChain->search(val); if (found) foundList.push_back(val); else notFoundList.push_back(val); } cout << "Found: "; printList(foundList); cout << "Did not find: "; printList(notFoundList); cout << endl << "*** Deleting Hash Table ***" << endl; list deleteList; list deleteNotFoundList; for (int i = 0; i < numDelete; i++) { int val = deleteArray[i]; bool deleted = hChain->remove(val); if (deleted) deleteList.push_back(val); else deleteNotFoundList.push_back(val); } cout << "Deleted: "; printList(deleteList); cout << "Did not find: "; printList(deleteNotFoundList); cout << endl << "*** Hash Table Structure (after deletion) ***" << endl; size = 0; for (int i = 0; i < TABLE_SIZE; i++) { cout << "Slot " << i << ": "; printList(hChain->getList(i)); size += hChain->getList(i)->size(); } cout << endl << "Size of hash table: " << size << endl; return hChain; } //BST BST *testBST() { cout << "\n****************** Test BST Correctness ******************" << endl << endl; BST *bst = new BST(); cout << "Inserting the following numbers: "; printArray(arrayIns, numInsert); for (int i = 0; i < numInsert; i++) { bst->insert(arrayIns[i]); } cout << endl << "*** BST Structure (after insertion) ***" << endl; bst->print(); cout << endl << endl << "Size of BST: " << bst->getSize() << endl; cout << "\n*** Searching BST ***" << endl; list foundList; list notFoundList; for (int i = 0; i < numSearch; i++) { int val = searchArray[i]; if (bst->search(val) != NULL) foundList.push_back(val); else notFoundList.push_back(val); } cout << "Found: "; printList(foundList); cout << "Did not find: "; printList(notFoundList); cout << endl << "*** Deleting BST ***" << endl; list deleteList; list deleteNotFoundList; for (int i = 0; i < numDelete; i++) { int val = deleteArray[i]; bool deleted = bst->remove(val); if (deleted) deleteList.push_back(val); else deleteNotFoundList.push_back(val); } cout << "Deleted: "; printList(deleteList); cout << "Did not find: "; printList(deleteNotFoundList); cout << endl << "*** BST Structure (after deletion) ***" << endl; bst->print(); cout << endl << endl << "Size of BST: " << bst->getSize() << endl; return bst; } static void cleanTest(Hashing *hashing, BST *bst) { cout << "\n****************** Clean up ******************" << endl; for (int i = 0; i < numCleanUp; i++) { hashing->remove(cleanUp[i]); bst->remove(cleanUp[i]); } int size = 0; for (int i = 0; i < TABLE_SIZE; i++) size += hashing->getList(i)->size(); cout << "\nSize of hash table: " << size << endl; cout << "Size of BST: " << bst->getSize(); delete hashing; delete bst; } int main() { cleanTest(testHashing(), testBST()); return 0; }
BSTnode.h
#include <iostream> using namespace std; #ifndef BSTNODE_H_ #define BSTNODE_H_ class BSTNode { public: int value; BSTNode *left, *right, *parent; BSTNode(int val) { // each node is inserted as a leaf value = val; left = NULL; right = NULL; parent = NULL; } void toString() { if (parent == NULL) cout << "<" << value << ", null>"; else cout << "<" << value << ", " << parent->value << ">"; } }; #endif
In: Computer Science