Skip to content

Instantly share code, notes, and snippets.

@franvarney
Created May 12, 2016 19:45
Show Gist options
  • Save franvarney/f26e93cfd9799fa82f0a9e271ea0eaca to your computer and use it in GitHub Desktop.
Save franvarney/f26e93cfd9799fa82f0a9e271ea0eaca to your computer and use it in GitHub Desktop.
getPeakUserCount
function swap (array, a, b) {
var temp = array[a]
array[b] = (array[a] = array[b], temp)
}
function makeSortedArray(x, y) {
var sorted = []
for (var i = x; i < y; ++i) sorted.push(i)
return sorted
}
function makeUnsortedArray(a) {
var arrayCopy = a.slice() // copy
var currentIndex = arrayCopy.length
while (currentIndex) {
var randomIndex = Math.floor(Math.random() * currentIndex)
swap(arrayCopy, --currentIndex, randomIndex)
}
return arrayCopy
}
function mergeArrays(a1, a2) {
var merged = []
var val1, val2;
while (a1.length && a2.length) {
if (val1 < val2){
merged.push([val1, val2])
}
val1 = a1.pop()
val2 = a2.pop()
}
return merged
}
var sortedStart = makeSortedArray(1, 700)
var sortedEnd = makeSortedArray(400, 1000)
var unsortedStart = makeUnsortedArray(sortedStart)
var unsortedEnd = makeUnsortedArray(sortedEnd)
var merged = mergeArrays(unsortedStart, unsortedEnd)
console.log('`merged` length', merged.length)
var data = [[1,10],[5,9],[7,13],[2,3],[15,20]]
function getPeakUserCount(a) {
var map = {}
a.forEach((time) => {
for (var i = time[0]; i <= time[1]; ++i) {
if (!map[i]) map[i] = 1
else ++map[i]
}
})
var largest = 0
Object.keys(map).forEach((key) => {
if (largest < map[key]) largest = map[key]
})
return largest
}
console.log(getPeakUserCount(data))
console.log(getPeakUserCount(merged))
function getPeakUserCount2(a) {
var peak = a.reduce((accum, point) => {
if (!accum.hasOwnProperty(point[0])) {
accum[point[0]] = 0;
}
if (!accum.hasOwnProperty(point[1])) {
accum[point[1]] = 0;
}
accum[point[0]]++;
accum[point[1]]--;
return accum;
}, {});
var max = 0;
var current = 0;
for (var time in peak) {
current += peak[time]
if (current > max) {
max = current;
}
}
return max
}
console.log(getPeakUserCount2(data))
console.log(getPeakUserCount2(merged))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment