-1

i was trying to solve problem related to prefix sum. In which array is given

var nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

and we have to find Sum of each elements in range a, b inclusive

function is giving System.IndexOutOfRangeException

I Tried to solve this ways.

int[] pre;
NumArray(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

Console.WriteLine(SumRanges(0,2));
Console.WriteLine(SumRange(0,2));
void NumArray(int[] nums)
{
    pre = new int[nums.Length];
    pre[0] = nums[0];
    for (var i = 1; i < nums.Length; i++)
    {
        pre[i] += pre[i - 1] + nums[i];
    }
}
int SumRange(int left, int right)
{
    return pre[right] - left >= 1 ? pre[left - 1] : 0;
}
int SumRanges(int left, int right)
{
    int l = left >= 1 ? pre[left - 1] : 0;
    return pre[right] - l;
}

My Question is Why below function is giving System.IndexOutOfRangeException

int SumRange(int left, int right)
{
    return pre[right] - left >= 1 ? pre[left - 1] : 0;
}

but below equation won't give System.IndexOutOfRangeException

int SumRanges(int left, int right)
{
    int l = left >= 1 ? pre[left - 1] : 0;
    return pre[right] - l;
}

i just only stored in variable, i am not getting why it is?

Please help me.

2 Answers2

2

With the call SumRange(0,2) the argument left will be 0.

And if pre[right] - left >= 1 is true then you use pre[left - 1].

So if the condition is true then you use pre[-1].


With left >= 1 ? pre[left - 1] : 0; you first check to make sure that left is larger than 0, so pre[left - 1] will not use a negative index.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

First, those two method's logics are different I guess you think they are same

For this one

pre[right] - left >= 1 ? pre[left - 1] : 0;

the execution sequence is like this

(pre[right] - left >= 1) ? pre[left - 1] : 0;

It will compute the result of (pre[right] - left >= 1) first then execute others logic and you can change it to

return pre[right] - (left >= 1 ? pre[left - 1] : 0);

then they will be same

MichaelMao
  • 2,596
  • 2
  • 23
  • 54