-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
50 lines (45 loc) · 1.65 KB
/
Solution.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
// github.com/RodneyShag
import java.util.Scanner;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
/* Save input */
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int [] element = new int[size];
int [] frequency = new int[size];
for (int i = 0; i < size; i++) {
element[i] = scan.nextInt();
}
int numElements = 0;
for (int i = 0; i < size; i++) {
frequency[i] = scan.nextInt();
numElements += frequency[i];
}
scan.close();
/* Create and sort our data set */
int [] data = new int[numElements];
int dataIndex = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < frequency[i]; j++) {
data[dataIndex] = element[i];
dataIndex++;
}
}
Arrays.sort(data);
/* Calculate interquartile range */
double q1 = findMedian(data, 0, data.length / 2 - 1);
double q3 = findMedian(data, (data.length + 1) / 2, data.length - 1);
System.out.println(q3 - q1);
}
/* Treats elements from "start" to "end" (inclusive) as an array and calculates its median */
private static double findMedian(int [] array, int start, int end) {
if ((end - start) % 2 == 0) { // odd number of elements
return (array[(end + start) / 2]);
} else { // even number of elements
int value1 = array[(end + start) / 2];
int value2 = array[(end + start) / 2 + 1];
return (value1 + value2) / 2.0;
}
}
}