-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalc.java
135 lines (119 loc) · 2.9 KB
/
Calc.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.util.*;
/**
* Does calculations on the data.
* HashMap will not be changed!
*/
public class Calc
{
/**
* Sum of data.
*/
public static double sum(HashMap h)
{
if(h.size() == 0)
{
return -1;
}
double total = 0;
for(int i = 0 ; i < h.size() ; i++)
{
total += Integer.parseInt( (String) h.get(i) );
}
return total;
}
/**
* Average of data.
*/
public static double ave(HashMap h)
{
if(h.size() == 0)
{
return -1;
}
double total = 0;
for(int i = 0; i < h.size() ; i++)
{
int nextNum = Integer.parseInt((String)h.get(i));
total += nextNum;
}
return (total / h.size());
}
/**
* Middle of data.
*/
public static Integer median(HashMap h)
{
if(h.size() == 0)
{
return -1;
}
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < h.size() ; i++)
{
int nextNum = Integer.parseInt( (String) h.get(i) );
arr.add(nextNum);
}
Collections.sort(arr);
if(arr.size() % 2 != 0)
{
int middle = arr.size() / 2;
return arr.get(middle);
}
else
{
int oneValue = (int) (arr.size()/2);
int anotherValue = (int) ((arr.size()/2) +1);
int ave = (int) (arr.get(oneValue)) + (int) (arr.get(anotherValue));
return ave/2;
}
}
/**
* Range of data.
*/
public static int range(HashMap h)
{
if(h.size() == 0)
{
return -1;
}
int smallest = Integer.parseInt( (String) h.get(0) );
int largest = Integer.parseInt( (String) h.get(0) );
for(int i = 1 ; i < h.size() ; i++)
{
int num = Integer.parseInt( (String) h.get(i) );
if(num < smallest)
{
smallest = num;
}
if(num > largest)
{
largest = num;
}
}
return largest - smallest;
}
/**
* Standard Deviation of data.
*/
public static double sd(HashMap h)
{
if(h.size() == 0)
{
return -1;
}
double mean = ave(h);
double[] arr = new double[h.size()];
for(int i = 0; i < h.size() ; i++)
{
int num = Integer.parseInt( (String) h.get(i) );
arr[i] = Math.pow(num - mean,2);
}
int sum = 0;
for(int i = 0; i < arr.length ; i++)
{
sum += arr[i];
}
sum /= arr.length;
return (Math.sqrt(sum));
}
}