I am trying to convert a For loop to a Foreach loop for my solution. While For Loop generates me the desired output (see below). Foreach generates the following error:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
public static bool sumOfTwo(int[] a, int[] b, int v)
{
bool result = false;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < b.Length; j++)
{
if (a[i] + b[j] == v)
{
result = true;
}
}
}
return result;
}
and my foreach implementation: What did possibly go wrong?
public static bool sumOfTwo(int[] a, int[] b, int v)
{
bool result = false;
foreach (int i in a)
{
foreach (int j in b)
{
if (a[i] + b[j] == v)
result = true;
}
}
return result;
}
答案 0 :(得分:3)
The difference between them is that for (int i = 0; i < a.Length; i++)
is giving you an Index, while foreach (int i in a)
is giving you the actual value.
E.g.: if you have an array int[] a = {10, 0, 11}
, you'd get the following:
for (int i = 0; i < a.Length; i++)
Console.WriteLine(a[i])
// a[0] = 10
// a[1] = 0
// a[2] = 11
foreach (int i in a)
Console.WriteLine(a[i])
// a[10] = IndexOutOfRangeException
// a[0] = 10
// a[11] = IndexOutOfRangeException
So rather than using Array Accessors in the second bit of code, you should be using the values of i
& j
directly:
....
foreach (int j in b)
{
if (i + j == v)
result = true;
}
....
答案 1 :(得分:1)
You implementation is completely wrong in the foreach
foreach (int i in a)
the i
is the value of the array.
so if a[0]
has a value of 10
but your array size is less than 10, you are literally calling a[10]
in the if statement. You will have out of bound exception
just use
if (i + j == v)
in your if statement should work.
答案 2 :(得分:1)
You can get this down to a one-liner:
public static bool sumOfTwo(int[] a, int[] b, int v)
{
return a.Any(A => b.Any(B => B + A == v));
}
The Any()
method returns true
iff a sequence has any members, or false
otherwise. The rest of the code inside the call to Any()
allows you to filter the sequence on some condition predicate, so you only get true if anything "survives" the filter.
For the condition, we again use the Any()
method with the b
sequence, effectively comparing every possible combination from a
and b
, just as the original code does, and limit the results to items that match our a+b=v
condition. Where()
could work for this, too, but Any()
is better because it will stop at the first match.
I would prefer to use .Intersect()
for this, which could result in code that's easier to understand, but the .Intersect()
requires you to define a whole IEqualityComparer
class rather than a simple delegate.