In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion.
Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another MyArray object given as parameter.
MyArray supports the following operations.
• getSize: returns the size of the array.
• get (i): returns the i-th element of the array. If the element does not exist, it throws a "NoSuchElementException” which is a subclass of Java class RunTimeException.
• add (val): inserts value as the last element of the array. If necessary, double the size of the current array to accommodate the new item.
• equals: Two MyArrays are equal if they have the same number of elements in the same order. Implement this overriding method recursively.
• sum: returns the sum of all elements of the array. Implement this recursively.
• max: returns the largest element of the array. Implement this recursively.
• min: returns the smallest element of the array. Implement this recursively.
• srch (elt): Searches for the element using the recursive binary search algorithm and returns the index of position where it is found, -1 if not found.
• sort: Sorts the array using the bubble sort algorithm. Implement this recursively.
• invert: Inverts the order of elements in the array. Implement this recursively.
• toString: This must return a String which contains complete information about the array including how many elements it has and what are their values. Overrides the same method in the Object class.
The private instance variables of MyArray are an array of integers, and how many elements does it have.
It is perfectly legal to use the services of private methods to implement any recursive algorithms you wish. That is, you can implement some of the above methods with a call to another (private) method of the class passing appropriate parameters.
To test your implementation of MyArray class, write a test program as follows:
• Create a default MyArray MA1.
• Prompt the user for the name of the input and output files.
• Output the size of MA1.
• Read the number of elements to insert in MA1. Let this be n. [This is the first line of input from the file.]
• Now, read n integer values from the file and insert them in MA1 in that order.
• Output the size of MA1.
• Output MA1.
• Find and output the largest and smallest elements of MA1.
• Output the sum of all elements of MA1.
• Create another MyArray MA2 by copying MA1.
• Check and output if MA1 and MA2 are equal.
• Sort MA2 using the recursive bubble sort algorithm.
• Check and output if MA1 and MA2 are equal.
• Output MA2.
• Read the search elements from the input file (just continue to read the input file) till the end of the file, and for eachelement, output if that element exists in MA2. If it does, output its position; otherwise indicate that it does not exist in the array.
• Invert MA2.
• output MA2
Using the following code to read from a text
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class fileIO {
public static void main (String[] args) throws Exception
{ String inf = JOptionPane.showInputDialog("Input file?");
// Input file is src/<name of the file>
FileReader inFile = new FileReader(inf);
Scanner in = new Scanner(inFile);
String outf = JOptionPane.showInputDialog("Output file?");
PrintWriter outFile = new PrintWriter(outf);
while (in.hasNextLine())
{ String line = in.nextLine();
outFile.println(line+"\n");
}
outFile.close();
}
}
MyArray.java
======================
import java.util.NoSuchElementException;
public class MyArray {
// data fields
private int array[]; // array to store data
private int CAPACITY; // maximum capacity of
array
private int size; // total number of elements in
array
// default constructor
public MyArray() {
// create array of capacity
10
this(10);
}
// constructor with parameter
public MyArray(int capacity) {
// initialize data
this.CAPACITY = capacity;
array = new int[CAPACITY];
size = 0;
}
// copy constructor
public MyArray(MyArray other) {
// initialize this array and copy
each element from given array
this.CAPACITY =
other.CAPACITY;
this.size = other.size;
this.array = new
int[CAPACITY];
for(int i=0; i<size; i++)
{
this.array[i] =
other.array[i];
}
}
// returns the size of the array
public int getSize() {
return size;
}
// returns the i-th element of the array
// if the element does not exist, it throws a
"NoSuchElementException”
public int get(int i) {
// check for valid index
if(i < 0 || i >= size)
{
throw new
NoSuchElementException();
}
return array[i];
}
// inserts value as the last element of the
array
// if necessary, double the size of the current array
to accommodate the new item
public void add(int val) {
// validate size of array
if(size == CAPACITY) {
// double the
array size
CAPACITY =
CAPACITY * 2;
int[] temp = new
int[CAPACITY];
// copy each
element
for(int i=0;
i<size; i++) {
temp[i] = array[i];
}
array =
temp;
}
// add element to end of
array
array[size] = val;
size++;
}
// Two MyArrays are equal if they have the same
number of elements in the same order
public boolean equals(MyArray other) {
// call private method recursively
to check if both arrays are equal
if(this.size != other.size) {
return
false;
}
else {
return
equals(other, size - 1);
}
}
private boolean equals(MyArray other, int i) {
// base case
if(i < 0) {
return
true;
}
// recursive step
if(this.array[i] == other.array[i])
{
return
equals(other, i - 1);
}
return false;
}
// returns the sum of all elements of the
array
public int sum() {
// compute sum by recursively
calling private sum method
return sum(size - 1);
}
private int sum(int i) {
// base case
if(i < 0) {
return 0;
}
// recursive step
return sum(i - 1) + array[i];
}
// returns the largest element of the array
public int max() {
// recursively compute maximum
element in array
return max(array[size - 1], size -
1);
}
private int max(int max, int index) {
// base case
if(index < 0) {
return
max;
}
// recursive step
else if(array[index] > max)
{
return
max(array[index], index - 1);
}
else {
return max(max,
index - 1);
}
}
// returns the smallest element of the array
public int min() {
// recursively compute maximum
element in array
return min(array[size - 1], size -
1);
}
private int min(int min, int index) {
// base case
if(index < 0) {
return
min;
}
// recursive step
else if(array[index] < min)
{
return
min(array[index], index - 1);
}
else {
return min(min,
index - 1);
}
}
// Searches for the element using the recursive
binary search algorithm
// returns the index of position where it is found, -1
if not found.
public int search(int element) {
// recursively call search method
to find element
return search(element, size -
1);
}
private int search(int element, int index) {
// base case
if(index < 0) {
return -1;
}
if(array[index] == element) {
return
index;
}
// recursive step
return search(element, index -
1);
}
// Sorts the array using the bubble sort
algorithm
public void sort() {
// recursively call sort method to
sort the array
sort(size - 1);
}
private void sort(int index) {
// base case
if(index < 0) {
return;
}
// recursive step
// find max and put it at index
location
int max = max(array[index],
index);
// find index of max
int maxIndex = search(max);
// swap max with last element in
array
int temp = array[index];
array[index] = max;
array[maxIndex] = temp;
sort(index - 1);
}
// Inverts the order of elements in the array
public void invert() {
// invert array by recursively
swapping positions
invert(0, size - 1);
}
private void invert(int start, int end) {
// base case
if(start >= end) {
return;
}
// recursive step
int temp = array[start];
array[start] = array[end];
array[end] = temp;
invert(start + 1, end - 1);
}
// returns a String which contains complete
information about the array including how many elements it
has
// and what are their values. Overrides the same
method in the Object class.
@Override
public String toString() {
String str = "There are " + size +
" elements in array.\n[";
if(size > 0) {
// add first
element
str = str +
array[0];
}
// add remaining elements
for(int i=1; i<size; i++)
{
str = str + ", "
+ array[i];
}
return str + "]";
}
}
======================
fileIO.java
======================
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class fileIO {
// main method to test MyArray
public static void main (String[] args) throws
Exception{
// Create a default MyArray
MA1
MyArray MA1 = new MyArray();
// Prompt the user for the name
of the input and output files
String inf =
JOptionPane.showInputDialog("Input file?");
// Input file is src/<name of
the file>
FileReader inFile = new
FileReader(inf);
Scanner in = new
Scanner(inFile);
String outf =
JOptionPane.showInputDialog("Output file?");
PrintWriter outFile = new
PrintWriter(outf);
// Output the size of MA1
outFile.append(String.format("Size:
%d\n", MA1.getSize()));
// Read the number of elements to
insert in MA1. Let this be n. [This is the first line of input from
the file.]
int size =
Integer.parseInt(in.nextLine());
// Now, read n integer values from
the file and insert them in MA1 in that order
for(int i=0; i<size; i++)
{
MA1.add(in.nextInt());
}
// Output the size of MA1
// Output MA1.
outFile.append(MA1.toString());
outFile.append("\n");
// Find and output the largest and
smallest elements of MA1
outFile.append(String.format("Min:
%d\n", MA1.min()));
outFile.append(String.format("Max:
%d\n", MA1.max()));
// Output the sum of all elements
of MA1
outFile.append(String.format("Sum:
%d\n", MA1.sum()));
// Create another MyArray MA2 by
copying MA1
MyArray MA2 = new
MyArray(MA1);
// Check and output if MA1 and MA2
are equal
outFile.append(String.format("MA1
and MA2 are equal? %s\n", MA1.equals(MA2)));
// Sort MA2 using the recursive
bubble sort algorithm
MA2.sort();
// Check and output if MA1 and MA2
are equal
outFile.append(String.format("MA1
and MA2 are equal? %s\n", MA1.equals(MA2)));
// Output MA2
outFile.append(MA2.toString());
outFile.append("\n");
// Read the search elements from
the input file (just continue to read the input file) till the end
of the file,
// and for each element, output if
that element exists in MA2
// If it does, output its position;
otherwise indicate that it does not exist in the array
while(in.hasNext()) {
int elem =
in.nextInt();
int pos =
MA2.search(elem);
if(pos == -1)
{
outFile.append("Element: " +
Integer.toString(elem) + " does not exist in array\n");
}
else {
outFile.append("Element: " +
Integer.toString(elem) + " found in array at position: " +
Integer.toString(pos) + "\n");
}
}
// Invert MA2.
MA2.invert();
// output MA2
outFile.append(MA2.toString());
outFile.append("\n");
// close files
outFile.close();
in.close();
}
}
====================
input.txt
====================
10
5
-4
75
94
0
1
3
45 68
77 0 54
let me know if you have problem or doubts. thank you.
In Java, Implement a class MyArray as defined below, to store an array of integers (int)....
Java Program Create a class to store an array of with enough space to store 10 integer values. Using the principle of recursion, implement the following: *getSize : returns the size of the array. *get (i): returns the i-th element of the array. If the element does not exist, it throws a "NoSuchElementException” which is a subclass of Java class RunTimeException. *add (val): inserts value as the last element of the array. If necessary, double the size of the current...
Write a Java method that will take an array of integers of size n and shift right by m places, where n > m. You should read your inputs from a file and write your outputs to another file. Create at least 3 test cases and report their output. I've created a program to read and write to separate files but i don't know how to store the numbers from the input file into an array and then store the...
#include <iostream> using namespace std; template <typename Item> class MyArray{ private: Item *myarray; int size; int used; void doubleSize(); public: MyArray(); ~MyArray(); int length(); void insertHead(Item i); void insertTail(Item i); void deleteHead(); void deleteTail(); void sortAscending(); void sortDescending(); Item operator [](int i){ return myarray[i]; } }; template <typename Item> MyArray<Item>::MyArray(){ size = 5; used = 0; myarray = new Item[size];...
Programming Assignment #7 (Recursion) This assignment is to write some methods that perform simple array operations recursively. Specifically, you will write the bodies for the recursive methods of the ArrayRecursion class, available on the class web page. No credit will be given if any changes are made to ArrayRecursion.java, other than completing the method bodies Note that the public methods of ArrayRecursion – contains(), getIndexOfSmallest(), and sort() – cannot be recursive because they have no parameters. Each of these methods...
Implement the following: a. A template class named MyArray. 1) MyArray is a dynamic partially filled array for primitive types. 2) data members: - a pointer for the array - any associated variables needed to manage the array. 3) Constructor must insure that specified capacity is possible. Exit the program if an illegal value is specified. 4) “The Big Three” are required to insure deep copy. 5) Private grow function is used to automatically increase the size of the array...
Implement a Java class that is called RainFall that uses a double array to store the amount of rainfall for each month of the year. The class should have only one instance variable of type double[]. Implement the following methods in the RainFall class: 1. A constructor that creates and initializes all entries in the array to be -1. 2. toString: a method that returns a one-line String representation of the object that includes 12 double numbers that represent the...
In C only Please! This lab is to write a program that will sort an array of structs. Use the functions.h header file with your program. Create a source file named functions.c with the following: A sorting function named sortArray. It takes an array of MyStruct's and the length of that array. It returns nothing. You can use any of the sorting algorithms, you would like though it is recommended that you use bubble sort, insertion sort, or selection sort...
Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this file, include your assignment documentation code block. After the documentation block, you will need several import statements. import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; Next, declare the Lab12 class and define the main function. public class Lab12 { public static void main (String [] args) { Step 2: Declaring Variables For this section of the lab, you will need to declare...
package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 { public static void main (String [] args) { // ============================================================ // Step 2. Declaring Variables You Need // These constants are used to define 2D array and loop conditions final int NUM_ROWS = 4; final int NUM_COLS = 3; String filename = "Input.txt"; // A String variable used to save the lines read from input...
create a file homework_part_1.c a) Implement the function initialize_array that receives two parameters: an array of integers and the array size. Use a for loop and an if statement to put 0s in the odd positions of the array and 5s in the even positions. You must use pointers to work with the array. Hint: review pointers as parameters. b) Implement the function print_array that receives as parameters an array of integers and the array size. Use a for statements...