Advertisement
Guest User

findMedian.js

a guest
Jul 28th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const findMedian = (infiniteArray) => {
  2.   let infiniteLen = 0;
  3.   const arrayMap = infiniteArray.reduce(
  4.     (map, number) => {
  5.       map[number] = (map[number] || 0) + 1;
  6.       infiniteLen++; // demonstration of finding length of data without using .length
  7.       return map;
  8.     },
  9.     {}
  10.   );
  11.  
  12.   // Only numbers in map must be sorted
  13.   // Necessary to iterate from one number to next
  14.   const sortedKeys = Object.keys(arrayMap)
  15.     .map(Number)
  16.     .sort((a,b) => a - b)
  17.  
  18.   var medianIndex = ((infiniteLen + 1) / 2);
  19.  
  20.   let location = 0;
  21.   for (let index = 0; index < sortedKeys.length; index++) {
  22.     const number = sortedKeys[index];
  23.     const nextNumber = sortedKeys[index + 1];
  24.  
  25.     const numberAmount = arrayMap[number];
  26.     if (numberAmount) {
  27.       const nextLocation = numberAmount + location;
  28.       const flooredMedianIndex = Math.floor(medianIndex);
  29.       const inMedianRange = nextLocation >= flooredMedianIndex;
  30.       if (inMedianRange) {
  31.         if (medianIndex % 1 !== 0) {
  32.           let numberToAverageWith =
  33.             nextLocation === flooredMedianIndex ? nextNumber : number;
  34.           return (number + numberToAverageWith) / 2;
  35.         } else {
  36.           return number;
  37.         }
  38.       } else {
  39.         location += numberAmount;
  40.       }
  41.     }
  42.   }
  43. }
  44.  
  45. let test;
  46. test = [1,5,2,4,3,4,3]
  47. console.log(findMedian(test)); // 3
  48.  
  49. test = [1,1,5,2,4,3,4,3]
  50. console.log(findMedian(test)); // 3
  51.  
  52. test = [1,1,5,2,4,3,4,6]
  53. console.log(findMedian(test)); // 3.5
  54.  
  55. test = [1,1,5,2,6,3,5,7]
  56. console.log(findMedian(test)); // 4
  57.  
  58. test = [-1,-2,-3, -5, -4]
  59. console.log(findMedian(test)); // -3
  60.  
  61. test = [-1,-2,-3, 2, 1]
  62. console.log(findMedian(test)); // -1
  63.  
  64. test = [-1,-2,-3, -3, -5, -4]
  65. console.log(findMedian(test)); // -3
  66.  
  67. test = [-1,-2,-3, 2, -1, 1]
  68. console.log(findMedian(test)); // -1
  69.  
  70. test = [-1,-2,-4, -3, -5, -4]
  71. console.log(findMedian(test)); // -3.5
  72.  
  73. test = [-1,-2,-3, 2, 1, 1]
  74. console.log(findMedian(test)); // 0
  75.  
  76. test = [-1.5,-2,-3, 2, 1.75, 1]
  77. console.log(findMedian(test)); // -0.25
  78.  
  79. test = [-1.5,-2,-3, 1.75, 1]
  80. console.log(findMedian(test)); // -1.5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement