Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created November 11, 2021 05:53
Show Gist options
  • Save tk3369/a1439b11c06ca2c17b0d666685d74e08 to your computer and use it in GitHub Desktop.
Save tk3369/a1439b11c06ca2c17b0d666685d74e08 to your computer and use it in GitHub Desktop.
function getMaxEatenDiscountCount_foreach(N, D, K) {
let eaten = new Set();
let eatSum = 0;
let eatCounter = 0;
D.forEach((dish) => {
if (!eaten.has(dish)) {
eatSum++;
eaten.add(dish);
eatCounter++;
}
if (eatCounter > K) {
eaten.delete(eaten.values().next().value);
eatCounter--;
}
});
return eatSum;
}
function getMaxEatenDiscountCount_forloop(N, D, K) {
let eaten = new Set();
let eatSum = 0;
let eatCounter = 0;
for (dish in D) {
if (!eaten.has(dish)) {
eatSum++;
eaten.add(dish);
eatCounter++;
}
if (eatCounter > K) {
eaten.delete(eaten.values().next().value);
eatCounter--;
}
};
return eatSum;
}
function getMaxEatenDiscountCount_arraylookup(N, D, K) {
let MaxD = Math.max.apply(null, D)
let eaten = new Array(MaxD + 1)
let index = []
let eatCounter = 0
let eatSum = 0
D.forEach((dish) => {
if (!eaten[dish]) {
eatSum++;
eaten[dish] = true;
eatCounter++;
index.push(dish);
}
if (eatCounter > K) {
let oldest_dish = index.shift();
eaten[oldest_dish] = false;
eatCounter--;
}
});
return eatSum;
}
function randomInt(N) {
return Math.floor(Math.random() * N);
}
function randomIntArray(N, size) {
return Array.from({length:size}, (_,i) => randomInt(N));
}
function test(fn) {
N = 6; D = [1,2,3,3,2,1]; K = 1;
console.log("test1: ", fn(N, D, K) == 5)
N = 6; D = [1,2,3,3,2,1]; K = 2;
console.log("test1: ", fn(N, D, K) == 4)
N = 7; D = [1,2,1,2,1,2,1]; K = 2;
console.log("test1: ", fn(N, D, K) == 2)
}
function ultimate_test() {
let N = 50000;
let MaxD = 100000;
let D = randomIntArray(MaxD, N);
let K = 25000;
console.time('getMaxEatenDiscountCount_foreach');
getMaxEatenDiscountCount_foreach(N, D, K);
console.timeEnd('getMaxEatenDiscountCount_foreach');
console.time('getMaxEatenDiscountCount_forloop');
getMaxEatenDiscountCount_forloop(N, D, K);
console.timeEnd('getMaxEatenDiscountCount_forloop');
console.time('getMaxEatenDiscountCount_arraylookup');
getMaxEatenDiscountCount_arraylookup(N, D, K);
console.timeEnd('getMaxEatenDiscountCount_arraylookup');
}
ultimate_test()
// test(getMaxEatenDiscountCount_foreach)
// test(getMaxEatenDiscountCount_arraylookup)
@tk3369
Copy link
Author

tk3369 commented Nov 11, 2021

$ node /tmp/sushi.js 
getMaxEatenDiscountCount_foreach: 138.487ms
getMaxEatenDiscountCount_forloop: 301.517ms
getMaxEatenDiscountCount_arraylookup: 99.349ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment