COMP2140 Archives - Mantutor https://mantutor.com/product-category/comp2140/feed/ Programming Help · Debugging · Full-Stack Learning Sun, 05 Feb 2023 09:34:19 +0000 en-US hourly 1 https://i0.wp.com/mantutor.com/wp-content/uploads/2022/02/cropped-mantutor2.png?fit=32%2C32&ssl=1 COMP2140 Archives - Mantutor https://mantutor.com/product-category/comp2140/feed/ 32 32 182416984 COMP2140 – Priority Queues, Heaps & Graphs – Assignment 5 – https://mantutor.com/product/comp2140-priority-queues-heaps-graphs-assignment-5-solved/ Sun, 05 Feb 2023 09:34:19 +0000 https://mantutor.com/?post_type=product&p=91229 Question 1: Simulating a Hospital Emergency Room [17 marks] This question can be done after Week 11. You will implement a priority queue and use it to simulate a hospital emergency room.  Input will be a list of people arriving at the ER, read from a txt file (described below).  Output will be a list […]

The post COMP2140 – Priority Queues, Heaps & Graphs – Assignment 5 – appeared first on Mantutor.

]]>
Question 1: Simulating a Hospital Emergency Room [17 marks]

This question can be done after Week 11.

You will implement a priority queue and use it to simulate a hospital emergency room.  Input will be a list of people arriving at the ER, read from a txt file (described below).  Output will be a list of events in the ER, where each event is either (i) a patient arriving at the hospital, or (ii) the doctor completing a treatment and becoming available to treat another patient, or (iii) a patient being called in to see the doctor.

 

The Patient Class

Create a Patient class as follows:

  • Each patient will have a unique patient number (integer). For the emergency room simulation, the patients will be given a patient number in the order they arrive at the emergency room, beginning with 1.
  • Each patient will have an urgency (an integer between 1 and 10), where 1 is low priority (the least urgent cases) and 10 is high priority (the most urgent cases).
  • Each patient will have a treatment time (an integer representing a number of minutes). This represents the amount of time that the doctor will be occupied treating that patient.
  • Include public methods to get the patient number, urgency, and treatment time.
  • Write a toString method that returns a String containing the Patient information (and use it while debugging). Depending on the desired format of the information, methods outside the Patient class that need to print patient information could use the toString method, or use the get methods to retrieve data to be included in output.

 

The Priority Queue Class

You will use a priority queue of patients to determine the order that patients are seen by the doctor.  Before writing the code to simulate the emergency room, you should implement the priority queue as below.  Remember to test the priority queue as you develop it.

  • Your priority queue must be implemented using a heap of Patients.
  • The public methods for your priority queue will be insert (add a new item to the queue), deleteMax (remove the highest priority item from the priority queue), peek (peek at the highest priority item in the priority queue), and isEmpty.
  • The highest priority patients should be located at the top of the heap (front of the priority queue).
  • The isEmpty method will return true if the queue contains no items and false otherwise.
  • The insert method will insert a patient into the priority queue, so that the highest priority patient is at the front of the queue (i.e. you will pass insert a Patient object).
  • The deleteMax method will return the patient at the front of the priority queue (i.e. deleteMax will return a Patient object), and will remove that patient from the queue.
  • The peek method will return the patient at the front of the priority queue, but will leave that patient in the queue.

 

The Emergency Room Simulation

Simulate an emergency room with one doctor.  As patients arrive, they are placed in a priority queue according to the urgency of their case.  When the doctor is available (e.g. when one treatment ends), the next patient in the queue will be called in.

  • Assume that the input file is named txt and stored in the same directory as your .java file. The input file contains a list of patients, one per line.  Each line contains the arrival time, the urgency, and the required time with the doctor.  The integers are separated by a single space. See the sample input below.
  • Use a “clock” that starts at 0 when the simulation begins, and tracks the number of minutes that have elapsed in the simulation. For efficiency, the clock time should “jump” from one event to the next, and not run through all minutes one by one.
  • The arrivals (input) file is in order by time of arrival. You should read in only one arrival at a time, and only read the next arrival when the previous has been entered in the queue.
  • A patient should only be entered in the queue when the clock time is equal to the patient’s arrival time. That is, the queue should always represent the situation in the waiting room at the current time.
  • When the doctor is free, and there is a patient waiting, the patient at the front of the priority queue will be called in for treatment.
  • Print a statement for each event (when a patient arrives at the hospital, when a patient is called in to see the doctor, when the doctor finishes treating a patient and becomes available). Use a format similar to the sample output below.
  • The output must be ordered by the event time, but might not be exactly as below. For example, depending on your implementation, you might have an arrival printed before or after a treatment starting at the same time.

 

Sample Program Input

2 4 15 5 3 5

7 9 12

14 5 9

131 2 5

138 3 10

 

 

 

Sample Program Output

Doctor is available at time = 0

Patient 1 arrived at time = 2 with urgency = 4 and treatment time = 15.

Doctor is available at time = 2

Patient 1 in for treatment at time = 2 with urgency = 4 and treatment time = 15.

Patient 2 arrived at time = 5 with urgency = 3 and treatment time = 5.

Patient 3 arrived at time = 7 with urgency = 9 and treatment time = 12.

Patient 4 arrived at time = 14 with urgency = 5 and treatment time = 9.

Doctor is available at time = 17

Patient 3 in for treatment at time = 17 with urgency = 9 and treatment time = 12.

Doctor is available at time = 29

Patient 4 in for treatment at time = 29 with urgency = 5 and treatment time = 9.

Doctor is available at time = 38

Patient 2 in for treatment at time = 38 with urgency = 3 and treatment time = 5.

Doctor is available at time = 43

Patient 5 arrived at time = 131 with urgency = 2 and treatment time = 5.

Doctor is available at time = 131

Patient 5 in for treatment at time = 131 with urgency = 2 and treatment time = 5.

Doctor is available at time = 136

Patient 6 arrived at time = 138 with urgency = 3 and treatment time = 10.

Doctor is available at time = 138

Patient 6 in for treatment at time = 138 with urgency = 3 and treatment time = 10.

Doctor is available at time = 148                                      

Question 2: Graphs [24 marks]

This question requires material from Week 12.

For EACH of the two graphs given below, complete the following four items. No code is required for this question.

  • Draw the graph corresponding to the given adjacency matrix (graph 1) / adjacency list (graph 2). These graphs have more nodes and edges than many of the examples in the course materials. There will be many edges and it will not be possible to draw a pretty graph. Do your best to make it legible.
  • Complete a depth-first traversal of the graph, beginning at vertex B. Format your answer in a table containing (i) the event (visit/pop), (ii) the stack contents, and (iii) the current depth-first list of nodes, as in the depth-first traversal example in Week 12. Once the traversal is complete, write out the depth-first list of nodes, in the order they were visited.
  • Complete a breadth-first traversal of the graph, beginning at vertex L. Format your answer in a table containing (i) the event (visit/remove), (ii) the queue contents, (iii) the current vertex, and (iv) the current breadth-first list of nodes, as in the breadth-first traversal example in Week 12. Once the traversal is complete, write out the breadth-first list of nodes, in the order they were visited.
  • Use Dijkstra’s shortest path algorithm to find the lowest-cost paths from vertex H to all other vertices. Submit a table showing the details of each step of the algorithm. At each step, show the current least cost distance to each vertex, the previous vertex on that least cost path, and mark completed paths with an asterisk. That is, format your answer in a table, as in the Dijkstra’s algorithm example in Week 12. Once the algorithm is complete, write out the lowest-cost path from H to each other vertex (i.e. list the vertices along each path and state the total cost of each path).

 

Caution: Be aware of how the graphs would be stored in a computer. Use the adjacency matrix or adjacency list to determine the order that nodes are visited. Remember that a computer will process the vertices in a very systematic way.

 

You may use Photoshop, Powerpoint, or other software to draw your graphs and tables, or you may draw your graphs and tables by hand on paper and scan/photograph your solution.  Whatever method you choose, convert your solution into a pdf file.  Each graph should occupy a full page.  Your answer (including all vertices, lines, and labels) must be legible after conversion to pdf, and be well-organized so that it can be easily marked.

Your pdf file must be named <your last name><your first name>A5Q2.pdf (e.g. SmithJohnA5Q2.pdf). Submit your pdf file to the Assignment 5 dropbox in UM Learn, along with your solution to question 1.

 

 

Graph 1:  This graph is stored in an adjacency matrix.

     to from A B C D E F G H I J K L
