Issue
I have a problem statement –
Given Array = [ [1, 1, 5, 2, 3], [4, 5, 6, 4, 3], [9, 4, 4, 1, 5] ], the function should return 4.
Common IDs 1, 3, 4, and 5 are at more than one array.
This Finds the number present at more than one array. I am trying to have a better solution for this problem.
let t0 = performance.now();
/* let arr = [
[1, 2, 2],
[3, 1, 4]
]; */
/* let arr = [
[4, 3],
[5, 5],
[6, 2]
]; */
let arr = [
[1, 1, 5, 2, 3],
[4, 5, 6, 4, 3],
[9, 4, 4, 1, 5]
]
let allArra = [];
let finalOutcome;
let checkCOmmon = (arr1, arr2) => {
/* console.log(arr1);
console.log(arr2); */
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
allArra.push(arr1[i]);
}
}
}
}
for (i = 0; i < arr.length; i++) {
for (j = i + 1; j < arr.length; j++) {
checkCOmmon(arr[i], arr[j]) // find the common element from both the array
}
}
console.log(allArra)
finalOutcome = allArra.sort().filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
});
console.log(finalOutcome);
console.log(finalOutcome.length)
let t1 = performance.now();
console.log(`time taken ${t1 - t0} milliseconds.`);
My proposed solution –
http://jsfiddle.net/neerajswarnkar/6v5omjt0/
How basically we check the performance of function only through profiler I find performance.now()
to check the time.
Please help me to have a better solution that will scale.
Solution
One optimized solution could be –
let arr = [
[1, 1, 5, 2, 3],
[4, 5, 6, 4, 3],
[9, 4, 4, 1, 5]
];
function solution(A) {
let len = A.length;
let hospitals = [];
for (var i = 0; i < len; i++) {
for (var j = i + 1; j < len; j++) {
let conflictShcedule = A[i].filter(schedule => A[j].includes(schedule));
hospitals.push(...conflictShcedule);
}
}
let uniqScheudle = [...new Set(hospitals)].length;
return uniqScheudle;
}
console.log(solution(arr));
let me know your thoughts..
Answered By – Javascript Coder
Answer Checked By – Jay B. (BugsFixing Admin)