Source : https://www.hackerrank.com/challenges/s10-quartiles
Objective
In this challenge, we practice calculating quartiles. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers, calculate the respective first quartile (), second quartile (), and third quartile (). It is guaranteed that , , and are integers.
Input Format
The first line contains an integer, , denoting the number of elements in the array.
The second line contains space-separated integers describing the array's elements.
Constraints
- , where is the element of the array.
Output Format
Print lines of output in the following order:
- The first line should be the value of .
- The second line should be the value of .
- The third line should be the value of .
Sample Input
93 7 8 5 12 14 21 13 18
Sample Output
61216
Explanation
. When we sort the elements in non-decreasing order, we get . It's easy to see that .
As there are an odd number of data points, we do not include the median (the central value in the ordered list) in either half:
Lower half (L): 3, 5, 7, 8
Upper half (U): 13, 14, 18, 21
Now, we find the quartiles:
- is the . So, .
- is the . So, .
- is the . So, .
Source : https://www.hackerrank.com/challenges/s10-quartiles
Solution
// github.com/RodneyShag | |
import java.util.Scanner; | |
import java.util.Arrays; | |
public class Solution { | |
public static void main(String[] args) { | |
int [] array = getValues(); | |
Arrays.sort(array); | |
int q1 = findMedian(array, 0, array.length / 2 - 1); | |
int q2 = findMedian(array, 0, array.length - 1); | |
int q3 = findMedian(array, (array.length + 1) / 2, array.length - 1); | |
System.out.println(q1); | |
System.out.println(q2); | |
System.out.println(q3); | |
} | |
/* Creates array from input */ | |
private static int [] getValues() { | |
Scanner scan = new Scanner(System.in); | |
int n = scan.nextInt(); | |
int [] array = new int[n]; | |
for (int i = 0; i < n; i++) { | |
array[i] = scan.nextInt(); | |
} | |
scan.close(); | |
return array; | |
} | |
/* Treats elements from "start" to "end" (inclusive) as an array and calculates its median */ | |
private static int 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 Math.round((value1 + value2) / 2); | |
} | |
} | |
} |
No comments:
Post a Comment