A 0 40 20 20 30 80 0 0 0 0 70 0
B 0 0 0 20 40 0 0 0 0 0 5 0
C 0 0 0 0 0 30 0 50 0 0 30 30
D 0 0 10 0 0 0 0 0 0 30 50 0
E 0 0 0 0 0 0 40 0 0 20 0 20
F 10 0 0 0 0 0 0 30 0 0 0 60
G 0 0 30 90 0 60 0 0 0 0 80 0
H 60 0 0 50 10 0 70 0 0 0 0 0
I 0 0 0 0 0 0 0 40 0 70 0 10
J 10 60 0 0 0 80 10 0 0 0 90 0
K 20 60 0 0 20 0 20 0 0 0 0 0
L 0 70 60 0 0 90 0 0 0 0 0 0

 

 

Graph 2:  This graph is stored in an adjacency list, where each list lists the vertices adjacent to a given vertex, and each entry in the list gives the adjacent vertex and the edge weight. (That is, the arrows below represent links in the linked lists, not edges in the graph.)

A: (E, 70) → (G, 40) → (H, 60) → (K, 30)

B: (D, 70) → (E, 50) → (I, 20) → (L, 40)

C: (F, 40) → (G, 20) → (H, 70) → (K, 10) → (L, 50)

D: (B, 70) → (G, 50) → (H, 90) → (I, 30) → (J, 60) → (L, 10)

E: (A, 70) → (B, 50) → (I, 10) → (L, 30)

F: (C, 40) → (G, 60) → (I, 80) → (J, 50) → (L, 30)

G: (A, 40) → (C, 20) → (D, 50) → (F, 60) → (I, 10) → (K, 30)

H: (A, 60) → (C, 70) → (D, 90) → (J, 20)

I: (B, 20) → (D, 30) → (E, 10) → (F, 80) → (G, 10) → (K, 60)

J: (D, 60) → (F, 50) → (H, 20) → (K, 80)

K: (A, 30) → (C, 10) → (G, 30) → (I, 60) → (J, 80)

L: (B, 40) → (C, 50) → (D, 10) → (E, 30) → (F, 30)

The post COMP2140 – Priority Queues, Heaps & Graphs – Assignment 5 – appeared first on Mantutor.

]]>
91229
COMP2140 – Binary Trees & 2-3-4 Trees – Assignment 4 – https://mantutor.com/product/comp2140-binary-trees-2-3-4-trees-assignment-4-solved/ Sun, 05 Feb 2023 09:32:01 +0000 https://mantutor.com/?post_type=product&p=91228 Question 1: Expression Trees [30 marks] This question can be done after Week 8 of the course but reviewing Week 9 before beginning is recommended. Read through all of the instructions for question 1 before beginning. You will use an expression tree to store and manipulate algebraic expressions. Your expression tree will be constructed from […]

The post COMP2140 – Binary Trees & 2-3-4 Trees – Assignment 4 – appeared first on Mantutor.

]]>
Question 1: Expression Trees [30 marks]

This question can be done after Week 8 of the course but reviewing Week 9 before beginning is recommended.

Read through all of the instructions for question 1 before beginning.

You will use an expression tree to store and manipulate algebraic expressions. Your expression tree will be constructed from nodes, as described below.

Examples of expression trees are shown in the Week 8 class materials. Some additional examples of expression trees are

+                    *                      *

/ \                  / \                   /   \

A   –                A   ^                 +     –

/ \                  / \               / \   / \    B   C                B   +             A   B C   D

/ \

C   D

(A+(B-C))           (A*(B^(C+D)))        ((A+B)*(C-D))

 

One advantage of postfix and prefix notations is that parentheses are not needed to specify order of operations. In this question you will create expression trees from both postfix and prefix forms of algebraic expressions. You will also simplify the expression trees and print infix, postfix, and prefix versions of the expressions stored in the trees. Your program will read commands from a file and output the result of executing those commands.

 

Input

The input file will consist of one command per line, where the command will be one of the 6 options below. If additional information is needed, it will follow on the same line. Possible commands are:

  • COMMENT – A line beginning with “COMMENT” should be echoed to the console. No manipulation of the tree is required.
  • NEW – A line beginning with “NEW” will construct a new expression tree. Any existing tree will be discarded and replaced with the new tree. The expression that follows “NEW” will be either prefix or postfix notation. Your program should be able to determine which notation is used. All operands and operators will be separated by spaces, so that you may split the line read from file into tokens, where each token contains a String that will correspond to a node in the tree.

Output a single statement, “New tree constructed”, when a tree is successfully created. Please see the sections below on constructing expression trees for some hints on how to read in expressions and construct trees.

  • PRINTPREFIX – A line beginning with “PRINTPREFIX” will print the current tree using prefix notation. Similar to the prefix notation used when reading from the input file, separate all operands and operators with a space.
  • PRINTPOSTFIX – A line beginning with “PRINTPOSTFIX” will print the current tree using postfix notation. Similar to the postfix notation used when reading from the input file, separate all operands and operators with a space.
  • PRINTINFIX – A line beginning with “PRINTINFIX” will print the current tree using infix notation. Infix notation requires parentheses to indicate the order of operations, and you will print a fully parenthesized expression, where each operand-operator-operand is enclosed in parentheses. Examples of fully parenthesized expressions are ( ( 8 + 6 ) * ( 4 – 5 ) ) and ( ( ( B + 5 ) * 4 ) ^ 3 ).
  • SIMPLIFY – A line beginning with “SIMPLIFY” will simplify the current tree, following common arithmetic rules, and output the statement “Tree simplified” when complete. Traverse the tree and stop to consider each node containing an operator. (You need to determine which type of traversal is best to use.) Look at the subtree consisting of the operator node and its left and right subtrees, and simplify where possible. Some examples to get you started: o If both children of an operator are numeric values, perform the operation and replace that subtree with the result stored in a single node.
    • A * 1 = A. If the operator is * and one of the children is 1, replace the subtree with the other child.
    • A * 0 = 0. If the operator is * and one of the children is 0, replace the subtree with 0. o A ^ 1 = A. If the operator is ^ and the right child is 1, replace the subtree with the left child.

 

Nodes for Expression Trees

The nodes in the expression tree will have the ability to hold three types of information: operators, variables, or constants. Possible operators will be +, -, *, and ^. We will omit division so that we can deal only with integers.

The fields in your nodes should be:

  • A type that identifies the node as an operator, variable, or a number. Something similar to enum NodeType{OPERATOR, VARIABLE, NUMBER;} is appropriate.
  • A char that will store the operator for operator nodes. The only valid characters are

‘+’, ‘-‘, ‘*’, and ‘^’.

  • A String that will store the variable name for variable nodes.
  • An int that will store the value for numerical nodes.
  • Two Node references, that refer to the left child and the right child. For leaf nodes these will be null.

Note: Even though we will use ‘^’ as the symbol (e.g. x ^ y to represent xy), use the pow() method in your program. ^ in Java is a bitwise XOR.

The Expression Tree Class

Your expression tree class must have methods that allow it to carry out the expected commands. Recursion should be used when appropriate.

 

A Queue to store Nodes

You will need a queue of Nodes (i.e. a queue where each item stored in the queue is a Node) to aid in the construction of an expression tree from prefix notation.

You may choose the underlying implementation for your queue that you think is most appropriate (linked list or array). The implementation that you choose should be hidden from a user of the class. That is, the user will enqueue and dequeue Nodes, and will not know how they are managed inside the queue.

Your queue must have the following methods:

  • A constructor that creates an empty queue.
  • A boolean isEmpty() method that returns a boolean, indicating whether the queue is empty.
  • A boolean enqueue(Node toAdd) method that will insert the given Node into the queue. This method will return true if the enqueue is successful, and return false if the enqueue fails.
  • A Node dequeue() method that will dequeue and return the Node at the front of the queue. This method removes the returned Node from the queue. This method should return null if the user tries to dequeue from an empty queue.
  • A Node peek() (or front) method that returns the Node at the front of the queue. This method does not remove the returned Node from the queue. This method should return null if the user tries to peek at an empty queue.

 

A Stack to store Nodes

You will need a stack of Nodes (i.e. a stack where each item stored in the stack is a Node) to aid in the construction of an expression tree from postfix notation.

As for the queue class, you may choose the underlying implementation for your queue that you think is most appropriate (linked list or array). The implementation that you choose should be hidden from a user of the class. That is, the user will push and pop Nodes, and will not know how they are managed inside the stack.

