Question

In: Computer Science

In this assignment, you will be practicing the Java OOP skills we've learned this week in...

In this assignment, you will be practicing the Java OOP skills we've learned this week in implementing a customized mutable Array class. Please read the following requirements carefully and then implement your own customized Array class:

=== 1) Basic (100' pts total) ===

Your Array class must provide the following features:

--1.1) (20' pts) Two constructors. One takes the input of the initialized capacity (int) and create the underlying array with that capacity; the other takes no input and creates an array that can hold a single element by default (that is, init capacity == 1);

--1.2) (20' pts) Getters and setters and basic methods we discussed during the class including: getCapacity(), getSize(), set(int index, E val), get(int index), isEmpty();

--1.3) (20' pts) CRUD operations we discussed during the class including: add(int index, E val), addLast(), addFirst(), remove(int index), removeLast(), removeFirst(), removeElement(int target), removeAll(int target);

--1.4) (20' pts) Supports generic types;

--1.5) (20' pts) Mutable, that is when add element exceeding its capacity, it can resize to accommodate the change.

=== 2) Bonus (20' pts total) ===

2.1) (10' pts) Implement a (private or public) swap(int a, int b) method that swaps the two elements in the index a and b if a and b are both admissible; also a public reverse() method that reverses the order of stored elements in-place (means, no additional spaces are allocated).

2.2) (10' pts) A public void sort() method sorts the stored elements in ascending order inO(nlog(n)) time.

[hint]: Quicksort or Merge sort

Solutions

Expert Solution

Answer for Part -1:-

class DynamicArray<T>{

private T[] arr;
private int len = 0; // length user thinks array is
private int capacity = 0; // Actual array size

public DynamicArray() {
this(1);
}

public DynamicArray(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + capacity);
this.capacity = capacity;
arr = (T[]) new Object[capacity];
}

public int size() {
return len;
}

public boolean isEmpty() {
return size() == 0;
}

public T get(int index) {
return arr[index];
}

public void set(int index, T elem) {
arr[index] = elem;
}

public void removeAll() {
for (int i = 0; i < len; i++) arr[i] = null;
len = 0;
}

public void add(T elem) {

// Time to resize!
if (len + 1 >= capacity) {
if (capacity == 0) capacity = 1;
else capacity *= 2; // double the size
T[] new_arr = (T[]) new Object[capacity];
for (int i = 0; i < len; i++) new_arr[i] = arr[i];
arr = new_arr; // arr has extra nulls padded
}

arr[len++] = elem;
}

// Removes an element at the specified index in this array.
public T removeAt(int rm_index) {
if (rm_index >= len || rm_index < 0) throw new IndexOutOfBoundsException();
T data = arr[rm_index];
T[] new_arr = (T[]) new Object[len - 1];
for (int i = 0, j = 0; i < len; i++, j++)
if (i == rm_index) j--; // Skip over rm_index by fixing j temporarily
else new_arr[j] = arr[i];
arr = new_arr;
capacity = --len;
return data;
}

public boolean remove(Object obj) {
int index = indexOf(obj);
if (index == -1) return false;
removeAt(index);
return true;
}

public int indexOf(Object obj) {
for (int i = 0; i < len; i++) {
if (obj == null) {
if (arr[i] == null) return i;
} else {
if (obj.equals(arr[i])) return i;
}
}
return -1;
}

public boolean contains(Object obj) {
return indexOf(obj) != -1;
}
  
@Override
public String toString() {
if (len == 0) return "[]";
else {
StringBuilder sb = new StringBuilder(len).append("[");
for (int i = 0; i < len - 1; i++) sb.append(arr[i] + ", ");
return sb.append(arr[len - 1] + "]").toString();
}
}
}

public class Main{
public static void main(String args[]){
DynamicArray a = new DynamicArray();
a.add(1);
a.add(2);
a.add(3);
System.out.println(a.toString());
}
}
Output Screenshot:-

Answer for Part -2:-

import java.util.*;

