Reputation: 13955
Came across this question / quiz as something that might be asked in an interview. Not seeing how to do this...
You have two arrays full of random numbers and each array has a number that they share. Find the number and output the number. (NOTE: Do not use IF Statements)
Upvotes: 0
Views: 123
Reputation: 1911
I had similar experience but I had to use procedural programming to find out if I can think of more than one way to solve the puzzle.
Here is code achievable with while loop:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int x = 0;
int y = 0;
while (x < array1.Length)
{
y=0;
while (y < array2.Length)
{
while (array1[x] == array2[y])
{
Console.WriteLine(String.Format("Matching number is {0}", array1[x]));
break;
}
y++;
}
x++;
}
Above code will print all matches. To get only first match you can use goto
to get out of these loop.
Best advise, learn if you have any idea what you can expect learn all possible ways to do something. You never can know too much.
Upvotes: 1
Reputation: 18775
What they are examining is your ability to do functional programming (as opposed to procedural). As stated by several answers, you can use LINQ to intersect two lists.
The other answers aren't quite complete; you were also told
In the spirit of quasi-functional programming you ought to do this in one statement without loops or explicit conditionals:
int[] a = { 1, 2, 3 };
int[] b = { 3, 4, 5 };
Console.WriteLine(a.Intersect(b).Single());
This could be more robust, eg
Console.WriteLine(a.Intersect(b).FirstOrDefault());
This won't barf when there are zero or multiple elements in the intersection, but strictly speaking these fail to report violation of preconditions - there should be exactly one match, anything else should produce an exception.
Upvotes: 1
Reputation: 6455
Well you may want to take a look at Intersect extension method.
A little bit example here:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
// get the shared number(s)
var intersect = array1.Intersect(array2);
foreach (int val in intersect)
{
Console.WriteLine(val);
}
Upvotes: 1