Your stack must have the following methods:

  • A constructor that creates an empty stack.
  • A boolean isEmpty() method that returns a boolean, indicating whether the stack is empty.
  • A boolean push(Node toAdd) method that will insert the given Node into the stack. This method will return true if the push is successful, and return false if the push fails.
  • A Node pop() method that will pop and return the Node on the top of the stack. This method removes the returned Node from the stack. This method should return null if the user tries to pop from an empty stack.
  • A Node peek() (or top) method that returns the Node on the top of the stack. This method does not remove the returned Node from the stack. This method should return null if the user tries to peek at an empty stack.

 

Constructing An Expression Tree From Postfix Notation

Constructing an expression tree from postfix notation is similar to evaluating a postfix expression (discussed in Week 6, slides #142-157). However, instead of storing operands on the stack, you store entire subtrees. Read along the postfix expression from left to right, as we did when evaluating a postfix expression. When you encounter an operand (a number or a variable name):

  • Make a Node that holds the operand.
  • Push that Node onto the stack.

When you encounter an operator:

  • Pop two operands/subtrees (B and C) off the stack.
  • Create a new Node (A) that holds the operator.
  • Attach B (the first node popped) as the right child of A.
  • Attach C (the second node popped) as the left child of A.
  • Push A onto the stack. Note that this effectively pushes the entire subtree onto the stack, because the stack holds node A, and A is linked to B and C.

When you’re done processing the postfix expression, pop the one remaining item off the stack, which will be the root node of the tree that depicts the entire postfix expression.

Hint: Before writing any code, run through this algorithm on paper for a few examples.  For example, the postfix expression DEF+* should produce the tree for the infix expression D*(E+F).

 

Constructing An Expression Tree From Prefix Notation

To construct an expression tree from prefix notation, make use of a queue of nodes to temporarily store subtrees as you build the full tree.  Begin by reading the prefix expression from left to right and placing the entire expression into the queue. That is, for each operand or operator, create a node containing that token and put it into the queue.  Then, until the queue contains only a single item, remove the item at the front of the queue:

  • If the item is an operand or an operator that already has children, enqueue it again at the back/end of the queue without any modification.
  • If the item is an operator without children, examine the next two items in the queue.
    • If those two items are each either an operand or operator with children, remove them from the queue.
      • Set the first item removed as the left child of the operator.
      • Set the second item removed as the right child of the operator.
      • Enqueue the operator again at the back/end of the queue (it is now linked to two children).
    • If they are not both operands or operators with children, do not remove them from the queue (you’ll process them on the next iterations of the loop), and enqueue the operator (without children) again at the back/end of the queue.

Hint 1: Note that while operator nodes should always have two non-null children in a valid tree, you will sometimes want to queue operator nodes temporarily without children while building the tree.

Hint 2: Notice that we want to be able to peek at (examine) two items in the queue without dequeuing them.  For this assignment (even though it is not a real queue operation), add a peek2 method to your Queue class. This method should return (without removing) the second item in the queue (and return null if a second item does not exist).

Hint 3: Before writing any code, run through this algorithm on paper for a few examples.  For example, the prefix expression *D+EF should produce the tree for the infix expression D*(E+F).

 

Application (Main) Class – named <your last name><your first name>A4Q1

Your application class should process commands from an input file, as described above, until the end of the file. You may assume that the data file will be named A4Q1input.txt and will be located in the same directory as your .java file.  (A file is not provided – you should create your own tests as you write your program.)

 

Sample Program Input

COMMENT Starting tests…

NEW C 3 + 5 4 – *

PRINTINFIX SIMPLIFY

PRINTINFIX

PRINTPOSTFIX

PRINTPREFIX

COMMENT Second Test

NEW firstVble 1 ^ secondVble 0 * firstVble secondVble + 5 * – +

PRINTINFIX SIMPLIFY

PRINTINFIX

COMMENT End of tests.

Sample Program Output

Starting tests…

New tree constructed

( ( C + 3 ) * ( 5 – 4 ) )

Tree simplified

( C + 3 )

C 3 +

+ C 3

Second Test

New tree constructed

( ( firstVble ^ 1 ) + ( ( secondVble * 0 ) – ( ( firstVble + secondVble ) * 5 ) ) )

Tree simplified

( firstVble – ( ( firstVble + secondVble ) * 5 ) ) End of tests.

 

[Programming Standards are worth 8 marks]

 

 

Question 2: 2-3-4 Trees [12 marks]

This question requires material from Week 10.

Similar to the examples seen in Week 10 for 2-3 and 2-3-4 trees, you will redraw a 2-3-4 tree after each insertion listed below.  No code is required for this question.

In this question we are looking at the type of 2-3-4 tree that contains data in both interior and leaf nodes. Recall that 2-3-4 trees contain nodes with up to 3 data items/4 children per node.

Begin with an empty 2-3-4 tree. Insert the values listed below, in the order listed, re-drawing the entire tree after EACH insertion. (You may also draw an intermediate stage when node splitting is required, if you find that helpful.) Use a top-down 2-3-4 tree, where full nodes are split on the way down to the insertion point.

You may use Photoshop, Powerpoint, or other software to draw your trees, or you may draw your trees by hand on paper and scan or photograph your solution. Whatever method you choose, convert your solution into a pdf file. Your answer must be legible after conversion to pdf, and be well-organized so that it can be easily marked.

  1. Begin with an empty 2-3-4 tree.
  2. Insert 28. 3. Insert 15. 4. Insert 22. 5. Insert 24. 6. Insert 41. 7. Insert 33. 8. Insert 31. 9. Insert 36. 10. Insert 25. 11. Insert 44. 12. Insert 42. 13. Insert 48. 14. Insert 40. 15. Insert 37. 16. Insert 39.
  3. Insert 47.

Your pdf file must be named <your last name><your first name>A4Q2.pdf (e.g. SmithJohnA4Q2.pdf). Submit your pdf file to the Assignment 4 submission folder in UM Learn, along with your solution to question 1.

The post COMP2140 – Binary Trees & 2-3-4 Trees – Assignment 4 – appeared first on Mantutor.

]]>
91228
COMP2140 – Stacks & Queues, & Hashing – Assignment 3 – https://mantutor.com/product/comp2140-stacks-queues-hashing-assignment-3-solved/ Sun, 05 Feb 2023 09:28:39 +0000 https://mantutor.com/?post_type=product&p=91230 Question 1: Find a Path Through a Maze [25 marks] This question can be done after Week 6 of the course. In this question you will read a maze from a file, and attempt to find a path through the maze twice. One attempt will use a stack to store the positions visited in the […]

The post COMP2140 – Stacks & Queues, & Hashing – Assignment 3 – appeared first on Mantutor.

]]>
Question 1: Find a Path Through a Maze [25 marks]

This question can be done after Week 6 of the course.

In this question you will read a maze from a file, and attempt to find a path through the maze twice. One attempt will use a stack to store the positions visited in the maze, and the other attempt will use a queue to store the positions visited in the maze.  (Later in the term we will talk about depth-first and breadth-first searches.  That is essentially what you will be doing here.)

 

Maze Representation

Each position in the maze will be one of the following:

  • a path (an open space you can walk on), represented by . (period)
  • a wall (a blocked space that you can not step on), represented by # (hash mark) a starting point, represented by S
  • a finish line, represented by F

If a path has been found and the maze is displayed, the path from start to finish should be marked with * (asterisk).

 

