I have a list of users and the contents they have received already.
users = [
{ name: 'Steve', received_contents: ['1a', '1b', '3c'] },
{ name: 'Virginie', received_contents: ['3a', '2b', '3c'] },
{ name: 'Fiona', received_contents: ['1b', '2a', '3b'] },
{ name: 'Jenny', received_contents: ['3b', '2c', '1b'] },
{ name: 'James', received_contents: ['2b', '1b', '3a'] },
{ name: 'Fede', received_contents: ['2c', '3a', '1c'] },
{ name: 'Sara', received_contents: ['3a', '2c', '3b'] },
{ name: 'Tizi', received_contents: ['2b', '1b', '2a'] },
{ name: 'Thomas', received_contents: ['3c', '2b', '1a'] },
]
// These are the boxes for the next shipment and their contents
boxes = [
{ code: 'gr1', contents: ['1a', '1b'] },
{ code: 'gr2', contents: ['1a', '2b'] },
{ code: 'gr3', contents: ['1b', '2c'] },
{ code: 'gr4', contents: ['2c', '3c'] },
{ code: 'gr5', contents: ['3b', '1c'] },
]
The task is to create a function that accepts the list of users and returns a list of users and the boxes they can receive without getting the same contents again.
I'm a bit stuck as to how to make my solution more effective and time efficient.
Here's my solution:
for (var i in users ){
let user = users[i];
console.log("User "+user.name+ " can receive " + getReceivableBoxes(user.received_contents));
}
function getReceivableBoxes (contents){
let receivableBoxes = [];
for(var i in boxes){
let box = boxes[i];
let canReceive = canReceiveBox(contents, box);
if(canReceive){
receivableBoxes.push(box.code);
}
}
return receivableBoxes;
}
function canReceiveBox(received_contents, box) {
let receivableBoxes = [];
for (var i = 0; i < received_contents.length; i++) {
for (var j = 0; j < box.contents.length; j++) {
if (box.contents[j] === received_contents[i]) {
return false;
}
}
}
return true;
}