-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSc2720_lab5.java
More file actions
102 lines (75 loc) · 2.54 KB
/
CSc2720_lab5.java
File metadata and controls
102 lines (75 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//Program Name: Lab5
//Name: Stephanie L. Wyckoff
//Date: 2/10/2017
//Course: Data Structures Lab
//Professor: Duan
//TA: Pelin Icer, Shubin Wu
//Description: Array manipulation. Program populates an array with random integers and then adds new numbers to the beginning and end, adds a new index and reverses the array.
//Input: none
//Output: names of the methods followed by the original array and the manipulated array for all methods
import java.util.Arrays;
import java.util.Random;
public class lab5 {
//insert new number at beginning and move others down
public static String insertBeg(int[] array, int v){
int[] newArr = Arrays.copyOf(array, array.length);
for(int i = newArr.length-1; i > 0; i--){
newArr[i] = newArr[i-1];
}
newArr[0] = v;
System.out.println("insertBeg");
return toString(array, newArr);
}
//insert new number at end and move others up
public static String insertEnd(int[] array, int v){
int[] newArr = Arrays.copyOf(array, array.length);
for(int i = 0; i < newArr.length-1; i++){
newArr[i] = newArr[i+1];
}
newArr[newArr.length-1] = v;
System.out.println("insertEnd");
return toString(array, newArr);
}
//insert new number at new index, make bigger array
public static String insertIndex(int[] array, int p, int v){
int[] newArr = Arrays.copyOf(array, array.length+1);
for(int i = 0; i < p; i++){
newArr[i] = newArr[i];
}
newArr[p] = v;
for(int i = (p+1); i < newArr.length; i++){
newArr[i] = newArr[i];
}
System.out.println("insertIndex");
return toString(array, newArr);
}
//reverse original array
public static String reverse(int[] array){
int[] newArr = Arrays.copyOf(array, array.length);
for(int i = 0; i < newArr.length/2; i++){
int temp = newArr[i];
newArr[i] = newArr[newArr.length-1-i];
newArr[newArr.length-1-i] = temp;
}
System.out.println("reverse");
return toString(array, newArr);
}
//print out each array
public static String toString(int[] array, int[] array1){
return "The Original Array: " + Arrays.toString(array) + "\nNew Array: "+ Arrays.toString(array1);
}
public static void main(String[] args){
Random r = new Random();//random value 1-10
int[] arr = new int[5];
int v = 42;
int p = 5;
//populate array with random integers
for(int i = 0; i < arr.length; i++){
arr[i] = r.nextInt(10)+1;
}
System.out.println(insertBeg(arr,v) + "\n");
System.out.println(insertEnd(arr,v) + "\n");
System.out.println(insertIndex(arr,p,v) + "\n");
System.out.println(reverse(arr) + "\n");
}
}