The input file will contain one maze. You can assume that the input file does not contain any errors. The first line in the file will contain the number of rows, followed by a space, followed by the number of columns. The rest of the file will contain the text representation of the maze, using the symbols listed above (. and # and S and F). Please see the sample input below.

 

Approach to Path Finding

You will implement two searches, one using a stack and one using a queue.  For each search algorithm, you will maintain the data structure (stack/queue) containing the Positions left to explore, while updating the Maze object.  Think carefully about keeping track of which positions in the maze have been visited, and where they have been visited from.

The following pseudocode describes both searches:

Add start position to data structure    Mark start position as visited    while (data structure is not empty):

current = position removed from data structure       if (current is the finish):

exit search       for (each neighbour of current that is an unvisited path):

Mark neighbour as visited

Record neighbour as visited from current

Add neighbour to the data structure

When this algorithm is complete, current will be the finish position if the search found a path, but will be some other position if the search failed. The path found will be a path, not necessarily the shortest path. If the search succeeded, you can reconstruct the path by checking from which position the finish was visited, and then checking from which position that position was visited, and so on, until you reach the start.

 

Your solution must include the following classes.  It is strongly suggested that you write one class at a time, and test each thoroughly before moving on to the next class.  You will have a very difficult time debugging your stack and queue classes if you try to do so while solving a maze.

 

Position Class

The Position class represents one location in the maze (i.e. a particular row and column, where the leftmost top position in the maze is row 0, column 0).  It stores information about that position, including whether it is a path or a wall, and whether it is the start/origin or finish/destination.  The fields in one Position object should be:

  • The row number.
  • The column number.
  • A type that identifies the type of square (start, finish, path, wall). Something similar to enum SquareType{START, FINISH, PATH, WALL;} is appropriate. (See the section below on enumerated types.)
  • A boolean to indicate whether this position has been visited (so that a search does not get stuck in a cycle).
  • A reference to the previous position on the path (or null if this position is not on the path).

The Position class should have a constructor that accepts a row, column, and type for a location. The constructor should set the other fields to default values.

You will also need methods that return String representations of the position, to use when displaying the maze or listing the path through the maze.  One method should return the appropriate symbol (e.g. “#” for a wall), and the other should return the coordinates in the format (2, 3).

 

Stack & Queue Classes

You will need a Stack that stores Positions, and a Queue that stores Positions.  One of the stack or queue should be implemented using an array implementation, and the other should be implemented using a linked list implementation.  The Stack class should have the standard push, pop, top, and isEmpty methods. The Queue class should have the standard enqueue, dequeue, front, and isEmpty methods. You may also find toString/print methods handy for debugging (if you write them, leave them in the code that you submit).

The constructors for Stack and Queue when implemented using an array should accept a size.  Estimate the maximum number of Positions that might be stored by looking at the size of the maze.

 

Maze Class

The Maze will consist of a two-dimensional array of Positions (or, more specifically, references to Positions).

The Maze constructor should read the input file, create a 2D array of the appropriate size, and then fill the array.

The search methods should be in this class.  One method will use a stack to track the progress through the maze, and the other will use a queue.  They should be otherwise similar.

You will find that you need a number of short methods in this class. For example, where should the search start? Finish? You will need methods that return the start/finish Positions for the maze.

Because you are going to try two different searches for a path through the maze, write a resetMaze() method, that will reset all Positions in the maze to unvisited.

 

Application (Main) Class

Your application class will create a Maze (reading from a file, where the filename is typed by the user).  It will attempt to solve the maze using a stack, and print the result (the maze and the list of positions along the path from start to finish, or a message that no path could be found).  The maze will be reset, and then the application class will attempt to solve the maze using a queue, and print that result.

 

Sample Input 1 (Note that this sample has walls along the edge)

4 7

#######

#…#S#

#F#…#

#######

 

Sample Output 1

Please enter the input file name (.txt only): sample1.txt

Processing sample1.txt…

The initial maze is:

#######

#…#S#

#F#…#

#######

The path found using a stack is:

#######

#***#S#

#F#***#

#######

Path from start to finish: (1, 5) (2, 5) (2, 4) (2, 3) (1, 3) (1, 2)

(1, 1) (2, 1)

The path found using a queue is:

#######

#***#S#

#F#***#

#######

Path from start to finish: (1, 5) (2, 5) (2, 4) (2, 3) (1, 3) (1, 2)

(1, 1) (2, 1)

Processing terminated normally.

 

 

Sample Input 2 (A more general case, without walls along all edges)

6 9

##S…##.

…##.#..

.#..#.#.#

.##.#…#

..#.##.## #F…….

 

Sample Output 2

Please enter the input file name (.txt files only): sampleMaze3.txt

Processing sampleMaze3.txt…

The initial maze is:

##S…##.

…##.#..

.#..#.#.#

.##.#…#

..#.##.## #F…….

The path found using a stack is:

##S…##.

..*##.#..

.#**#.#.#

.##*#…#

..#*##.## #F**…..

Path from start to finish is: (0, 2) (1, 2) (2, 2) (2, 3) (3, 3) (4,

3) (5, 3) (5, 2) (5, 1) The path found using a queue is:

##S…##.

***##.#..

*#..#.#.#

*##.#…#

**#.##.## #F…….

Path from start to finish is: (0, 2) (1, 2) (1, 1) (1, 0) (2, 0) (3,

0) (4, 0) (4, 1) (5, 1)

Program terminated normally.

 

 

 

 

Enumerated Types

An enumerated type is basically a type that says any variable of that type is only allowed to have one of a predefined set of values.  They are useful when you want to limit the possible values for something.

You define the type outside of any classes so that it applies globally. If you haven’t seen enumerated types before, here are a couple of links.

https://www.w3schools.in/javatutorial/enumeration/

https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Once you have defined the type, you can use it in the maze to test the type of the current square.  For example, if your enumerated type is

enum SquareType{     START,

FINISH,

PATH,

WALL;

} and a Position has a field

public SquareType typeOfSquare;

then you would set the type using statements such as

typeOfSquare = SquareType.PATH; //set this position to be a PATH

and can then test the type with statements such as

if (current.typeOfSquare == SquareType.PATH){

…do processing for a path…

}

else if (current.typeOfSquare == SquareType.WALL){

…do processing for a wall… }

(where current is a reference to a Position object).

Enumerated types in Java can have their own methods.  You may write a toString method for this Type if you choose, but it is not required.

 

 

Question 2: Dictionary Implementations [25 marks]

This question requires material from Week 7.

In this question you will create three implementations of a dictionary, and will compare the time to fill and search the dictionaries.  The first dictionary implementation will use an ordered array to store the contents of the dictionary.  The second and third implementations will use a hash table to store the contents of the dictionary.  The second dictionary will use open addressing, with double hashing to resolve collisions.  The third will use separate chaining.  Details specific to each table are listed in separate sections below.

 

The Application (Main) Class

  • The application class is provided for you. The only change you should make is to rename this class to include your name.
  • Look at how the dictionaries are created, filled, and searched in this class. For each dictionary, you must implement methods with names and parameters such that they work with this class.
  • txt (from http://www.gutenberg.org/ebooks/1400) will be used to build the dictionaries, with the goal of each dictionary storing all words that appear in this file.
    • Place a copy of this file in your working directory. o The application class builds the dictionaries by processing this file one line at a time, and building a dictionary as it goes. Each line is split into tokens, and each token is added to the dictionary. The dictionary insert methods should prevent duplicates – see below. Punctuation is stripped and only letters and apostrophes are kept. Due to the nature of the input file, not everything added to the dictionary will be a real word. Do not worry about this. To prevent multiple versions of the same word, you should convert to lower case as words are inserted in the dictionary (e.g. insert “Hello” as “hello”).
  • Notice that initially an empty dictionary of each type is created by passing an initial size of 100 to each constructor. Hash table sizes should be prime numbers and the constructors should adjust the initial size appropriately – see the sections below for details.
  • The output will include the size of each dictionary. These should all be equal because the input file is processed in an identical manner for each dictionary.
  • txt contains a list of words that will be searched for in the dictionaries.
    • Place a copy of this file in your working directory.
    • The output includes the number of words found. That number should be the same for each dictionary.

 

 

The Dictionary Classes

Your dictionary classes must be named DictionaryOrdered, DictionaryOpen, and DictionaryChain. Each dictionary class must have the following public methods.  Use additional (private) helper methods as appropriate.

  • A constructor that accepts an integer indicating the initial size of the dictionary. That is, public DictionaryOrdered(int size) for the dictionary using an ordered array, public DictionaryOpen(int size) for the dictionary using open addressing, and public DictionaryChain(int size) for the dictionary using separate chaining. See the instructions for each dictionary below re: initial size.
  • public int getSize(): Return the number of words in the dictionary.
  • public void insert(String newWord): Insert the given word into the dictionary. If a word already exists in the dictionary do not add it. All entries in the dictionary should be unique.
  • public boolean search(String wordToFind): Return true if the word is in the dictionary, false otherwise.

Keep the implementation details hidden from the user of the dictionary classes.  The main class accesses the dictionary contents ONLY via the above public methods.

It is common when working in a team on a large software projects to specify the public methods that a class will have, and the task that each method will accomplish.  It is then possible for different programmers to work on different classes and the classes to work together as expected when all programmers have finished. You must follow this procedure and implement the dictionary classes and methods as specified. Instance variables and helper methods should be private, and unreachable from your main class.

 

Details Specific to the Dictionary using an Ordered Array

  • The constructor for the dictionary class accepts an initial size from the user. This should be the size of the initial array.
  • When inserting words, if the dictionary is full, double the size of the array. There should never be a case where someone tries to insert a word and the insertion fails.
  • The search method should use a (non-recursive) binary search to search the ordered array. Use a non-recursive search to avoid timing the overhead associated with recursive calls.

 

Details Specific to the Dictionary using Open Addressing

  • The constructor for the dictionary class accepts an initial size from the user. However, the hash table size should always be a prime number. Find the first prime number larger than the requested array size, and use that prime number as the size of your hash table.
    • To find the prime number, start with the requested array size, test whether that number is prime, if not increment by 1 and test again, until you find a number that is prime.
    • To test if a given number (n) is prime:

starting with j=2, and as long as j*j <= n    if n % j == 0, n is not prime

  • Use Horner’s method (with a = 27) as your primary hash function.

o To convert characters to integers, since we are dealing with lowercase letters, cast a char to an int and subtract 96 (ASCII for a is 97, meaning that a would end up as 1, b as 2, c as 3, etc.). o If there happen to be any non-alphabetical characters left in the “words” (e.g. apostrophe), ignore them. That is, when computing the hash value, only include characters with ASCII values from 97 (a) to 122 (z).

  • You will resolve collisions using double hashing. For the secondary hash function, use stepSize = constant – (sum_of_characters % constant). As above, subtract

96 to map a to z into the range 1 to 26, and include only letters in the sum of characters. The constant should be prime and smaller than the array size.  In this assignment, use constant = 41.

  • When inserting words, if the hash table is more than 60% full, enlarge the array and rehash all the words currently in the dictionary, transferring the contents to the larger array. To determine the size of the new array, find the first prime number larger than double the current array size.

 

Details Specific to the Dictionary using Separate Chaining

  • You will need a linked list class and will store a linked list at each location in your hash array. Your linked lists do not need to be ordered.
  • Similar to the open addressing implementation, find the first prime number larger than the requested array size, and use that prime number as the size of the hash array.
  • Use Horner’s method (as above) as your hash function, where the sum of characters again uses the method of subtracting 96 from the char value to obtain a number between 1 and 26 for each letter.
  • Enlarge the hash table when the load factor exceeds 2. That is, enlarge the hash array when the number of words stored in the table is more than twice the size of the hash array. (Recall that the hash array is the array of chains/linked lists.)

[Programming Standards are worth 8 marks]

The post COMP2140 – Stacks & Queues, & Hashing – Assignment 3 – appeared first on Mantutor.

]]>
91230
COMP2140 – Sorting & Linked Lists – Sorting & Linked Lists – https://mantutor.com/product/comp2140-sorting-linked-lists-sorting-linked-lists-solved/ Sun, 05 Feb 2023 09:28:35 +0000 https://mantutor.com/?post_type=product&p=91227 Question 1: Time to Sort  [20 marks code + 5 marks report] This question can be done after Week 3 of the course. In this question you will complete a program that times the execution of seven sorting algorithms (insertion sort, bubble sort, selection sort, merge sort, quick sort, a hybrid quick sort (details below), […]

The post COMP2140 – Sorting & Linked Lists – Sorting & Linked Lists – appeared first on Mantutor.

]]>
Question 1: Time to Sort  [20 marks code + 5 marks report]

