Enhance the implementation of IntArray so that it has a prepend method. Instead
ID: 3813414 • Letter: E
Question
Enhance the implementation of IntArray so that it has a prepend method. Instead of adding an element to the end, prepend adds it to the beginning, at index 0, and causes all existing elements to have their indexes increased by 1. However, like add, your prepend method must also guarenteed that only a linear number of elements are copied.
Easiest method: Double the array when you run out of space it as before, but copy the old array to the middle of the new array.
This is what I have so far. Please help!
public class IntArray {
// Int array representing the internal data.
private int[] a;
private int length;
public IntArray() {
a = new int[8];
length = 0;
}
public int get(int i) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
return a[i];
}
public void set(int i, int value) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
a[i] = value;
}
public int size() {
return length;
}
public void add(int value) {
if (length >= a.length) {
int[] b = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
}
}
}
Explanation / Answer
public class IntArray {
// Int array representing the internal data.
private int[] a;
private int length;
// main function to verify.
public static void main(String args[]){
IntArray arr = new IntArray();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
arr.add(6);
arr.add(7);
arr.add(8);
arr.add(9);
arr.prepend(10);
arr.add(1);
for(int i=0;i<arr.length;i++){
System.out.println(arr.a[i]);
}
}
public IntArray() {
a = new int[8];
length = 0;
}
public int get(int i) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
return a[i];
}
public void set(int i, int value) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
a[i] = value;
}
public int size() {
return length;
}
public void add(int value) {
if (length >= a.length) {
int[] b = new int[a.length * 2];
int i;
for (i = 0; i < a.length; i++) {
b[i] = a[i];
}
b[i] = value;
a = b;
}
else{
a[length] = value;
}
length += 1;
}
public void prepend(int value){
if(length>=a.length){
int[] c = new int[a.length*2];
// add value to first index
c[0] = value;
// moving each element to new array by increasing it's index
for(int i=0;i<a.length;i++){
c[i+1] = a[i];
}
a = c;
}
else{
// increasing the index of each element.
for(int i=length;i>=0;i--){
a[i+1] = a[i];
}
// adding value to first index.
a[0] = value;
}
length += 1;
}
}
/* sample output
10
1
2
3
4
5
6
7
8
9
1
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.