Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created November 11, 2021 05:30
Show Gist options
  • Save tk3369/b4ff957d04197ec826044e29d4267547 to your computer and use it in GitHub Desktop.
Save tk3369/b4ff957d04197ec826044e29d4267547 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 randomInt(N) {
return Math.floor(Math.random() * N);
}
function randomIntArray(N, size) {
return Array.from({length:size}, (_,i) => randomInt(N));
}
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');
@tk3369
Copy link
Author

tk3369 commented Nov 11, 2021

Result:

$ node /tmp/sushi.js 
getMaxEatenDiscountCount_foreach: 138.572ms
getMaxEatenDiscountCount_forloop: 305.100ms

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