This question can be done after Week 3 of the course.

In this question you will complete a program that times the execution of seven sorting

algorithms (insertion sort, bubble sort, selection sort, merge sort, quick sort, a hybrid quick sort (details below), and a shell sort) and reports on the run time and whether the algorithms actually sorted the list.

The file A2Q1SortingTemplate.java contains your starting point for this assignment.  Do not change any of the provided code, except change the name of the application class to include your name.  Your job is to add the sorting methods, as described below, and any helper methods needed by the sorting methods. Each sort you implement should sort an array of numbers into ascending order. You are permitted to use and modify code provided in the class notes and textbook. You are not permitted to use code from any other sources.

 

A (non-recursive) Insertion Sort

Take the insertion sort algorithm from class and modify it so that it sorts only positions array[start] to (and including) array[end-1] in the array, not touching any other position in array. The header should be:

private static void insertionSort( int[] array, int start, int end)

Also write a public driver method with the header

public static void insertionSort( int[] array )

whose task is simply to call the private method, passing the correct values to the private method’s parameters so that it sorts the entire array.

These methods must not create arrays.

Note that the private method with also be used by the hybrid quick sort.

Hint: Test the private method’s ability to sort only part of the array without touching any other part of the array.  Many students get this wrong, and then can’t figure out why their hybrid quick sort doesn’t work.

 

A (non-recursive) Bubble Sort

Implement a bubble sort with the header

public static void bubbleSort( int[] array ) to sort the entire array, as reviewed in class and seen in COMP 1020.

 

A (non-recursive) Selection Sort

Implement a selection sort with header

public static void selectionSort( int[] array )

that sorts the entire array by locating the minimum item amongst the unsorted items at each step. This sort should make use of a helper method

private static int findMin( int[] array, int start, int end )

that will return the index of the minimum item stored in positions start to end-1 (inclusive) in the array.  This sort should also make use of the provided swap method.

 

 

 

 

 

A Recursive Merge Sort

Implement the algorithm as discussed in class, except that you should add a new base case: if there are just two items to be sorted, swap them if necessary.  There are three methods that you need to write:

  • The public driver mergeSort method: It simply calls the private recursive method with the array and the extra parameters (the start and end indices and the extra array temp) that the recursive method needs.
  • The private recursive helper mergeSort method: It does the recursive merge sort. It receives the array, indices start and end, and the temporary array as parameters. Its task is to merge sort positions start to end-1 (inclusive) in the array – and it must not touch any other positions in the array. This is the method that should have the new base case added to it.
  • The non-recursive helper merge method: It merges two sorted sublists (defined by three indices start, mid, and end) into one sorted list, using the extra array temp. Make sure that you use the indices to define the sublists in a way that is consistent with how sublists are defined by indices in all other parts of the code: from some index up to, but not including, some other index.

Reminder: Only the public driver method should create an array.  All the other methods used by merge sort must use the arrays and positions (indices) that they are passed in their parameters without creating any other arrays.

 

A Recursive Quick Sort

Implement the algorithm as discussed in class, except that you should add the base case: if there are just two items to be sorted, swap them if necessary. You need to write the following methods:

  • The public driver quickSort method: It simply calls the private recursive method, passing it the extra parameters (the start and end indices) the recursive method needs.
  • The private recursive helper quickSort method: It is the recursive quick sort method, which receives the array, and indices start and end as parameters. Its task is to quick sort positions start to end-1 (inclusive) in the array – and it must not touch any other positions in the array. This is the method that should have a base case added for two items.
  • The private non-recursive median-of-three method: It chooses a pivot from the items in positions start to end-1 (inclusive) in the array using the median-of-three method, and swaps the chosen pivot into position start in the array.
  • The private non-recursive partition method: It partitions the items in positions start to end-1 (inclusive) in the array using the chosen pivot (which it assumes is already in position start), and returns the final position of the pivot after the partition is complete. It should use one simple for-loop.

None of these methods should create an array.

A Hybrid Recursive Quick Sort that uses a Breakpoint

Use the header

private static void hybridQuickSort( int[] array, int start, int end )

This method is similar to the recursive quickSort algorithm above, except it has a different base case:

  • If array[start] to (and including) array[end-1] is fewer than BREAKPOINT items, then call the private insertionSort method to sort array[start] to (and including) array[end-1] (and not touch any other position in the array).

If array[start] to (and including) array[end-1] consists of at least BREAKPOINT items, then do the usual quick sort steps (choose a pivot using the median-of-three technique, partition the items using the chosen pivot, and finally recursively call hybridQuickSort twice to sort each of the smalls and the bigs).

Make sure the recursive calls in hybridQuickSort are to hybridQuickSort, not to quickSort.

Also write a public driver method with the header

public static void hybridQuickSort( int[] array )

Its task is to simply call the above private hybridQuickSort method, passing the correct values to the private method’s parameters so that it sorts the entire array.

None of the hybrid quick sort methods should create an array.

A (non-recursive) Shell Sort

Implement a shell sort with the header

public static void shellSort( int[] array )

that will perform an insertion sort on widely-spaced items, then less widely-spaced items, then even less widely-spaced items, etc., until it ends with a regular insertion sort that includes all items.  The shell sort should use Knuth’s sequence for the gap sequence, starting with the largest possible gap h that is smaller than the size of the array, as described in the week 3 lecture slides.

 

Report

In the comments at the end of your program, paste the output from one run of your program, and answer the following questions:

  1. Was insertion sort faster than selection sort? Why or why not?
  2. Was quick sort faster than insertion sort? Why or why not?
  3. Was hybrid quick sort faster than quick sort? Why or why not?
  4. Which sort(s) would you recommend to others, and why?
  5. Which sort(s) would you warn others against using, and why?

Question 2: Modelling a Train with a Linked List [25 marks]

This question requires material from Weeks 4 & 5.

