naive imperative solution | let result = (() => {
if(arr1.length !== arr2.length) return false;
let arr2_indices = new Set();
for(let i = 0;i < arr1.length;i++) {
let found_match = false;
for(let j = 0;j < arr2.length;j++) {
if(arr1[i] === arr2[j] && !arr2_indices.has(j)) {
arr2_indices.add(j);
found_match = true;
break;
}
}
if(!found_match) return false;
}
return true;
})();
if(result !== true) throw Error(`naive imperative solution didn't return true\n\narr1=${arr1}\n\n\n\n\n\n\n\n\n\narr2=${arr2}`);
| ready |
solution using Map (1) | let result = (() => {
if(arr1.length !== arr2.length) return false;
let arr2_elementCount = new Map();
for(let i = 0;i < arr2.length;i++) {
arr2_elementCount.set(arr2[i], (~~arr2_elementCount.get(arr2[i])) + 1);
}
for(let i = 0;i < arr1.length;i++) {
let elementCount = ~~arr2_elementCount.get(arr1[i]);
if(elementCount ===
0) return false;
arr2_elementCount.set(arr1[i], elementCount - 1);
}
let elementsRemaining = false;
arr2_elementCount.forEach(value => {
if(value !== 0) elementsRemaining = true;
});
return !elementsRemaining;
})();
if(result !== true) throw Error(`solution using Map (1) didn't return true\n\narr1=${arr1}\n\n\n\n\n\n\n\n\n\narr2=${arr2}`);
| ready |
solution using Map (2) | let result = (() => {
if(arr1.length !== arr2.length) return false;
let arr2_elementCount = new Map();
for(let i = 0;i < arr2.length;i++) {
arr2_elementCount.set(arr2[i], (~~arr2_elementCount.get(arr2[i])) + 1);
}
for(let i = 0;i < arr1.length;i++) {
let elementCount = ~~arr2_elementCount.get(arr1[i]);
if(elementCount === 0) return false;
arr2_elementCount.set(arr1[i], elementCount - 1);
}
arr2_elementCount = arr2_elementCount.values();
for(let i = 0;i < arr2_elementCount;i++) {
if(arr2_elementCount[i] !== 0) return false;
}
return true;
})();
if(result !== true) throw Error(`solution using Map (2) didn't return true\n\narr1=${arr1}\n\n\n\n\n\n\n\n\n\narr2=${arr2}`);
| ready |
solution using Map (3) | let result = (() => {
if(arr1.length !== arr2.length) return false;
let arr2_elementCount = new Map();
for(let i = 0;i < arr2.length;i++) {
arr2_elementCount.set(arr2[i], (~~arr2_elementCount.get(arr2[i])) + 1);
}
for(let i = 0;i < arr1.length;i++) {
let elementCount = ~~arr2_elementCount.get(arr1[i]);
if(elementCount === 0) return false;
arr2_elementCount.set(arr1[i], --elementCount);
if(elementCount === 0) arr2_elementCount.delete(arr1[i]);
}
return arr2_elementCount.size === 0;
})();
if(result !== true) throw Error(`solution using Map (3) didn't return true\n\narr1=${arr1}\n\n\n\n\n\n\n\n\n\narr2=${arr2}`);
| ready |