Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then:
- If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set , is the median.
- If your set contains an even number of elements, the median is the average of the two middle elements of the sorted sample. In the sorted set , is the median.
- Given an input stream of integers, you must perform the following task for each integer:
- Add the integer to a running list of integers.
- Find the median of the updated list (i.e., for the first element through the element).
- Print the list's updated median on a new line. The printed value must be a double-precision number scaled to decimal place (i.e., format).
- Input Format
- The first line contains a single integer, , denoting the number of integers in the data stream.
- Each line of the subsequent lines contains an integer, , to be added to your list.
- Constraints
- Output Format
- After each new integer is added to the list, print the list's updated median on a new line as a single double-precision number scaled to decimal place (i.e., format).
- Sample Input
- 6
- 12
- 4
- 5
- 3
- 8
- 7
- Sample Output
- 12.0
- 8.0
- 5.0
- 4.5
- 5.0
- 6.0
- **/
- 'use strict';
- const fs = require('fs');
- process.stdin.resume();
- process.stdin.setEncoding('utf-8');
- let inputString = '';
- let currentLine = 0;
- process.stdin.on('data', inputStdin => {
- inputString += inputStdin;
- });
- process.stdin.on('end', _ => {
- inputString = inputString.trim().split('\n').map(str => str.trim());
- main();
- });
- function readLine() {
- return inputString[currentLine++];
- }
- /*
- * Complete the runningMedian function below.
- */
- function runningMedian(a) {
- let result = '';
- let arr = [];
- for (let i = 0; i < a.length; i++) {
- // insert number
- arr.push(a[i]);
- // sort arr
- for (let j = arr.length; j > 1; j--) {
- // swap
- if (arr[j - 2] > arr[j - 1]) {
- let temp = arr[j - 2];
- arr[j - 2] = arr[j - 1];
- arr[j - 1] = temp;
- } else {
- break;
- }
- }
- // get median
- if (arr.length % 2 === 0) {
- // if even
- let index = arr.length / 2;
- let median = (arr[index] + arr[index - 1]) / 2
- result += median + '\n';
- } else {
- // if odd
- let index = Math.ceil(arr.length / 2);
- result += arr[index-1] + '\n';
- }
- }
- return result;
- }
- function main() {
- const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
- const aCount = parseInt(readLine(), 10);
- let a = [];
- for (let aItr = 0; aItr < aCount; aItr++) {
- const aItem = parseInt(readLine(), 10);
- a.push(aItem);
- }
- let result = runningMedian(a);
- ws.write(result);
- ws.end();
- }
Add Comment
Please, Sign In to add comment