In this question you will model a train with a linked list, where each node in the linked list will represent one car on the train.

  • Model the train with a doubly-linked list, where each node has a reference (pointer) to both the node ahead of it and the node behind it.
  • Your program should ask the user to enter the name of an input file.
  • Your program will process the input file, performing the requested operations as it goes. The input file will consist of lines of commands, with a command possibly followed by lines of data. See the input description below.  Echo each command to the console, perform the operation, and print a summary of the actions performed. Please see the sample output below.
  • You must create at least four classes:
    • a TrainCar class, which stores the information about one train car. The TrainCar class should store the type of cargo (a String), and the value of the cargo.
    • a Node class, which stores links to neighbouring nodes and one TrainCar object. o a Train class (the linked list class).
    • an application/main class (to process the input file).
  • The Train class constructor will create a train consisting of one car (an engine, where the type of cargo is set to “engine” and the value is set to $0).

 

Program Input

Possible commands in the input file are:

  • PICKUP [num]

num (an integer) indicates the number of train cars to be added to the train. Each car is listed separately on a following line (type of cargo followed by value, separated by a space; engines do not have a value).  Engines are always added at the front of the train.  Cars containing cargo are added at the end of the train.

  • PRINT

Print the entire train, including engines(s).  Print one line displaying the number of cars in the train and the total value of the cargo.  On a second line, print the train from front to back, listing the type of cargo in each car (the list of cars may wrap to multiple lines).

  • DROPLAST [num]

Remove the last num (an integer) cargo cars from the train.  Never drop engines.  If the number given is larger than the number of cargo cars on the train, print the number actually dropped.

  • DROPFIRST [num]

Remove the first num (an integer) cargo cars from the train.  That is, drop the first num cars after the engine(s).  If the number given is larger than the number of cargo cars on the train, print the number actually dropped.

  • DROP [type] [num]

Remove the first num (an integer) cars that contain the specified type (a String) of cargo.  If fewer than num cars of the specified type exist, print the number actually dropped.

 

Sample program input:

PICKUP 6 oil 40000 wheat 20000 lumber 30000 engine oil 45000 oil 60000 PRINT

DROPLAST 1

PRINT PICKUP 8 oil 50000 lumber 25000 wheat 25000 oil 30000 oil 45000 wheat 20000 lumber 20000 oil 60000 PRINT

DROP oil 4

PRINT

DROPFIRST 3 PRINT

 

Sample program output:

Processing command: PICKUP 6

1 engines and 5 cars added to train

Processing command: PRINT

Total number of engines: 2, Total number of cargo cars: 5, Total value of cargo:

$195000

The cars on the train are: engine – engine – oil – wheat – lumber – oil – oil

Processing command: DROPLAST 1

1 cars dropped from train

Processing command: PRINT

Total number of engines: 2, Total number of cargo cars: 4, Total value of cargo:

$135000

The cars on the train are: engine – engine – oil – wheat – lumber – oil

Processing command: PICKUP 8

0 engines and 8 cars added to train

Processing command: PRINT

Total number of engines: 2, Total number of cargo cars: 12, Total value of cargo:

$410000

The cars on the train are: engine – engine – oil – wheat – lumber – oil – oil – lumber – wheat – oil – oil – wheat – lumber – oil

Processing command: DROP oil 4

4 cars dropped from train

Processing command: PRINT

Total number of engines: 2, Total number of cargo cars: 8, Total value of cargo:

$245000

The cars on the train are: engine – engine – wheat – lumber – lumber – wheat – oil – wheat – lumber – oil

Processing command: DROPFIRST 3

3 cars dropped from train

Processing command: PRINT

Total number of engines: 2, Total number of cargo cars: 5, Total value of cargo:

$170000

The cars on the train are: engine – engine – wheat – oil – wheat – lumber – oil End of processing.

 

Q2 Additional Notes

  • You may assume that the input file does not contain any errors. All commands will be valid commands, and the format of each line in the file will be as shown above.
  • You may assume that the integer following the PICKUP command exactly matches the following number of lines listing the cargo in the cars that are to be added to the train.
    • You may assume that the cargo type will always be given as one word, without any spaces (e.g. “oil”, “cars”, “dieselfuel”, “sugarbeets”)
    • You may assume that if the cargo type is not “engine” the type will be followed by a number (the value of the cargo).
  • The DROPFIRST and DROPLAST commands should never drop engines. If a DROP command specifies “engine” as the cargo type, then you drop engines.
  • Use the above input as a starting point. The file “trainInput.txt” contains additional test input.
  • Place all classes for question 2 in the same .java file.

 

 

 

[Programming Standards are worth 8 marks]

 

The post COMP2140 – Sorting & Linked Lists – Sorting & Linked Lists – appeared first on Mantutor.

]]>
91227
COMP2140-Lab 6 Graphs https://mantutor.com/product/comp2140-lab-6-graphs-solved/ Mon, 21 Jun 2021 06:12:53 +0000 https://mantutor.com/?post_type=product&p=62431 To write code to compute the in-degree of every vertex and to print out the vertices visited in a depth-first traversal starting at Vertex 0, for an adjacency-list implementation of a directed graph. In-Degrees and a Depth-First Traversal Get a copy of GraphAL.java (an adjacency-list implementation). Get a copy of the graph file graph.txt which […]

The post COMP2140-Lab 6 Graphs appeared first on Mantutor.

]]>
To write code to compute the in-degree of every vertex and to print out the vertices visited in a depth-first traversal starting at Vertex 0, for an adjacency-list implementation of a directed graph.

In-Degrees and a Depth-First Traversal

Get a copy of GraphAL.java (an adjacency-list implementation). Get a copy of the graph file graph.txt which lists the number of vertices (5) and edges between them. Write the body of the method printIndegrees, which prints out the in-degree of each vertex in the graph. Also, write the body of the method recursiveTraversal, which performs a recursive depth-first traversal of the graph starting at the vertex given by parameter currVertex, printing out a vertex when the traversal visits it.

The steps of a recursive depth-first traversal at currVertex:

  • Visit currVertex;
  • for each vertex i that is adjacent to currVertex (i.e., such that there is an edge from currVertex to i)
  • if vertex i has not yet been visited do a recursive depth-first traversal at i

The intent is to see which vertices can be reached if you start at vertex 0, and what order you would visit them in

The post COMP2140-Lab 6 Graphs appeared first on Mantutor.

]]>
62431
COMP2140-Lab 5 Hash Tables https://mantutor.com/product/comp2140-lab-5-hash-tables-solved/ Mon, 21 Jun 2021 06:10:19 +0000 https://mantutor.com/?post_type=product&p=62428 To complete a program that compares two different hash table implementations of ADT Table. The Nearly-Complete Program File Lab05.java contains a nearly-complete application that uses two Table implementations: the first is a hash table using linear probing and the second is a hash table using separate chaining. It inserts all the items in input file […]

The post COMP2140-Lab 5 Hash Tables appeared first on Mantutor.

]]>
To complete a program that compares two different hash table implementations of ADT Table.

The Nearly-Complete Program

File Lab05.java contains a nearly-complete application that uses two Table implementations: the first is a hash table using linear probing and the second is a hash table using separate chaining. It inserts all the items in input file Lab05Input.txt into both tables and then prints some statistics to allow a comparison. (Input file Lab05Input.txt is available on UM Learn with Lab05.java.)

In this application, an item consists of a String. The String is the key — there is no auxiliary data associated with the key in this application. The input file contains one item per line.

The file Lab05.java contains four classes:

  1. The application class (named Lab05), which contains main() and the method it calls.
  2. The TableWithLP class, which implements ADT Table with a hash table that uses linear probing for collision resolution.
  3. The TableWithSC class, which implements ADT Table with a hash table that uses separate chaining for collision resolution. In this implementation, each table slot is a pointer to a Node which is a pointer to the first Node in a linked list of keys that hash to this position, — that is, each table slot is an unordered linked list with no dummy nodes.
  4. The private Node class inside the TableWithSC This class implements an ordinary linked-list node with public instance members item and next.

You will complete two methods in the TableWithSC class.

Exercise

Complete the program in the file Lab05.java by adding TWO method bodies (details below). Do not change any of the code that is already written in Lab05.java — just add the two required method bodies. You can write helper methods for these two methods, if needed.

The two methods you will write the bodies of:

insert: There are two inserts, the first one is already implemented. You will implement the second insert. This method is passed a key (a String). It is supposed to insert key into the hash table, using separate chaining to resolve any collisions.

If the key is already in the table, then the method should print an error message and not insert the key — duplicates are not allowed.

If the key is not in the table, then the method should insert the key and increment instance member numberItems, which contains the total number of items currently stored in the table.

search: This method is passed a key (a String). It does a proper hash table search for the key, returning true if it finds the key and false if it doesn’t.