// main class
public class Main {

static int [] arr = {10, 20, 30, 40, 50};

public static void swap(int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

public static void reverse() {
int n = arr.length;
int[] b = new int[n];
int j = n;
for (int i = 0; i < n; i++) {
b[j - 1] = arr[i];
j = j - 1;
}
for (int i = 0; i < n; i++) {
arr[i] = b[i];
}

}

public static int partition( int low, int high) {
int pivot = arr[high];
int i = (low - 1); // index of smaller element
for (int j = low; j < high; j++) {
// If current element is smaller than the pivot
if (arr[j] < pivot) {
i++;

// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

swap (i + 1, high);

return i + 1;
}


public static void sort( int low, int high) {
if (low < high) {
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition( low, high);

// Recursively sort elements before
// partition and after partition
sort( low, pi - 1);
sort( pi + 1, high);
}
}

public static void printArray() {
for (int i = 0; i < arr.length; ++i) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {

System.out.println("Array: ");
printArray();
System.out.println("Reversed Array: ");
reverse();
printArray();
System.out.println("Sorted Array: ");
sort(0, arr.length - 1);
printArray();

}
}

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

Please give me a UPVOTE. Thank you :)


Related Solutions

In this assignment, you will be practicing the Java OOP skills we've learned this week in...
In this assignment, you will be practicing the Java OOP skills we've learned this week in implementing a customized mutable Array class. Please read the following requirements carefully and then implement your own customized Array class: === 1) Basic (100' pts total) === Your Array class must provide the following features: --1.1) (20' pts) Two constructors. One takes the input of the initialized capacity (int) and create the underlying array with that capacity; the other takes no input and creates...
Please use the skills you learned in section 9.2 for this assignment. For this activity, you...
Please use the skills you learned in section 9.2 for this assignment. For this activity, you will be creating a confidence interval for the average number of hours of TV watched. Last semester, my MAT 152 online students asked the question, “How many hours of screen time do you have in a typical week?” Please use the data they collected to answer the following questions. Data: 21, 2, 28, 30, 18, 21, 25, 20, 25, 14, 21, 25, 50, 39,...
Please use the skills you learned in section 9.2 for this assignment. For this activity, you...
Please use the skills you learned in section 9.2 for this assignment. For this activity, you will be creating a confidence interval for the average number of hours of TV watched. Last semester, my MAT 152 online students asked the question, “How many hours of screen time do you have in a typical week?” Please use the data they collected to answer the following questions. Data: 21, 2, 28, 30, 18, 21, 25, 20, 25, 14, 21, 25, 50, 39,...
Program in Java using Inheritence The purpose of this assignment is to practice OOP programming covering...
Program in Java using Inheritence The purpose of this assignment is to practice OOP programming covering Inheritance. Core Level Requirements (up to 6 marks) The scenario for this assignment is to design an online shopping system for a local supermarket (e.g., Europa Foods Supermarket or Wang Long Oriental Supermarket). The assignment is mostly concentrated on the product registration system. Design and draw a UML diagram, and write the code for the following classes: The first product category is a fresh...
For this assignment, you are going to build upon several skills that you've learned: Create an...
For this assignment, you are going to build upon several skills that you've learned: Create an object that contains objects. Using querySelectorAll to read a nodeList from the DOM. Looping through the nodeList then updating the HTML page. Set up Create the assignment in a "week6" folder with the typical files: index.html css/styles.css js/scripts.js This is the standard structure that we'll use in all assignments. Here is the HTML to use for this assignment. Change the meta author tag to...
We've learned about PHI and how important it is to protect patient information. We've also learned...
We've learned about PHI and how important it is to protect patient information. We've also learned how "loose talk" causes problems. But how many of us have put that into practice? Your challenge is to go out into the world this week (or your current home or work environment), sit for awhile, and count how many times in a day you hear others talking about someone behind their back. It can be good or bad, it doesn't matter for the...
For this assignment, you will apply what you learned in analyzing a simple Java™ program by...
For this assignment, you will apply what you learned in analyzing a simple Java™ program by writing your own Java™ program. The Java™ program you write should do the following: Display a prompt on the console asking the user to type in his or her first name Construct the greeting string "Hello, nameEntered!" Display the constructed greeting on the console Complete this assignment by doing the following: Download and unzip the linked zip file. Add comments to the code by...
For this assignment, you will apply what you learned in analyzing Java™ code so far in...
For this assignment, you will apply what you learned in analyzing Java™ code so far in this course by writing your own Java™ program. The Java™ program you write should do the following: Accept user input that represents the number of sides in a polygon. Note: The code to do this is already written for you. If input value is not between 3 and 5, display an informative error message If input value is between 3 and 5, use a...
you are practicing your basketball skills by shooting some hoops. You shoot a basketball with initial...
you are practicing your basketball skills by shooting some hoops. You shoot a basketball with initial velocity vo= 10.2 m/s @ θo = 34.0° above the horizontal. Doing so causes the basketball to first go higher than the net, reach a maximal height, and then come back down through the net from above. Find the time it takes the basketball to reach a maximal height (call this height tmax)b.What is the ball’s vertical velocity at tmax?c.What is the ball’s total...
/******************************************************************************* * * Welcome to Assignment 1! In this assignment, you're going to be practicing lots...
/******************************************************************************* * * Welcome to Assignment 1! In this assignment, you're going to be practicing lots * of new JavaScript programming techniques. You'll see comments like this one: * * @param {String} name - the name to greet in the message * * These are specially formatted comments that define parameters to functions, * and tell use the type {String} or {Number}, and also the parameter's name. * Finally, we also explain a bit about how the parameter is used,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT