In: Computer Science
Using JavaScript for the following assignment
Design and code a function named "intersection" that
takes two arrays of numbers in parameter and returns a new
array containing only the values that are both in the
two arrays. A value must not be found more than once in
the resulting array but can be found more than once in
the arrays in parameter. The order of the elements in the resulting array
must respect the order of the first parameter. For example :
intersection ([3, 1, 4, 1, 5], [2, 4, 4, 3])
must return [3, 4].
You also need to design and code a unit test function and
call it. To test that the result of
intersection ([3, 1, 4, 1, 5], [2, 4, 4, 3])
which returns [3, 4], you can use a test like this:
assert (intersection ([3, 1, 4, 1, 5], [2, 4, 4, 3]) == "3,4");
This works because the == operator does the automatic conversion
from arrays to text (if one of the two operands are a text).
Code:
<!DOCTYPE html>
<html>
<head>
<script>
function intersection(arr1,arr2) //function which is taking two
arrays as input
{
var result=[]; //result array for storing resultant elements
var k=0;
for (var i = 0; i < arr1.length; i++) //iterate loop from 0 to
length of array1
{
for (var z = 0; z < arr2.length; z++) //iterate loop from 0 to
length of array2
{
if ((arr1[i]==arr2[z])) //if elements are equal
{
if
(result.includes(arr1[i])==true) // if the elements are already
present in result break the loop
break;
else
{
result[k]=arr1[i]; //otherwise put element in
result array
k=k+1; //increment k value
}
}
}
}
for (i=0;i<result.length;i++)
document.writeln(result[i]); //print the result
list in page
return result;
//return the result array
}
var arr1 = [3, 1, 4, 1, 5];
var arr2 = [2, 4, 4, 3]; //declaration of two arrays
var res=intersection (arr1,arr2); // calling intersection()
function and storing returned result in res
console.assert (res ==
"3,4",'Intersection Elements are wrong'); //finally writing
assert() to check intersection elements is correct or not.
</script>
</head>
<body>
</body>
</html>
Code and Output Screenshots:
Note: assert gives error when expression is false so when the returned elements is 3,4 it will not print anything
in second code we are writing assert(res==3,1) it is false so it prints intersection elements are wrong.
Note: if you have any queries please post a comment thanks a lot..always available to help you...