Of course, it assumes that the hash table is using separate chaining to resolve collisions.

The post COMP2140-Lab 5 Hash Tables appeared first on Mantutor.

]]>
62428
COMP2140-Lab 4 Simulating a Simple Survivor Game with a Queue https://mantutor.com/product/comp2140-lab-4-simulating-a-simple-survivor-game-with-a-queue-solved/ Mon, 21 Jun 2021 06:07:05 +0000 https://mantutor.com/?post_type=product&p=62426 To simulate a simple survivor game with a queue. Exercise File Lab4.java contains an almost-complete application with a simple Queue. You need to add most of the body of the method survivor, which currently only prints some information. The survivor method should simulate (using a queue) the survivor game. In this game, N people (numbered […]

The post COMP2140-Lab 4 Simulating a Simple Survivor Game with a Queue appeared first on Mantutor.

]]>
To simulate a simple survivor game with a queue.

Exercise

File Lab4.java contains an almost-complete application with a simple Queue. You need to add most of the body of the method survivor, which currently only prints some information.

The survivor method should simulate (using a queue) the survivor game. In this game, N people (numbered 0 to N− 1) stand in circle, then every kth person is counted out (leaves the circle), until only one person is left. At each elimination, you should print out the eliminated person’s number.

For example, if there are 7 people (N = 7) and k = 2, then you should print out 1 3 5 0 4 2 6 because

the circle changes as follows:    
0 0 0

6                                1                6                 1               6

  • 2 5             2             5              2

4                      3                           4                     3                           4                      3

Start                                First elimination: 1                 Second elimination: 3

0                                                   0

  • 6 6
4

Third elimination: 5

4

Fourth elimination: 0

  4

Fifth elimination: 4

6   6  

5                2                                                   2                         2

2

Third elimination: 2            Last element remaining: 6

The code that you add to the survivor method must simulate the game using a queue to represent the circle of people. To do the eliminating, you must use the standard queue methods (enter, leave, front, and isEmpty) provided in the Queue class. You may not change the Queue class or the main method in any way.

Hint: You can keep eliminating until no people are left in the circle. Sample output:

7 people numbered 0 to 6 stand in a circle.

Every second person is eliminated repeatedly until only one person is left.

The people are eliminated in the following order:

1 3 5 0 4 2 6 <=== last person left

11 people numbered 0 to 10 stand in a circle.

Every third person is eliminated repeatedly until only one person is left. The people are eliminated in the following order:

2 5 8 0 4 9 3 10 7 1 6 <=== last person left

17 people numbered 0 to 16 stand in a circle.

Every 5-th person is eliminated repeatedly until only one person is left.

The people are eliminated in the following order:

4 9 14 2 8 15 5 12 3 13 7 1 0 6 11 16 10 <=== last person left

Program ends normally.

The post COMP2140-Lab 4 Simulating a Simple Survivor Game with a Queue appeared first on Mantutor.

]]>
62426
COMP2140-Lab 3 Intersection of Linked Lists https://mantutor.com/product/comp2140-lab-3-intersection-of-linked-lists-solved/ Mon, 21 Jun 2021 06:04:23 +0000 https://mantutor.com/?post_type=product&p=62424 To implement intersection of sets implemented as simple linked lists with no dummy nodes. Intersection of Two Linked Lists File Lab03.java contains a nearly-complete application that creates pairs of sets of integers (implemented as simple linked lists) and then tests union and intersection methods on them. Union is already implemented, you will implement the intersection […]

The post COMP2140-Lab 3 Intersection of Linked Lists appeared first on Mantutor.

]]>
To implement intersection of sets implemented as simple linked lists with no dummy nodes.

Intersection of Two Linked Lists

File Lab03.java contains a nearly-complete application that creates pairs of sets of integers (implemented as simple linked lists) and then tests union and intersection methods on them. Union is already implemented, you will implement the intersection method only.

If the set is {3,5,7}, then the linked list implementation looks like the following:

top                                                        last

This set implementation uses a simple linked with

  • top, a pointer to the first Node in the list, • last, a pointer to the last Node in the list, and
  • No dummy nodes.

Furthermore, the list is ordered and does not allow duplicates. (Basically, class Set is a renamed class LinkedList.)

Inside the Set class is a privateNode class with public instance members, item and next. Because the Node class is private inside the LinkedList class, no code outside the LinkedList class can access or know about Nodes. Because item and next are public, you can access the item and next of any node anywhere inside the LinkedList class. (This structure is not good object-oriented practice. However, it is very simple and will allow you to transfer your knowledge to non-object-oriented languages easily.)

The method you must write: In the Set class, you must complete method intersection, which is passed two Sets:

  • One set is pointed at by implicit parameter this, and
  • The second set is passed in parameter otherSet.

It returns another set containing all the elements that are in both this and otherSet, without changing this or otherSet. For example, if this is a linked list representing {1,3,5} and otherSet is a linked list representing {3,55}, then method intersection should return a linked list representing {3} (and this and otherSet should be unchanged).

How does it work? A bit like merge in merge sort. Since the linked lists are ordered linked lists, you simply need to loop through this and otherSet at the same time, adding a new element to the (initially empty) result set whenever you see that this and otherSet have the same element.

The intersection begins with pointers thisCurr and otherCurr at the start of the two sets:

Since otherCurr’s item is smaller than thisCurr’s item, nothing is added to the intersection set and otherCurr is moved to the next node:

Since thisCurr’s item is equal to otherCurr’s item, the item is added to the intersection set and both thisCurr and otherCurr are moved to the next node:

Since thisCurr’s item is less than otherCurr’s item, nothing is added to the intersection set and thisCurr is moved to the next node:

2

Since thisCurr’s item is equal to otherCurr’s item, the item is added to the intersection set and both thisCurr and otherSet are moved to the next node:

Since thisCurr is now null, there cannot be any more items that are common to both sets, so the method returns the intersection set (which now contains 3 and 7).

So you need a loop that goes until one of thisCurr or otherCurr is null, moving the pointers as appropriate and only adding an item to the intersection set when thisCurr’s and otherCurr’s items are equal. (You can use private helper method addLast to add items to the intersection set, since the items you are adding are added in increasing order.)

Reminder: Your method should have only ONE return statement. You should not have any break or continue statements.

The post COMP2140-Lab 3 Intersection of Linked Lists appeared first on Mantutor.

]]>
62424
COMP2140-Lab 2 Quick Sort https://mantutor.com/product/comp2140-lab-2-quick-sort-solved/ Mon, 21 Jun 2021 06:01:22 +0000 https://mantutor.com/?post_type=product&p=62422 successfully sort all the numbers in an array, using your partition function. Your partition function should return the correct pivot index of the subarray. You must use a dynamically-allocated array for this lab; no other data structures may be used. The following summarizes the commands used in the Quicksort lab: (OK means no error was […]

The post COMP2140-Lab 2 Quick Sort appeared first on Mantutor.

]]>
successfully sort all the numbers in an array, using your partition function.

  1. Your partition function should return the correct pivot index of the subarray.
  2. You must use a dynamically-allocated array for this lab; no other data structures may be used.
  3. The following summarizes the commands used in the Quicksort lab: (OK means no error was raised.)
Function                                           DESCRIPTION                                       OUTPUT  
QuickSort constructor Create a quickSort array of size capacity. Set initial number of elements (Size) to 0. OK or

Error

 
addToArray <int>  Add data (an integer value) to quickSort array. Duplicates are allowed. OK or

Error

 
capacity Return the capacity of the quickSort array. size  
clear Delete all inserted nodes from the

QuickSort array. (Do not delete QuickSort array – capacity stays the same.)

OK or  
size Return the number of elements currently in the array. An integer value  
private quickSort <start> <end> quickSort the elements in the quickSort array from index <start> to index <end> (where <end> is one past last element) using median and partition functions. OK or

Error

 
public quickSort quickSort all the elements in the quickSort array using median and partition functions. OK or  Error  
medianOfThree <start> <end> 1) Calculate the middle index (middle = (start + end)/2), then 2) bubble-sort the values at the start, middle, and end indices. (<right> is one past last element.) Index of the pivot

(middle index); -1 if provided with invalid input

 
partition <start> <end> <pivot> Partition the quickSort array

(<start>, <end> and <pivot> indexes) around the pivot value. Values smaller than or equal to the pivot should be placed to the start of the pivot while values larger than the pivot should be

Pivot’s ending index, -1 if provided with invalid input  
    placed to the right of the pivot. (<end> is one past last element.)  
  printArray Print the contents of the quickSort array as comma separated values (using a toString() function.) Array values or

Empty

