Skip to content

Instantly share code, notes, and snippets.

@kawilliams8
Created March 6, 2021 18:33
Show Gist options
  • Save kawilliams8/46b8637ee1040c10282708a62155688e to your computer and use it in GitHub Desktop.
Save kawilliams8/46b8637ee1040c10282708a62155688e to your computer and use it in GitHub Desktop.
cardTypes solution
let cardTypes = [4, 7, 5, 11, 15];
function cardPackets(cardTypes) {
let packets = [2, 3]; //Assume two packets will require fewer additional cards, but check three packets, as well
let addlCardsSums = [0, 0]; //Store the sum of additional cards needed, per packet quantity (2 or 3, for now)
let addlCards = Array(cardTypes.length).fill(0); //Create a base array of [0,0, ..., 0] to capture add'l cards needed by type
packets.forEach((packet, i) => { //Iterate through 2 and 3 packets versions
cardTypes.map((count, j) => { //Map through cardTypes and increment until each type is divisible by the number of packets
while (count % packets[i] !== 0) {
count++;
addlCards[j]++;
}
return count;
});
addlCardsSums[i] = addlCards.reduce((sum, num) => sum += num); //Sum up the final tally of additional needed cards, for this number of packets
})
let cards = Math.min(...addlCardsSums); //Find the lowest number of additional needed cards
let index = addlCardsSums.indexOf(cards); //Find the correlating index in the packets array
return `${cards} additional cards required for ${packets[index]} packets.`; //Output the result!
}
cardPackets(cardTypes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment