ISE-ComProg-After-Midterm/Week8/JavaFiles/InsertArray.java

59 lines
2.5 KiB
Java
Raw Normal View History

2020-10-20 15:21:15 +00:00
//This code is written by Siwat Sirichai
//Utilizing the method arraycopy(Array a,int a_start_pos, Array b,int b_start_pos, length)
//This is kinda complicated, diagram attached.
public class InsertArray {
public static void arraycopy(int[] a, int apos,int[] b, int bpos, int length) {
for(int i=0;i<length;i++) b[i+bpos] = a[i+apos];
}
public static int[] insert(int[] a, int[] b, int pos) {
int[] result = new int[a.length+b.length]; //Create an array with length of a+b
if (pos<=0){ //If pos <= 0, just put a b before a
arraycopy(b, 0, result, 0, b.length);
arraycopy(a, 0, result, b.length, a.length);
}
else if (pos>=a.length-1) { //If pos => a.length just put a before b
arraycopy(a, 0, result, 0, a.length);
arraycopy(b, 0, result, a.length, b.length);
}
else {
arraycopy(b, 0, result, pos, b.length); //put in b first
arraycopy(a, 0, result, 0, pos); //put the first part of a in (part before b)
arraycopy(a, pos, result, pos+b.length ,a.length-pos); //put the second part of a in (part after b)
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 1, 2, 3, 4};
int[] b = { 5, 6, 7};
int[] c = { 8, 9, 10, 11, 12};
System.out.print("Printing array a: "); Replace.printArray(a);
System.out.print("Printing array b: "); Replace.printArray(b);
System.out.print("Printing array c: "); Replace.printArray(c);
System.out.println("Now calling inserts!");
System.out.println("------------------------");
int[] d = insert(a,b,1);
int[] e = insert(a,b,4); //ERROR
int[] f = insert(b,a,0);
int[] g = insert(c,a,3);
int[] h = insert(c,a,-1);
int[] i = insert(c,a,7); //ERROR
System.out.print("Printing array a, expecting {1,2,3,4} : "); Replace.printArray(a);
System.out.print("Printing array b, expecting {5,6,7} : "); Replace.printArray(b);
System.out.print("Printing array c, expecting {8,9,10,11,12} : "); Replace.printArray(c);
System.out.print("Printing array d, expecting {1,5,6,7,2,3,4} : "); Replace.printArray(d);
System.out.print("Printing array e, expecting {1,2,3,4,5,6,7} : "); Replace.printArray(e);
System.out.print("Printing array f, expecting {1,2,3,4,5,6,7}: "); Replace.printArray(f);
System.out.print("Printing array g, expecting {8,9,10,1,2,3,4,11,12} : "); Replace.printArray(g);
System.out.print("Printing array h, expecting {1,2,3,4,8,9,10,11,12} : "); Replace.printArray(h);
System.out.print("Printing array i, expecting {8,9,10,11,12,1,2,3,4} : "); Replace.printArray(i);
}
}