Steps:

  • Step 1 – Begin with a main function.
    1. You will need to write your own main function.
    2. Use command line arguments for input and output files.
  • Step 2 – Add your QuickSort class.
    1. Your QuickSort class should contain a dynamically-allocated templated array. Before you focus too much on the actual sorting algorithm, make sure the logistics of the class work correctly. Focus on addToArray(), clear(), getSize(), and toString() member functions.
    2. The QuickSort class should ask the user to input an integer array size called capacity and create an array accordingly, by randomly generating capacity (for example 100) integers (you can use any random number generator). These created integers should be added to the array by the addToArray() function.
  • Step 3 – Write your medianOfThree() function in the QuickSort class.
    1. The Median-of-Three function takes start and right indexes as parameters and then calculates the index in the middle of the indexes (rounding down if necessary). Note that these are being done on the array populated in Step2.b.
    2. Sort the left, middle, and right numbers from smallest to largest in the array.
    3. Finally, return the index of the middle value. This will be your pivot value in the sortAll() function.
  • Step 4 – Write your partition() function in the QuickSort class.
    1. The partition() function should begin by swapping the leftmost element of the array with the pivot index element.
    2. Now, follow partition the array such that all elements less than or equal to the pivot value are left of the pivot and all elements great than the pivot value are to the right of the pivot.
    3. The partition() function should return the location of the pivot index.
  • Step 5 – Write the private quickSort() function, using your medianOfThree() and partition()
    1. Note that this function will be recursive. Most people use public quicksort() as a starter function that then call another private quicksort function to do the sorting.
    2. To sort, first call your medianOfThree() function to sort the first, middle, and last elements and return the pivot index.
    3. Now, call your partition() function, using the index returned from medianOfThree() as the pivot index. This function will return a new pivot index where your array is split.
    4. Finally, recursively call your sort() function on the two halves of your array, with one half from the left to the pivot and the other half from the pivot to the right.
    5. Print the sorted array.

The post COMP2140-Lab 2 Quick Sort appeared first on Mantutor.

]]>
62422
COMP2140-Assignment 5 Merkle Hash Trees https://mantutor.com/product/comp2140-assignment-5-merkle-hash-trees-solved/ Mon, 21 Jun 2021 05:57:03 +0000 https://mantutor.com/?post_type=product&p=62420 The purpose of this assignment is to write a Java program that implements a MerkleTree to be used in a blockchain. Then you will write a brief report describing your results, in the comments of your program; see the end of this document. Code you can use: You are permitted to use and modify the […]

The post COMP2140-Assignment 5 Merkle Hash Trees appeared first on Mantutor.

]]>
The purpose of this assignment is to write a Java program that implements a MerkleTree to be used in a blockchain. Then you will write a brief report describing your results, in the comments of your program; see the end of this document.

Code you can use: You are permitted to use and modify the code your instructor gave you in class for the various sorting algorithms, and code from Labs. Of course, you must use the code we provided to you below. You are NOT permitted to use code from any other source, You are NOT permitted to show or give your code to any other student. Any other code you need for this assignment, you must write for yourself. We encourage you to write ALL the code for this assignment yourself, based on your understanding of the algorithms — you will learn the material much better if you write the code yourself.

What you need to know about Blockchain:

This assignment is self-contained and probably the easiest. You will write two functions.  We do not expect you to know how Blockchain works. However, by the end of this assignment, if you read the code well enough, you will learn Blockchain in detail.

You will be surprised how this Blockchain technology, considered revolutionary, is built on such simple ideas that a beginner student can code. And later in life, you can mention that you were writing blockchains in your second year of undergraduate.

A transaction is a transfer of coins from a set of addresses (i.e., senders) to another set of addresses (i.e., receivers).

Each sender or receiver is an address, which is stored in a String variable (see Transaction.java). In real life, people can create and use many addresses. We cannot know the owner of an address by just looking at the string.  A Bitcoin transaction can have many senders and receivers. This is why transactions in Figure 1 have different shape sizes. For this assignment, we simplify the transaction model to only one sender and one receiver (see Transaction.java).

A transaction has sender, receiver, and amount attributes. In Bitcoin, transactions are created by ordinary users and sent to a Peer-to-Peer network. Miners listen to the network, discover new transactions, and create blocks out of them. In this assignment, we will not have a real Peer-to-Peer network. The PeerToPeerNetwork.java simulates this and returns a random number of artificial transactions whenever someone calls the collectNewTransactions() function.

A miner is a user (anyone can choose to be a miner) who wants to create a block. The process of getting transactions, putting them into a block, and solving the Proof-of-Work puzzle is called mining a block.

Proof-of-Work (see mineTheBlock() in Blockchain.java) involves creating a string from the blockHash of the previous block, topHash of the MerkleTree, and a long integer (called nonce). Once the SHA256 hash is applied to this string, a 256-bit integer is computed. If the integer is less than a predefined difficulty, the nonce is said to satisfy the difficulty. The block is said to be mined.

Any helper function that you need (e.g., to hash SHA256) is already given in the files.

What you should implement: Implement the following algorithms and methods (you can add any necessary private helper methods):

1- buildFrom function in MerkleTree.java:

Concerns and steps:

Implement the algorithm that takes n transactions and creates a Merkle tree from them. A Merkle tree is a binary tree where leaf nodes are transactions, and interior nodes are transaction hashes (SHA256 algorithm). See figure 1.

In leaf nodes, we take a SHA256 of each transaction, and then concatenate these hashes in the next level, and take their hash again. For example, in the figure the hash “goz1erin…” is computed by

SHA256(SHA256(tx1.toString())+sha256(tx2.toString())). This is applied until we end up with one top hash in the Merkle tree.

At every level (from bottom up), output how many hashes are computed at each level:

Merkle Tree, Bottom Up, Level: 0, number of hashes: 21

Merkle Tree, Bottom Up, Level: 1, number of hashes: 11

Merkle Tree, Bottom Up, Level: 2, number of hashes: 6

Merkle Tree, Bottom Up, Level: 3, number of hashes: 3

Merkle Tree, Bottom Up, Level: 4, number of hashes: 2

Merkle Tree, Bottom Up, Level: 5, number of hashes: 1 – See the Assignment5Output.txt file for output details.

Note that by definition, SHA256(tx1.toString() +SHA256(tx2.toString()) is not equal to SHA256(tx2.toString()+ SHA256(tx1.toString()). When you are creating the Merkle tree, the transaction order is important. You should follow the transaction order defined in the block.

A blockchain does not need to store the Merkle tree, it computes the Merkle tree just to find the top hash, which is “iNu7ag1gor…” in the figure. As a result your code can either i) implement the Merkle tree and store each interior node to reach the top hash, or ii) find the tophash and not store interior nodes.  1st solution: When implementing MerkleTree with nodes, child pointers need to point to parents, because you should build the tree from bottom up, starting from transactions.

2nd solution: If you want to use the second approach, be efficient. Code can be written in 20 lines.

The current block hash is computed from SHA256(previousBlockHash+ topHash+nonce). This way, the block hash of the current block is linked to the block hash of the previous block. If anyone changes the previous block, its hash will change. We will call this event “corruption”.

2- validate() in BlockchainPOW.java

A method to validate the blockchain:

The validation starts from the second block. The first block (genesis block) is mined by the creator of the Bitcoin: Satoshi Nakamoto.

Take the list of transactions stored in a block, and create a Merkle tree from them again (use the existing BuildFrom() function in MerkleTree.java) to find the top hash.

Link the previous block and nonce (follow the order given in mineTheBlock() function in Blockchain.java. Compute the Block hash and compare it to the block hash stored in the block. if they do not match (use string1.equals(string2)), call it a corruption, and return.

  1. Optional 1: write code to update the difficulty every 2 weeks. For this, you can runthe blockchain in a while(true) loop.
  2. Optional 2: write code to update block reward every 4 years. 5. A log file forsample output will be shared on D2L. The output of your code must follow similar steps.
  3. See the discussion forum on D2L for your questions.

Concerns. Please avoid magical numbers in your code. There should be only ONE return per method. See the programming standards (under content/course documents) file on UMLearn, and follow the suggestions. Assignments will be graded by considering these standards. Your code must not give any warnings or errors when compiled and run.

Report

Write a small report in the comments at the end of your program. Answer the following questions in terms of transaction count n. (use short sentences, ideally only one sentence):

  1. What is the depth of the Merkle tree in a block.
  2. If we want to detect corruption at the transaction level, how many comparisonsshould we make in the Merkle tree.

Is there a way to corrupt any part of the blockchain without being detected

The post COMP2140-Assignment 5 Merkle Hash Trees appeared first on Mantutor.

]]>
62420