Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const findMedian = (infiniteArray) => {
- let infiniteLen = 0;
- const arrayMap = infiniteArray.reduce(
- (map, number) => {
- map[number] = (map[number] || 0) + 1;
- infiniteLen++; // demonstration of finding length of data without using .length
- return map;
- },
- {}
- );
- // Only numbers in map must be sorted
- // Necessary to iterate from one number to next
- const sortedKeys = Object.keys(arrayMap)
- .map(Number)
- .sort((a,b) => a - b)
- var medianIndex = ((infiniteLen + 1) / 2);
- let location = 0;
- for (let index = 0; index < sortedKeys.length; index++) {
- const number = sortedKeys[index];
- const nextNumber = sortedKeys[index + 1];
- const numberAmount = arrayMap[number];
- if (numberAmount) {
- const nextLocation = numberAmount + location;
- const flooredMedianIndex = Math.floor(medianIndex);
- const inMedianRange = nextLocation >= flooredMedianIndex;
- if (inMedianRange) {
- if (medianIndex % 1 !== 0) {
- let numberToAverageWith =
- nextLocation === flooredMedianIndex ? nextNumber : number;
- return (number + numberToAverageWith) / 2;
- } else {
- return number;
- }
- } else {
- location += numberAmount;
- }
- }
- }
- }
- let test;
- test = [1,5,2,4,3,4,3]
- console.log(findMedian(test)); // 3
- test = [1,1,5,2,4,3,4,3]
- console.log(findMedian(test)); // 3
- test = [1,1,5,2,4,3,4,6]
- console.log(findMedian(test)); // 3.5
- test = [1,1,5,2,6,3,5,7]
- console.log(findMedian(test)); // 4
- test = [-1,-2,-3, -5, -4]
- console.log(findMedian(test)); // -3
- test = [-1,-2,-3, 2, 1]
- console.log(findMedian(test)); // -1
- test = [-1,-2,-3, -3, -5, -4]
- console.log(findMedian(test)); // -3
- test = [-1,-2,-3, 2, -1, 1]
- console.log(findMedian(test)); // -1
- test = [-1,-2,-4, -3, -5, -4]
- console.log(findMedian(test)); // -3.5
- test = [-1,-2,-3, 2, 1, 1]
- console.log(findMedian(test)); // 0
- test = [-1.5,-2,-3, 2, 1.75, 1]
- console.log(findMedian(test)); // -0.25
- test = [-1.5,-2,-3, 1.75, 1]
- console.log(findMedian(test)); // -1.5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement