Check if three arrays contains the same elementChecking if two byte arrays are the sameFind the object that contains title1-2Matching element of arrays on a conditionTesting if numbers in the array can be added up to equal the largest number in the arrayExtensible actions for same elementCheck if 2 arrays have (exactly) the same elements recursivelyJavascript node/react web developer interview codeSum Of Two Arrays element by element and arrays can be of unequal lengthIterating over an object that contains arraysThe difference of two arrays
Playing a Character as Unobtrusive and Subservient, Yet Not Passive
What ways have you found to get edits from non-LaTeX users?
SQL counting distinct over partition
How to draw a Technology Radar?
Prime Sieve and brute force
You have (3^2 + 2^3 + 2^2) Guesses Left. Figure out the Last one
How do governments keep track of their issued currency?
Soft question: Examples where lack of mathematical rigour cause security breaches?
Second (easy access) account in case my bank screws up
How come the nude protesters were not arrested?
Why would future John risk sending back a T-800 to save his younger self?
concatenation of context sensitive and context-free is context sensitive or not?
What makes Ada the language of choice for the ISS's safety-critical systems?
How to manually rewind film?
CROSS APPLY produces outer join
How to trick the reader into thinking they're following a redshirt instead of the protagonist?
What to do when surprise and a high initiative roll conflict with the narrative?
Implement Own Vector Class in C++
Is it expected that a reader will skip parts of what you write?
Arriving at the same result with the opposite hypotheses
How can I end combat quickly when the outcome is inevitable?
With Ubuntu 18.04, how can I have a hot corner that locks the computer?
How can this tool find out registered domains from an IP?
Why can my keyboard only digest 6 keypresses at a time?
Check if three arrays contains the same element
Checking if two byte arrays are the sameFind the object that contains title1-2Matching element of arrays on a conditionTesting if numbers in the array can be added up to equal the largest number in the arrayExtensible actions for same elementCheck if 2 arrays have (exactly) the same elements recursivelyJavascript node/react web developer interview codeSum Of Two Arrays element by element and arrays can be of unequal lengthIterating over an object that contains arraysThe difference of two arrays
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
Do 3 arrays contain a common element, if they contain output it.
For example: [1,2,3], [2,3], [2,4] -> answer = 2
let arr1 = [1, 3, 11, 32, 44, 99];
let arr2 = [4, 12, 15, 99];
let arr3 = [4, 11, 13, 15, 23, 43];
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0;
let j = 0;
while (1)
I will be glad if you give me any tips to improve my code. Thanks in advance.
Sorry, I'm not an English speaker.
javascript array
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
Do 3 arrays contain a common element, if they contain output it.
For example: [1,2,3], [2,3], [2,4] -> answer = 2
let arr1 = [1, 3, 11, 32, 44, 99];
let arr2 = [4, 12, 15, 99];
let arr3 = [4, 11, 13, 15, 23, 43];
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0;
let j = 0;
while (1)
I will be glad if you give me any tips to improve my code. Thanks in advance.
Sorry, I'm not an English speaker.
javascript array
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
1
$begingroup$
Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say "common element", are you expecting just one answer? What happens if there's more than one? Can there be more than one?
$endgroup$
– Joseph
8 hours ago
$begingroup$
What do you mean by "first" common element? The lowest value? Or some metric involving the three indices?
$endgroup$
– Toby Speight
8 hours ago
$begingroup$
The lowest value
$endgroup$
– Gervenel
8 hours ago
add a comment |
$begingroup$
Do 3 arrays contain a common element, if they contain output it.
For example: [1,2,3], [2,3], [2,4] -> answer = 2
let arr1 = [1, 3, 11, 32, 44, 99];
let arr2 = [4, 12, 15, 99];
let arr3 = [4, 11, 13, 15, 23, 43];
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0;
let j = 0;
while (1)
I will be glad if you give me any tips to improve my code. Thanks in advance.
Sorry, I'm not an English speaker.
javascript array
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
Do 3 arrays contain a common element, if they contain output it.
For example: [1,2,3], [2,3], [2,4] -> answer = 2
let arr1 = [1, 3, 11, 32, 44, 99];
let arr2 = [4, 12, 15, 99];
let arr3 = [4, 11, 13, 15, 23, 43];
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0;
let j = 0;
while (1)
I will be glad if you give me any tips to improve my code. Thanks in advance.
Sorry, I'm not an English speaker.
javascript array
javascript array
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 8 hours ago
Gervenel
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 8 hours ago
GervenelGervenel
234
234
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Gervenel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
$begingroup$
Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say "common element", are you expecting just one answer? What happens if there's more than one? Can there be more than one?
$endgroup$
– Joseph
8 hours ago
$begingroup$
What do you mean by "first" common element? The lowest value? Or some metric involving the three indices?
$endgroup$
– Toby Speight
8 hours ago
$begingroup$
The lowest value
$endgroup$
– Gervenel
8 hours ago
add a comment |
1
$begingroup$
Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say "common element", are you expecting just one answer? What happens if there's more than one? Can there be more than one?
$endgroup$
– Joseph
8 hours ago
$begingroup$
What do you mean by "first" common element? The lowest value? Or some metric involving the three indices?
$endgroup$
– Toby Speight
8 hours ago
$begingroup$
The lowest value
$endgroup$
– Gervenel
8 hours ago
1
1
$begingroup$
Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say "common element", are you expecting just one answer? What happens if there's more than one? Can there be more than one?
$endgroup$
– Joseph
8 hours ago
$begingroup$
Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say "common element", are you expecting just one answer? What happens if there's more than one? Can there be more than one?
$endgroup$
– Joseph
8 hours ago
$begingroup$
What do you mean by "first" common element? The lowest value? Or some metric involving the three indices?
$endgroup$
– Toby Speight
8 hours ago
$begingroup$
What do you mean by "first" common element? The lowest value? Or some metric involving the three indices?
$endgroup$
– Toby Speight
8 hours ago
$begingroup$
The lowest value
$endgroup$
– Gervenel
8 hours ago
$begingroup$
The lowest value
$endgroup$
– Gervenel
8 hours ago
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
Your code assumes that each of the 3 arrays is sorted. Otherwise the < operator would not work. It's ok to assume this. You should have mentioned this in your question.
You use the == operator for comparing the numbers and the lengths. You should better use the === since the == operator considers 0 and "0" equal, which is not good in most cases.
It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for arr3.
I would write the code differently:
function smallestCommonElement(a, b, c)
let i = 0, j = 0, k = 0;
while (i < a.length && j < b.length && k < c.length)
const max = Math.max(Math.max(a[i], b[j]), c[k]);
let n = 0;
while (i < a.length && a[i] < max) i++, n++;
while (j < b.length && b[j] < max) j++, n++;
while (k < c.length && c[k] < max) k++, n++;
if (n === 0)
return a[i];
return null;
The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.
Looking again at your code, there is a bug. Given the arrays [2, 3], [2, 3], [3], your code will return 'No equal number' even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.
It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.
$endgroup$
add a comment |
$begingroup$
Although your code seems to work, it is difficult to read. Loops inside loops and many if, else if blocks and continue or return. Let's start with some big issues:
You use an endless while loop when it is clear you don't have to. The code below would perform the same function:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
for (let k = 0; k < arr3.length; k++)
if (arr1[i] == arr3[k]) return arr1[i];
return 'No equal numbers';
This has one less return 'No equal numbers'; (code repetition) and only one return from within the while loop.
Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found.
There is a handy array method called includes(). It could replace the whole looping of the third array, like this:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
if (arr3.includes(arr1[i])) return arr1[i];
return 'No equal numbers';
By now you can probably guess we don't need the complex while loop at all. We could just loop through array 1 and see if its values are contained in array 2 and 3:
function searchThreeSameNum2(arr1, arr2, arr3)
for (number of arr1)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
The assumption here is that array 1 is properly sorted. If it isn't you can sort it.
function searchThreeSameNum2(arr1, arr2, arr3)
let sorted = arr1.sort((a, b) => a - b);
for (number of sorted)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
Arrays 2 and 3 don't need to be sorted.
In summary
- If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.
- Try not to use complex execution flow constructions, with lot of
else,continueandreturn. They are difficult to read and to debug. - Use the build in array methods, they are very handy, but don't overdo it.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Gervenel is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221724%2fcheck-if-three-arrays-contains-the-same-element%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Your code assumes that each of the 3 arrays is sorted. Otherwise the < operator would not work. It's ok to assume this. You should have mentioned this in your question.
You use the == operator for comparing the numbers and the lengths. You should better use the === since the == operator considers 0 and "0" equal, which is not good in most cases.
It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for arr3.
I would write the code differently:
function smallestCommonElement(a, b, c)
let i = 0, j = 0, k = 0;
while (i < a.length && j < b.length && k < c.length)
const max = Math.max(Math.max(a[i], b[j]), c[k]);
let n = 0;
while (i < a.length && a[i] < max) i++, n++;
while (j < b.length && b[j] < max) j++, n++;
while (k < c.length && c[k] < max) k++, n++;
if (n === 0)
return a[i];
return null;
The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.
Looking again at your code, there is a bug. Given the arrays [2, 3], [2, 3], [3], your code will return 'No equal number' even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.
It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.
$endgroup$
add a comment |
$begingroup$
Your code assumes that each of the 3 arrays is sorted. Otherwise the < operator would not work. It's ok to assume this. You should have mentioned this in your question.
You use the == operator for comparing the numbers and the lengths. You should better use the === since the == operator considers 0 and "0" equal, which is not good in most cases.
It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for arr3.
I would write the code differently:
function smallestCommonElement(a, b, c)
let i = 0, j = 0, k = 0;
while (i < a.length && j < b.length && k < c.length)
const max = Math.max(Math.max(a[i], b[j]), c[k]);
let n = 0;
while (i < a.length && a[i] < max) i++, n++;
while (j < b.length && b[j] < max) j++, n++;
while (k < c.length && c[k] < max) k++, n++;
if (n === 0)
return a[i];
return null;
The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.
Looking again at your code, there is a bug. Given the arrays [2, 3], [2, 3], [3], your code will return 'No equal number' even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.
It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.
$endgroup$
add a comment |
$begingroup$
Your code assumes that each of the 3 arrays is sorted. Otherwise the < operator would not work. It's ok to assume this. You should have mentioned this in your question.
You use the == operator for comparing the numbers and the lengths. You should better use the === since the == operator considers 0 and "0" equal, which is not good in most cases.
It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for arr3.
I would write the code differently:
function smallestCommonElement(a, b, c)
let i = 0, j = 0, k = 0;
while (i < a.length && j < b.length && k < c.length)
const max = Math.max(Math.max(a[i], b[j]), c[k]);
let n = 0;
while (i < a.length && a[i] < max) i++, n++;
while (j < b.length && b[j] < max) j++, n++;
while (k < c.length && c[k] < max) k++, n++;
if (n === 0)
return a[i];
return null;
The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.
Looking again at your code, there is a bug. Given the arrays [2, 3], [2, 3], [3], your code will return 'No equal number' even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.
It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.
$endgroup$
Your code assumes that each of the 3 arrays is sorted. Otherwise the < operator would not work. It's ok to assume this. You should have mentioned this in your question.
You use the == operator for comparing the numbers and the lengths. You should better use the === since the == operator considers 0 and "0" equal, which is not good in most cases.
It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for arr3.
I would write the code differently:
function smallestCommonElement(a, b, c)
let i = 0, j = 0, k = 0;
while (i < a.length && j < b.length && k < c.length)
const max = Math.max(Math.max(a[i], b[j]), c[k]);
let n = 0;
while (i < a.length && a[i] < max) i++, n++;
while (j < b.length && b[j] < max) j++, n++;
while (k < c.length && c[k] < max) k++, n++;
if (n === 0)
return a[i];
return null;
The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.
Looking again at your code, there is a bug. Given the arrays [2, 3], [2, 3], [3], your code will return 'No equal number' even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.
It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.
edited 6 hours ago
answered 6 hours ago
Roland IlligRoland Illig
13.4k12253
13.4k12253
add a comment |
add a comment |
$begingroup$
Although your code seems to work, it is difficult to read. Loops inside loops and many if, else if blocks and continue or return. Let's start with some big issues:
You use an endless while loop when it is clear you don't have to. The code below would perform the same function:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
for (let k = 0; k < arr3.length; k++)
if (arr1[i] == arr3[k]) return arr1[i];
return 'No equal numbers';
This has one less return 'No equal numbers'; (code repetition) and only one return from within the while loop.
Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found.
There is a handy array method called includes(). It could replace the whole looping of the third array, like this:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
if (arr3.includes(arr1[i])) return arr1[i];
return 'No equal numbers';
By now you can probably guess we don't need the complex while loop at all. We could just loop through array 1 and see if its values are contained in array 2 and 3:
function searchThreeSameNum2(arr1, arr2, arr3)
for (number of arr1)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
The assumption here is that array 1 is properly sorted. If it isn't you can sort it.
function searchThreeSameNum2(arr1, arr2, arr3)
let sorted = arr1.sort((a, b) => a - b);
for (number of sorted)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
Arrays 2 and 3 don't need to be sorted.
In summary
- If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.
- Try not to use complex execution flow constructions, with lot of
else,continueandreturn. They are difficult to read and to debug. - Use the build in array methods, they are very handy, but don't overdo it.
$endgroup$
add a comment |
$begingroup$
Although your code seems to work, it is difficult to read. Loops inside loops and many if, else if blocks and continue or return. Let's start with some big issues:
You use an endless while loop when it is clear you don't have to. The code below would perform the same function:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
for (let k = 0; k < arr3.length; k++)
if (arr1[i] == arr3[k]) return arr1[i];
return 'No equal numbers';
This has one less return 'No equal numbers'; (code repetition) and only one return from within the while loop.
Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found.
There is a handy array method called includes(). It could replace the whole looping of the third array, like this:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
if (arr3.includes(arr1[i])) return arr1[i];
return 'No equal numbers';
By now you can probably guess we don't need the complex while loop at all. We could just loop through array 1 and see if its values are contained in array 2 and 3:
function searchThreeSameNum2(arr1, arr2, arr3)
for (number of arr1)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
The assumption here is that array 1 is properly sorted. If it isn't you can sort it.
function searchThreeSameNum2(arr1, arr2, arr3)
let sorted = arr1.sort((a, b) => a - b);
for (number of sorted)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
Arrays 2 and 3 don't need to be sorted.
In summary
- If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.
- Try not to use complex execution flow constructions, with lot of
else,continueandreturn. They are difficult to read and to debug. - Use the build in array methods, they are very handy, but don't overdo it.
$endgroup$
add a comment |
$begingroup$
Although your code seems to work, it is difficult to read. Loops inside loops and many if, else if blocks and continue or return. Let's start with some big issues:
You use an endless while loop when it is clear you don't have to. The code below would perform the same function:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
for (let k = 0; k < arr3.length; k++)
if (arr1[i] == arr3[k]) return arr1[i];
return 'No equal numbers';
This has one less return 'No equal numbers'; (code repetition) and only one return from within the while loop.
Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found.
There is a handy array method called includes(). It could replace the whole looping of the third array, like this:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
if (arr3.includes(arr1[i])) return arr1[i];
return 'No equal numbers';
By now you can probably guess we don't need the complex while loop at all. We could just loop through array 1 and see if its values are contained in array 2 and 3:
function searchThreeSameNum2(arr1, arr2, arr3)
for (number of arr1)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
The assumption here is that array 1 is properly sorted. If it isn't you can sort it.
function searchThreeSameNum2(arr1, arr2, arr3)
let sorted = arr1.sort((a, b) => a - b);
for (number of sorted)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
Arrays 2 and 3 don't need to be sorted.
In summary
- If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.
- Try not to use complex execution flow constructions, with lot of
else,continueandreturn. They are difficult to read and to debug. - Use the build in array methods, they are very handy, but don't overdo it.
$endgroup$
Although your code seems to work, it is difficult to read. Loops inside loops and many if, else if blocks and continue or return. Let's start with some big issues:
You use an endless while loop when it is clear you don't have to. The code below would perform the same function:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
for (let k = 0; k < arr3.length; k++)
if (arr1[i] == arr3[k]) return arr1[i];
return 'No equal numbers';
This has one less return 'No equal numbers'; (code repetition) and only one return from within the while loop.
Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found.
There is a handy array method called includes(). It could replace the whole looping of the third array, like this:
function searchThreeSameNum(arr1, arr2, arr3)
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length)
if (arr1[i] < arr2[j])
i++;
continue;
else if (arr1[i] > arr2[j])
j++;
continue;
else if (arr1[i] == arr2[j])
if (arr3.includes(arr1[i])) return arr1[i];
return 'No equal numbers';
By now you can probably guess we don't need the complex while loop at all. We could just loop through array 1 and see if its values are contained in array 2 and 3:
function searchThreeSameNum2(arr1, arr2, arr3)
for (number of arr1)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
The assumption here is that array 1 is properly sorted. If it isn't you can sort it.
function searchThreeSameNum2(arr1, arr2, arr3)
let sorted = arr1.sort((a, b) => a - b);
for (number of sorted)
if (arr2.includes(number) && arr3.includes(number)) return number;
return 'No equal numbers';
Arrays 2 and 3 don't need to be sorted.
In summary
- If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.
- Try not to use complex execution flow constructions, with lot of
else,continueandreturn. They are difficult to read and to debug. - Use the build in array methods, they are very handy, but don't overdo it.
answered 6 hours ago
KIKO SoftwareKIKO Software
2,586512
2,586512
add a comment |
add a comment |
Gervenel is a new contributor. Be nice, and check out our Code of Conduct.
Gervenel is a new contributor. Be nice, and check out our Code of Conduct.
Gervenel is a new contributor. Be nice, and check out our Code of Conduct.
Gervenel is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221724%2fcheck-if-three-arrays-contains-the-same-element%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
$begingroup$
Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say "common element", are you expecting just one answer? What happens if there's more than one? Can there be more than one?
$endgroup$
– Joseph
8 hours ago
$begingroup$
What do you mean by "first" common element? The lowest value? Or some metric involving the three indices?
$endgroup$
– Toby Speight
8 hours ago
$begingroup$
The lowest value
$endgroup$
– Gervenel
8 hours ago