Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@AmrAbdulrahman
Last active July 29, 2020 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmrAbdulrahman/538484b8d1d782c2424a8cc248408f8c to your computer and use it in GitHub Desktop.
Save AmrAbdulrahman/538484b8d1d782c2424a8cc248408f8c to your computer and use it in GitHub Desktop.
function checkWinner(codeList, shoppingCart) {
if (codeList.length === 0) return 1;
if (shoppingCart.length === 0) return 0;
function canMatch(group, fromIndex) {
// if cart has no enough items to match the group
if (fromIndex + group.length > shoppingCart.length) return false;
for (let groupItemIndex = 0; groupItemIndex < group.length; groupItemIndex++) {
// if items don't match, and we don't have a wildcard, then fail immediately
if(group[groupItemIndex] !== shoppingCart[fromIndex + groupItemIndex] && group[groupItemIndex] !== "anything")
return false;
}
// matched all items within the group
return true;
}
let currentGroupIndex = 0;
for (let itemIndex = 0; itemIndex < shoppingCart.length; itemIndex++) {
let group = codeList[currentGroupIndex];
// if we can't even match the current group
if (itemIndex + group.length > shoppingCart.length) break;
// if current group matches, start matching from (itemIndex + len(group))
if (canMatch(group, itemIndex)) {
currentGroupIndex ++;
itemIndex += group.length - 1;
// if matched all groups, we have a winner, yay!
if (currentGroupIndex === codeList.length)
return 1;
}
}
// matched none, or some, but failed to match all groups
return 0;
}
function distance(x, y) {
return Math.sqrt(Math.pow(location[0], 2) + Math.pow(location[1], 2));
}
function closestLocations(totalCrates, allLocations, truckCapacity) {
return allLocations
.map(([x, y]) => {
return { x, y, dist: distance(x, y) };
})
.sort((a, b) => a.dist - b.dist)
.slice(0, truckCapacity)
.map(({ x, y }) => ([x, y]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment