prob3
.html
keyboard_arrow_up
School
University of California, Berkeley *
*We aren’t endorsed by this school
Course
11
Subject
Computer Science
Date
Apr 28, 2024
Type
html
Pages
5
Uploaded by BaronFreedom13241 on coursehero.com
EECS16A: Homework 3
¶
Problem: Segway Tours
¶
Run the following block of code first to get all the dependencies.
In [1]:
# %load gauss_elim.py
from gauss_elim import gauss_elim
from numpy import zeros, cos, sin, arange, around, hstack
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.patches import Rectangle
import numpy as np
from scipy.interpolate import interp1d
import scipy as sp
Example Usage of gauss_elim
¶
In [2]:
def test_gauss_elim(A, b):
aug_matrix = np.c_[A, b]
print('Augmented:')
print(aug_matrix)
print('\nAfter GE:')
print(gauss_elim(aug_matrix) )
test_gauss_elim(np.array([[3, 10], \
[-2, 5]]), \
np.array([35, 0]) \
)
Augmented:
[[ 3 10 35]
[-2 5 0]]
After GE:
[[1 0 5]
[0 1 2]]
Dynamics
¶
In [22]:
# Dynamics: state to state
A = np.array([[1, 0.05, -.01, 0],
[0, 0.22, -.17, -.01],
[0, 0.1, 1.14, 0.10],
[0, 1.66, 2.85, 1.14]]);
# Control to state
b = np.array([.01, .21, -.03, -0.44])
nr_states = b.shape[0]
# Initial state
state0 = np.array([-0.3853493, 6.1032227, 0.8120005, -14])
# Final (terminal state)
stateFinal = np.array([0, 0, 0, 0])
Part (d)
¶
In [21]:
# YOUR CODE HERE!
# Complete Gaussian Elimination to see if we can reach stateFinal in 2 steps.
oh = stateFinal - np.dot(np.dot(A,A), state0)
we = np.c_[np.dot(A,b),b]
lol = np.c_[we,oh]
gauss_elim(lol)
Out[21]:
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[-0., -0., 1.],
[ 0., 0., 0.]])
Part (e)
¶
In [20]:
# YOUR CODE HERE!
# Complete Gaussian Elimination to see if we can reach stateFinal in 3 steps.
bro = stateFinal - np.dot(np.dot(np.dot(A,A),A),state0)
mee = np.c_[np.dot(np.dot(A,A),b), np.dot(A,b)]
lil = np.c_[mee, b]
big = np.c_[lil, bro]
gauss_elim(big)
Out[20]:
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
Part (f)
¶
In [23]:
# YOUR CODE HERE!
# Complete Gaussian Elimination to see if we can reach stateFinal in 4 steps.
jeo = stateFinal - np.dot(np.dot(np.dot(np.dot(A,A),A),A),state0)
eric = np.c_[np.dot(np.dot(np.dot(A,A),A),b), np.dot(np.dot(A,A),b)]
jorge = np.c_[eric, np.dot(A,b)]
pinga = np.c_[jorge, b]
pene = np.c_[pinga, jeo]
print(pene)
gauss_elim(pene)
[[ 2.62100300e-02 2.41570000e-02 2.08000000e-02 1.00000000e-02
3.17637529e-05]
[ 2.29773000e-02 2.43630000e-02 5.57000000e-02 2.10000000e-01
-6.30740802e-02]
[-1.26984820e-01 -8.34880000e-02 -5.72000000e-02 -3.00000000e-02
3.18901788e-01]
[-5.87888940e-01 -3.42448000e-01 -2.38500000e-01 -4.40000000e-01
1.77659810e+00]]
Out[23]:
array([[ 1. , 0. , 0. , 0. ,
-13.24875075],
[ 0. , 1. , 0. , 0. ,
23.73325125],
[ 0. , 0. , 1. , 0. ,
-11.57181872],
[ 0. , 0. , 0. , 1. ,
1.46515973]])
Part (g)
¶
Preamble
¶
This function will take care of animating the segway
In [25]:
# frames per second in simulation
fps = 20
# length of the segway arm/stick
stick_length = 1.
def animate_segway(t, states, controls, length):
#Animates the segway
# Set up the figure, the axis, and the plot elements we want to animate
fig = plt.figure()
# some config
segway_width = 0.4
segway_height = 0.2
# x coordinate of the segway stick
segwayStick_x = length * np.add(states[:, 0],sin(states[:, 2]))
segwayStick_y = length * cos(states[:, 2])
# set the limits
xmin = min(around(states[:, 0].min() - segway_width / 2.0, 1), around(segwayStick_x.min(), 1))
xmax = max(around(states[:, 0].max() + segway_height / 2.0, 1), around(segwayStick_y.max(), 1))
# create the axes
ax = plt.axes(xlim=(xmin-.2, xmax+.2), ylim=(-length-.1, length+.1), aspect='equal')
# display the current time
time_text = ax.text(0.05, 0.9, 'time', transform=ax.transAxes)
# display the current control
control_text = ax.text(0.05, 0.8, 'control', transform=ax.transAxes)
# create rectangle for the segway
rect = Rectangle([states[0, 0] - segway_width / 2.0, -segway_height / 2],
segway_width, segway_height, fill=True, color='gold', ec='blue')
ax.add_patch(rect)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
SKELETON CODE IS PROVIDED ALONG WITH C AND H FILES.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "node.h"
#include "stack_functions.h"
#define NUM_VERTICES 10
/** This function takes a pointer to the
adjacency matrix of a Graph and the
size of this matrix as arguments and
prints the matrix
*/
void print_graph(int * graph, int size);
/** This function takes a pointer to the
adjacency matrix of a Graph, the size
of this matrix, the source and dest
node numbers along with the weight or
cost of the edge and fills the adjacency
matrix accordingly.
*/
void add_edge(int * graph, int size, int src, int dst, int cost);
/** This function takes a pointer to the adjacency matrix of
a graph, the size of this matrix, source and destination
vertex numbers as inputs and prints out the path from the
source vertex to the destination vertex. It also prints
the total cost of this…
arrow_forward
Develop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.Develop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.
arrow_forward
PYTHON:
Please fix my code to print the correct traversals, especially at the def functions, because I could not print the correct results of the inorder, postorder, and preorder traversals from the user input.
#POSTORDERclass Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert Node def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the Tree def PrintTree(self): if self.left: self.left.PrintTree() print(self.data),…
arrow_forward
6.2 Create a Product class with Product Id & Product Name. Write a program to accept information of 10 products and store that in HashSet. Do following operations, a.Search a particular product in the HashSet.b.Remove a particular product from the HashSet by using product id.(Referbelow table for the product list)
Product Id Product Name
P001 Maruti 800
P002 Maruti Zen
P003 Maruti Dezire
P004 Maruti Alto
arrow_forward
I'm trying to understand LargeIntList classes for lists, I was wondering these statements or True or False? either or, can you please explain your answers? Thank you.
Uses the “by copy” approach with its elements.
Implements the ListInterface interface.
Keeps its data elements sorted.
Allows duplicate elements.
Uses the LLNode class of the support package.
Throws an exception if an iteration “walks off ” the end of the list.
Throws an exception if an element is added when it is "full".
Supports addition of elements at the front of the list, the end of the list, and anywhere in between.
Can hold objects of any Java class.
Has only O(1) operations, including its constructor.
Provides more than one Iterator.
arrow_forward
this code gives me an error
Traceback (most recent call last): File "main.py", line 2, in <module> from IntList import IntList File "/home/runner/local/submission/IntList.py", line 24, in <module> if new_node.data > current.next.data: NameError: name 'new_node' is not defined
The original code given that can be edited is below
class IntList: def __init__(self): self.head = None self.tail = None
def append(self, new_node): if self.head == None: self.head = new_node self.tail = new_node else: self.tail.next = new_node new_node.prev = self.tail self.tail = new_node
def prepend(self, new_node): if self.head == None: self.head = new_node self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node
def insert_after(self, current_node, new_node): if self.head is None:…
arrow_forward
Implement the LPU Latch my code is written below having a lot of bugs in it please give you code with proper comments and remove the bugs having proper reason with correct code:
#include <bits/stdc++.h>
using namespace std;
class LRUCache {
list dq;
unordered_map<int, list<int>::iterator> ma;
int csize;
public:
LRUCache(int);
void refer(int);
void display();
};
LRUCache::LRUCache(int n)
{
csize;
}
void LRUCache::refer(int x)
{
if (ma.find(x) == ma.end()) {
if (dq.size() = csize) {
dq.pop_back();
ma.erase(last);
}
}
else
dq.erase(ma[x]);
dq.push_front(x);
ma[x] = dq.begin();
}
void LRUCache::display()
{
for (auto it = dq.begin(); it = dq.end();
it+)
cout << (it);
cout << endl;
}
int main()
{
LRUCache ca(4);
ca.refer(1);
ca.refer(2);
ca.refer(3);
ca.refer(1);
ca.refer(4);
ca.refer(5);
return 0;
}
arrow_forward
/** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). Takes advantage of the fact that the * keys appear in increasing order to terminate` early when possible. * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { // TODO // Change this code to make use of the fact that the list is sorted to // terminate early when possible. // As this code already uses recursion, the private helper function is // already present below, but it will need to be changed to terminate // early when appropriate. if (key == null) throw new IllegalArgumentException("argument to delete() is null"); first = delete(first, key); }
// delete key in linked list beginning at Node x // warning: function call stack too large if table is large private Node delete(Node x, Key…
arrow_forward
TaskDeclare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of…
arrow_forward
Java Program
This assignment requires one project with two classes.
Class Employee
Class Employee
Attributes (all private):
id: String
lastName: String
firstName: String
salary: int
Executable Class
create an array of Employee objects.
create an ArrayList of Employee objects from that array.
use an enhanced for loop to print all employees as shown in the sample output.
create a TreeMap that uses Strings for keys and Employees as values.
this TreeMap should map Employee ID numbers to their associated Employees.
process the ArrayList to add elements to this map.
print all employees in ID # order as shown, but do so using the TreeMap's forEach method and a lambda expression
arrow_forward
C++
Create a generic function increment(start, stop, x) that adds x to every element in the range [start,stop). The addition is done using the + operator. The arguments start and stop are bidirectional iterators. Write a test driver.
arrow_forward
please update generateRandoms, letterToGrades, sumBetween, countCharacters
//A6Utilities.java
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.security.SecureRandom;import java.util.List;import java.util.TreeMap;import java.util.function.Function;import java.util.stream.Collectors;public class A6Utilities {/*** Returns the corresponding letter grade. Don't modify this method, simply use it when converting single* grades to their equivalent letter grade** @param grade the integer grade to convert* @return the letter grade equivalent to the integer grade*/private static char letterGrade(final int grade) {if (grade < 0) return '?';else if (grade < 60) return 'F';else if (grade < 70) return 'D';else if (grade < 80) return 'C';else if (grade < 90) return 'B';else if (grade <= 100) return 'A';else return '?';}/*** The method uses Java Streams only. Don't use any looping structures, conditional statements are OK (IF, TERNARY,…
arrow_forward
THE QUESTION IS ATTACHED:
PLEASE AVOID USING
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
BECAUSE I HAVEN'T STUDIED THEM YET, YOU CAN USE 1D AND 2D ARRAYS.
YOU ARE FREE TO USE
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
EFFECTIVELY USE LOOPS AND CONTROL STATEMENTS.
TXT. FILE IS INCLUDED BELOW:
MOVIE NAME, MOVIE YEAR, RATING AND GENRE.
The Martian2015Adventure8.0Murder on the Orient Express2017Crime6.5X-Men: First Class2011Action7.7X-Men: Days of Future Past2014Action7.9This Means War2012Action6.3Godzilla vs. Kong2021Adventure6.5Black Widow2021Action7.5Zack Snyder's Justice League2021Action8.1The Ten Commandments1956Drama7.9The Father2020Drama8.3Nobody2021Crime7.5Promising Young Woman2020Crime7.5What Lies Below2020Horror4.4Shrine2021Horror5.1Bram Stoker's Dracula1992Horror7.4
arrow_forward
Please implement this function:
void swap(int pos1, int pos2) {}.
There's an answer from the previous teacher but he added '' node** hRef " in the function (see below) please correct without the href.
For LinkedList, to maintain integrity of data in the structure, you are not to swap directly the element, nor remove a node. Instead, you are to only change the nodes' next pointers.
PLEASE CORRECT THIS ONE
void swap(node** hRef, int pos1, int pos2) { if (pos1 == pos2) return;
node *prevNode1 = NULL; node* currNode1 = *hRef;
while (currNode1 && currNode1->index != pos1) { prevNode1 = currNode1; currNode1 = currNode1->next; }
node *prevNode2 = NULL; node *currNode2 = *hRef;
while (currNode2 && currNode2->index != pos2) { prevNode2 = currNode2; currNode2 = currNode2->next; }
if (currNode1 == NULL || currNode2 == NULL) return;
if (prevNode1 != NULL) prevNode1->next =…
arrow_forward
You are going to implement a program that creates an unsorted list by using a linked list implemented by yourself. NOT allowed to use LinkedList class or any other classes that offers list functions. It is REQUIRED to use an ItemType class and a NodeType struct to solve this. Use C++, please read instructions carefully and new solution only!
The “data.txt” file has three lines of data
100, 110, 120, 130, 140, 150, 160
100, 130, 160
1@0, 2@3, 3@END
You need to
1. create an empty unsorted list
2. add the numbers from the first line to list using putItem() function.
Then print all the current keys to command line in one line using printAll().
3. delete the numbers given by the second line in the list by using deleteItem() function.
Then print all the current keys to command line in one line using printAll()..
4. putItem () the numbers in the third line of the data file to the corresponding location in the list. For example, 1@0 means adding number 1 at position 0 of the list.
Then…
arrow_forward
Can you please help update this?
//A6Utilities.java
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.security.SecureRandom;import java.util.List;import java.util.TreeMap;import java.util.function.Function;import java.util.stream.Collectors;public class A6Utilities {/*** Returns the corresponding letter grade. Don't modify this method, simply use it when converting single* grades to their equivalent letter grade** @param grade the integer grade to convert* @return the letter grade equivalent to the integer grade*/private static char letterGrade(final int grade) {if (grade < 0) return '?';else if (grade < 60) return 'F';else if (grade < 70) return 'D';else if (grade < 80) return 'C';else if (grade < 90) return 'B';else if (grade <= 100) return 'A';else return '?';}/*** The method uses Java Streams only. Don't use any looping structures, conditional statements are OK (IF, TERNARY, SWITCH)* <p>* Generates a list of secure…
arrow_forward
Hashing Project in Python to Extract Features of Names
You are given the following three functions. They take plain text names and covert then into features vefctors so that you can work with them in a classification system.
Let's check your understanding of Python function. Add notes to each line describing what is happening in these functions.
FUNCTION ONE:
def hashfeatures(baby, B, FIX):
"""
Input:
baby : a string representing the baby's name to be hashed
B: the number of dimensions to be in the feature vector
FIX: the number of chunks to extract and hash from each string
Output:
v: a feature vector representing the input string
"""
v = np.zeros(B)
for m in range(FIX):
featurestring = "prefix" + baby[:m]
v[hash(featurestring) % B] = 1
featurestring = "suffix" + baby[-1*m:]
v[hash(featurestring) % B] = 1
return v
FUNCTION TWO:
def name2features(filename, B=128, FIX=3, LoadFile=True):
"""
Output:
X : n feature…
arrow_forward
You are going to implement hashing with chaining with separate chaining. Please implement your hash function accordingly to distribute the data evenly in the array.
Fill in the missing code! C only!
ASAP!!!
THE CODE:
#include <stdio.h>
// RecordTypestruct RecordType{int id;char name;int order;};
// Fill out this structurestruct HashType{
};
// Compute the hash functionint hash(int x){
}
// parses input file to an integer arrayint parseData(char* inputFileName, struct RecordType** ppData){FILE* inFile = fopen(inputFileName, "r");int dataSz = 0;int i, n;char c;struct RecordType *pRecord;*ppData = NULL;
if (inFile){fscanf(inFile, "%d\n", &dataSz);*ppData = (struct RecordType*) malloc(sizeof(struct RecordType) * dataSz);// Implement parse data blockif (*ppData == NULL){printf("Cannot allocate memory\n");exit(-1);}for (i = 0; i < dataSz; ++i){pRecord = *ppData + i;fscanf(inFile, "%d ", &n);pRecord->id = n;fscanf(inFile, "%c ", &c);pRecord->name =…
arrow_forward
how do i test this function in javascript
function breakup(list,partitioner) { var result = {}; for(var i=0; i<list.length; i++) { var prop=partitioner(list[i]); if(!Array.isArray(result[prop])) { result[prop] = []; } result[prop].push(list[i]); } return result;}
breakup( list , partitioner )
This function accepts two inputs: a list of elements and a function that accepts an element from the list. The result is an object whose properties correspond to the items returned by the partitioner and whose values are lists of elements that generated that property.
Examples
breakup( [ 1, 2, 3, 5, 6, 7 ], (x) => { return x % 2 == 0; } ) => { true:[ 2, 6 ], false:[ 1, 3, 5, 7 ] }
breakup( [ 1.3, 5.1, 1.1, 4.3, 5.5 ], Math.floor ) => { 1:[ 1.3, 1.1 ], 4:[ 4.3 ], 5:[ 5.1, 5.5 ] }
breakup( [“cat”, “bat”, “rat”, “horse”, “pony”], function(s) { return s.length; } ) => { 3:[“cat”, “bat”, “rat”], 4:[“pony”], 5:[“horse”] }
arrow_forward
A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0.
Example: head refers to the list of nodes 1 → 2 → 3 → 1 → NULL. There is a cycle where node 3 points back to node 1, so return 1.
Function Description: Complete the has cycle function provided in the moodle assignment folder. It has the following parameter: • SinglyLinkedListNode pointer head: a reference to the head of the list.
Returns: • int: 1 if there is a cycle or 0 if there is not.
Note: if the list is empty, head will be null.
Input Format: The code stub reads from stdin and passes the appropriate argument to your function. The custom test cases format will not be described for this question due to its complexity. Expand the section for the main function and review the code if you would like to figure out how to create a custom case.
Constraints:…
arrow_forward
Implement the function below
void swap(int pos1, int pos2) {}
Inital code to be completed:
class LinkedList : public List { node* head; node* tail; int index;
node* create_node(int num) { node* n = (node*) malloc(sizeof(node)); n->element = num; n->next = NULL; return n; }
public: LinkedList() { index = 0; head = NULL; tail = NULL; }
int add(int num) { addTail(num); return index; } int get(int pos) { node* currnode = head; int count =0; while (currnode != NULL){ count++; if (count == pos){ return currnode -> element; }else{ currnode = currnode -> next; } } return -1; } int size() { return index; } void swap(int pos1, int pos2) { } // WARNING!…
arrow_forward
//Need help fixing some issues with a project. PLEASE read below
Write a Java program that implements both Linear Search and Binary Search. The program will take a collection of objects (generic type data) as input and print the number of comparisons needed to find a target element within that collection. You will create the following two Java classes:1. SearchCombo.java : Code for both linearSearch and binarySearch will be in this class. You may take help from the textbook Chapter 9, Section 9.1. However, note that the design requirements are different from the textbook code.•Both search methods must use the Comparable<T> interface and the compareTo() method.•Your program must be able to handle different data types, i.e., use generics.•For binarySearch, if you decide to use a midpoint computation formula that is different from the textbook, explain that formula briefly as a comment within your code.
2. Tester.java : This class will contain the main() method. The user will be…
arrow_forward
Write a Python code using the given function and conditions. Do not use Numpy. Use LinkedList Manipulation.
Given function: def insert(self, newElement, index)
Pre-condition: The list is not empty.
Post-condition: This method inserts newElement at the given index of the list. If an element with the same key as newElement value already exists in the list, then it concludes the key already exists and does not insert the key. [You must also check the validity of the index].
arrow_forward
You are going to implement a program that creates an unsorted list by using a linked list implemented by yourself. NOT allowed to use LinkedList class or any other classes that offers list functions. It is REQUIRED to use an ItemType class and a NodeType struct to solve this homework.
The “data.txt” file has three lines of data
100, 110, 120, 130, 140, 150, 160
100, 130, 160
1@0, 2@3, 3@END
You need to
1. create an empty unsorted list
2. add the numbers from the first line to list using putItem() function.
Then print all the current keys to command line in one line using printAll().
3. delete the numbers given by the second line in the list by using deleteItem() function.
Then print all the current keys to command line in one line using printAll()..
4. putItem () the numbers in the third line of the data file to the corresponding location in
the list. For example, 1@0 means adding number 1 at position 0 of the list.
Then print all the current keys to command line in one…
arrow_forward
Integer dataSize is read from input. Then, strings and integers are read and stored into string vector subjectList and integer vector pageList, respectively. Lastly, integer pageThreshold is read from input.
Set matchCount with the number of element pairs with a page greater than or equal to pageThreshold.
Output the subject of each pair found with a page greater than or equal to pageThreshold. End with a newline.
Ex: If the input is:
3 Environment 416 Cooking 353 Science 306 349
Then the output is:
Environment Cooking Total: 2
By using the following code:
#include
#include
using namespace std;
int main() {
int numElements;
int pageThreshold;
int matchCount;
unsigned int i;
cin >> numElements;
vector subjectList(numElements);
vector pageList(numElements);
for (i = 0; i < subjectList.size(); ++i) {
cin >> subjectList.at(i);
cin >> pageList.at(i);
}
cin >> pageThreshold;
/* Your code goes here */
cout << "Total: " << matchCount;…
arrow_forward
Fill the gaps :
#include <stdlib.h>#include "fatal.h" #include "heapsort.h"
voidSwap( ElementType *Lhs, ElementType *Rhs ){ElementType Tmp = *Lhs;*Lhs = *Rhs;*Rhs = Tmp;}
/* START: fig7_8.txt */
voidPercDown( ElementType A[ ], int P, int N ){int Child, i;ElementType Tmp;
Tmp = A[P];/* 1*/ for( i = P; < N; i = Child ){/* 2*/ Child = ____________;/* 3*/ if( Child != N - 1 && A[ Child + 1 ] > A[ Child ] )/* 4*/ Child++;/* 5*/ if( ___________ )/* 6*/ A[ i ] = A[ Child ];else/* 7*/ break;}/* 8*/ A[ i ] =Tmp;}
voidHeapsort( ElementType A[ ], int N ){int i;
/* 1*/ for( i = N / 2 - 1; i >= 0; i-- ) /* BuildHeap *//* 2*/ PercDown( A, i, N );/* 3*/ for( i = N - 1; i > 0; i-- ){/* 4*/ Swap( &A[ 0 ], &A[ i ] ); /* DeleteMax *//* 5*/ PercDown( A, 0, i );}}/* END */
arrow_forward
Edit the following:
package dao; import com.mongodb.client.MongoCollection; import dto.BasePaymentDto; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.bson.Document; import org.bson.types.ObjectId; public class PaymentDao implements BaseDao<BasePaymentDto> { private static PaymentDao instance; public MongoCollection<Document> collection; // TODO instead of using a list, directly use mongo to load/store private PaymentDao(MongoCollection<Document> collection){ this.collection = collection; } public static PaymentDao getInstance() { if (instance == null) { instance = new PaymentDao(MongoConnection.getCollection("Payments")); } return instance; } public static PaymentDao getInstance(MongoCollection<Document> collection) { instance = new PaymentDao(collection); return instance; } @Override public void put(BasePaymentDto basePaymentDto) { } @Override public BasePaymentDto get(String id) { return null; } @Override…
arrow_forward
In this assignment, you will create a Linked List data structure variant called a “Circular Linked List”. The Node structure is the same as discussed in the slides and defined as follows (we will use integers for data elements):
public class Node
{
public int data;
public Node next;
}
For the Circular Linked List, its class definition is as follows:
public class CircularLinkedList
{
public int currentSize;
public Node current;
}
In this Circular Linked List (CLL), each node has a reference to an existing next node. When Node elements are added to the CLL, the structure looks like a standard linked list with the last node’s next pointer always pointing to the first. In this way, there is no Node with a “next” pointer in the CLL that is ever pointing to null.
For example, if a CLL has elements “5”, “3” and “4” and “current” is pointing to “3”, the CLL should look like:
Key observations with this structure:
The currentSize is 3 meaning there…
arrow_forward
I'm trying to understand LargeIntList (Large Integers) classes for lists, I was wondering these statements or True or False? either or, can you please explain your answers? Thank you.
Allows duplicate elements.
Uses the LLNode class of the support package.
Throws an exception if an iteration “walks off ” the end of the list.
Throws an exception if an element is added when it is "full".
Supports addition of elements at the front of the list, the end of the list, and anywhere in between.
Can hold objects of any Java class.
Has only O(1) operations, including its constructor.
Provides more than one Iterator.
arrow_forward
Java Program:
There are errors in the lexer and shank file. Please fix those errors and there must be no error in any of the code at all. Below is the lexer, shank, and token files. The shank file is the main method. There is a rubric attached as well.
Lexer.java
import java.util.ArrayList;import java.util.HashMap;import java.util.List;
import mypack.Token.TokenType;
public class Lexer {
private static final int INTEGER_STATE = 1;private static final int DECIMAL_STATE = 2;private static final int IDENTIFIER_STATE = 3;private static final int SYMBOL_STATE = 4;private static final int ERROR_STATE = 5;private static final int STRING_STATE = 6;private static final int CHAR_STATE = 7;private static final int COMMENT_STATE = 8;
private static final char EOF = (char) -1;
private static String input;private static int index;private static char currentChar;private static int lineNumber = 1;private static int indentLevel = 0;private static int lastIndentLevel = 0;
private static…
arrow_forward
Java help.
The file UnsortedLinkedDictionary.java contains unimplemented methods for a dictionary basedon an unsorted linked list. Implement all these methods.
The java code is below:
import java.util.Iterator;import java.util.NoSuchElementException;public class UnsortedLinkedDictionary<K, V> {public static void main(String args[]){// Add you tests here}public UnsortedLinkedDictionary() {} // end default constructorpublic V add(K key, V value) {} // end addpublic V remove(K key) {} // end removepublic V getValue(K key) {} // end getValuepublic boolean contains(K key) {} // end containspublic boolean isEmpty() {} // end isEmptypublic int getSize() {} // end getSizepublic final void clear() { } // end clearprivate class Node {private K key;private V value;private Node next;private Node(K searchKey, V dataValue) {key = searchKey;value = dataValue;next = null; } // end constructorprivate Node(K searchKey, V dataValue, Node nextNode) {key = searchKey;value = dataValue;next =…
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- SKELETON CODE IS PROVIDED ALONG WITH C AND H FILES. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "node.h" #include "stack_functions.h" #define NUM_VERTICES 10 /** This function takes a pointer to the adjacency matrix of a Graph and the size of this matrix as arguments and prints the matrix */ void print_graph(int * graph, int size); /** This function takes a pointer to the adjacency matrix of a Graph, the size of this matrix, the source and dest node numbers along with the weight or cost of the edge and fills the adjacency matrix accordingly. */ void add_edge(int * graph, int size, int src, int dst, int cost); /** This function takes a pointer to the adjacency matrix of a graph, the size of this matrix, source and destination vertex numbers as inputs and prints out the path from the source vertex to the destination vertex. It also prints the total cost of this…arrow_forwardDevelop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.Develop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.arrow_forwardPYTHON: Please fix my code to print the correct traversals, especially at the def functions, because I could not print the correct results of the inorder, postorder, and preorder traversals from the user input. #POSTORDERclass Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert Node def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the Tree def PrintTree(self): if self.left: self.left.PrintTree() print(self.data),…arrow_forward
- 6.2 Create a Product class with Product Id & Product Name. Write a program to accept information of 10 products and store that in HashSet. Do following operations, a.Search a particular product in the HashSet.b.Remove a particular product from the HashSet by using product id.(Referbelow table for the product list) Product Id Product Name P001 Maruti 800 P002 Maruti Zen P003 Maruti Dezire P004 Maruti Altoarrow_forwardI'm trying to understand LargeIntList classes for lists, I was wondering these statements or True or False? either or, can you please explain your answers? Thank you. Uses the “by copy” approach with its elements. Implements the ListInterface interface. Keeps its data elements sorted. Allows duplicate elements. Uses the LLNode class of the support package. Throws an exception if an iteration “walks off ” the end of the list. Throws an exception if an element is added when it is "full". Supports addition of elements at the front of the list, the end of the list, and anywhere in between. Can hold objects of any Java class. Has only O(1) operations, including its constructor. Provides more than one Iterator.arrow_forwardthis code gives me an error Traceback (most recent call last): File "main.py", line 2, in <module> from IntList import IntList File "/home/runner/local/submission/IntList.py", line 24, in <module> if new_node.data > current.next.data: NameError: name 'new_node' is not defined The original code given that can be edited is below class IntList: def __init__(self): self.head = None self.tail = None def append(self, new_node): if self.head == None: self.head = new_node self.tail = new_node else: self.tail.next = new_node new_node.prev = self.tail self.tail = new_node def prepend(self, new_node): if self.head == None: self.head = new_node self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node def insert_after(self, current_node, new_node): if self.head is None:…arrow_forward
- Implement the LPU Latch my code is written below having a lot of bugs in it please give you code with proper comments and remove the bugs having proper reason with correct code: #include <bits/stdc++.h> using namespace std; class LRUCache { list dq; unordered_map<int, list<int>::iterator> ma; int csize; public: LRUCache(int); void refer(int); void display(); }; LRUCache::LRUCache(int n) { csize; } void LRUCache::refer(int x) { if (ma.find(x) == ma.end()) { if (dq.size() = csize) { dq.pop_back(); ma.erase(last); } } else dq.erase(ma[x]); dq.push_front(x); ma[x] = dq.begin(); } void LRUCache::display() { for (auto it = dq.begin(); it = dq.end(); it+) cout << (it); cout << endl; } int main() { LRUCache ca(4); ca.refer(1); ca.refer(2); ca.refer(3); ca.refer(1); ca.refer(4); ca.refer(5); return 0; }arrow_forward/** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). Takes advantage of the fact that the * keys appear in increasing order to terminate` early when possible. * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { // TODO // Change this code to make use of the fact that the list is sorted to // terminate early when possible. // As this code already uses recursion, the private helper function is // already present below, but it will need to be changed to terminate // early when appropriate. if (key == null) throw new IllegalArgumentException("argument to delete() is null"); first = delete(first, key); } // delete key in linked list beginning at Node x // warning: function call stack too large if table is large private Node delete(Node x, Key…arrow_forwardTaskDeclare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of…arrow_forward
- Java Program This assignment requires one project with two classes. Class Employee Class Employee Attributes (all private): id: String lastName: String firstName: String salary: int Executable Class create an array of Employee objects. create an ArrayList of Employee objects from that array. use an enhanced for loop to print all employees as shown in the sample output. create a TreeMap that uses Strings for keys and Employees as values. this TreeMap should map Employee ID numbers to their associated Employees. process the ArrayList to add elements to this map. print all employees in ID # order as shown, but do so using the TreeMap's forEach method and a lambda expressionarrow_forwardC++ Create a generic function increment(start, stop, x) that adds x to every element in the range [start,stop). The addition is done using the + operator. The arguments start and stop are bidirectional iterators. Write a test driver.arrow_forwardplease update generateRandoms, letterToGrades, sumBetween, countCharacters //A6Utilities.java import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.security.SecureRandom;import java.util.List;import java.util.TreeMap;import java.util.function.Function;import java.util.stream.Collectors;public class A6Utilities {/*** Returns the corresponding letter grade. Don't modify this method, simply use it when converting single* grades to their equivalent letter grade** @param grade the integer grade to convert* @return the letter grade equivalent to the integer grade*/private static char letterGrade(final int grade) {if (grade < 0) return '?';else if (grade < 60) return 'F';else if (grade < 70) return 'D';else if (grade < 80) return 'C';else if (grade < 90) return 'B';else if (grade <= 100) return 'A';else return '?';}/*** The method uses Java Streams only. Don't use any looping structures, conditional statements are OK (IF, TERNARY,…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education