forked from ucsd-cse15l-f22/lab3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayExamples.java
79 lines (68 loc) · 2.11 KB
/
ArrayExamples.java
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
public class ArrayExamples {
// Changes the input array to be in reversed order
static void reverseInPlace(int[] arr) {
for(int i = 0; i < arr.length / 2; i += 1) {
int tmp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = tmp;
}
/*
* error: overwrites arr[i] on first half without saving it for assignment later
* original:
for(int i = 0; i < arr.length; i += 1) {
arr[i] = arr[arr.length - i - 1];
}
*/
}
// Returns a *new* array with all the elements of the input array in reversed
// order
static int[] reversed(int[] arr) {
int[] newArray = new int[arr.length];
for(int i = 0; i < arr.length; i += 1) {
newArray[i] = arr[arr.length - i - 1];
}
return newArray;
/*
* error: Values from the empty new array are being assigned to the old array,
and it should be the other way around.
* original:
int[] newArray = new int[arr.length];
for(int i = 0; i < arr.length; i += 1) {
arr[i] = newArray[arr.length - i - 1];
}
return arr;
*/
}
// Averages the numbers in the array (takes the mean), but leaves out the
// lowest number when calculating. Returns 0 if there are no elements or just
// 1 element in the array
static double averageWithoutLowest(double[] arr) {
if(arr.length < 2) { return 0.0; }
double lowest = arr[0];
for(double num: arr) {
if(num < lowest) { lowest = num; }
}
double sum = 0;
for(double num: arr) {
sum += num;
}
sum -= lowest;
return sum / (arr.length - 1);
/*
* error: Same number might get skipped if equal to the lowest
(only one of the lowest number should be dropped,
but function will drop duplicates too)
* original:
if(arr.length < 2) { return 0.0; }
double lowest = arr[0];
for(double num: arr) {
if(num < lowest) { lowest = num; }
}
double sum = 0;
for(double num: arr) {
if(num != lowest) { sum += num; }
}
return sum / (arr.length - 1);
*/
}
}