Leetcode claims that exception is not handled which I handled - c#

I am trying to solve Dynamic Programming questions from leetcode. Started from the easiest ones. Fibonacci. I handled the IndexOutOfRangeException and tried my code with different values on my computer. But when I submit it, leetcode says:
Runtime Error
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
At Solution.Fib(Int32 n)
At __Driver__.Main(String[] args)
Here is the code:
public class Solution
{
public int Fib(int n)
{
int[] table = new int[n + 1];
// Seed the trivial answer.
table[1] = 1;
// Iterate and fill further positions based on current values.
for (int i = 0; i < n; i++)
{
try
{
table[i + 2] = table[i] + table[i + 1];
}
catch (IndexOutOfRangeException ex)
{
// Out of array bounds.
}
}
return table[n];
}
}

Thanks to the people at the comments, I noticed I forgot handle the cases with n<1.
public class Solution
{
public int Fib(int n)
{
if (n < 1)
{
return 0;
}
int[] table = new int[n + 1];
// Seed the trivial answer.
table[1] = 1;
// Iterate and fill further positions based on current values.
for (int i = 0; i < n; i++)
{
try
{
table[i + 2] = table[i] + table[i + 1];
}
catch (IndexOutOfRangeException ex)
{
// Out of array bounds.
}
}
return table[n];
}
}
Thanks to the Klaus from the comments n - 1 instead of n will also avoid the IndexOutOfRangeException exception so I don't have to use try catch anymore.
for (int i = 0; i < n - 1; i++){
table[i + 2] = table[i] + table[i + 1];
}

Your return could be triggering that because it is outside the try/catch. Based on your logic, I don't see how you would actually get IndexOutOfRangeException there, but it could be a code quality scanner that isn't happy.
Another possibility is that because your logic will always get IndexOutOfRangeException within the try/catch, the system is upset because you didn't actually 'handle' the catch, just ignored it.

Related

Look and say sequence

I'm trying to make a look and say sequence ant my code so far only works as it should when I have the 'realCounter' set to 2 or less and don't understand why. Thanks for any help! Here is my main :
string number = "1";
string[] tempStore = new string[2];
int realCounter = 0;
while (realCounter < 2)
{
int counter = 1;
for (int i = 0; i < number.Length; i++)
{
try
{
if (number[i] == number[i + 1])
{
counter++;
}
}
catch
{
tempStore[0] = number[i].ToString();
number = counter.ToString();
number = number + tempStore[0];
}
}
realCounter++;
}
Console.WriteLine(number);
Console.ReadLine();
I've been changing the line with the while loop from realCounter < 2 to realCounter < 3 and the program doesn't perform as it should
It is because you are specifically checking to ensure realCounter < 2 as a condition of your while loop
try
{
if (number[i] == number[i + 1])
{
counter++;
}
}
catch
{
tempStore[0] = number[i].ToString();
number = counter.ToString();
number = number + tempStore[0];
}
You are only updating your number variable when you encounter an exception. You only encounter an exception when number[i + 1] hits an IndexOutOfBounds exception. So you're only updating number with the LAST sequence it encounters, and you're dropping all the rest.

indexOutofRange BubbleSort when using inputbox

Its been bugging me for hours because it is always returning 0 at numbers[i] and I cant figure out the problem. code worked for a different program but I had to change it so it could have a custom array size and that's when everything went wrong.
any help would be great.
Thanks in advance.
int[] numbers = new int[Convert.ToInt16(TxtArray.Text)];
int j = 0;
for (j = numbers.Length; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 1; i++)
{
string NumbersInput = Microsoft.VisualBasic.Interaction.InputBox("Enter Numbers to be sorted",
"Numbers Input", "", -1, -1);
numbers[i] = Convert.ToInt16(NumbersInput);
//returns 0 in if statement
if (numbers[i] < numbers[i + 1])
{
int intTemp = 0;
intTemp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = intTemp;
}
}
}
for (int i = 0; i < numbers.Length; i++)
{
LstNumbers.Items.Add(numbers[i]);
}
private void button1_Click(object sender, EventArgs e)
{
int sizeOfArrayInt = Convert.ToInt32(arraySize.Text);
int[] array = new int[sizeOfArrayInt];
string numbers = arrayValues.Text;
string[] numbersSplit = numbers.Split(',');
int count = 0;
foreach (string character in numbersSplit)
{
int value;
bool parse = Int32.TryParse(character, out value);
if (value != null)
{
array[count] = value;
}
count++;
}
array = this.SortArray(array);
foreach (int item in array)
{
this.listBox.Items.Add(item);
}
}
private int[] SortArray(int[] arrayToSort)
{
//int[] sortedArray = new int[arrayToSort.Length];
int count = arrayToSort.Length;
for (int j = count; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 2; i++)
{
if (arrayToSort[i] < arrayToSort[i + 1])
{
int intTemp = 0;
intTemp = arrayToSort[i];
arrayToSort[i] = arrayToSort[i + 1];
arrayToSort[i + 1] = intTemp;
}
}
}
return arrayToSort;
}
strong text
This I got to work as a Windows Form and the output displays in the list box as each array item or individual i iteration over the array. Of course there is no error checking. Hope that helps.
Setting aside the strangeness of how you are working with text boxes, your problem with throwing an exception would happen even without them because it lies here, in your inner loop:
for (i = 0; i <= j - 1; i++)
Suppose that numbers.Length == 2. This means that j == 2. So on the first time through the outer loop, you hit the inner loop with these conditions. The first time through, i == 0. You get to the if statement:
if (numbers[i] < numbers[i + 1])
numbers[0] exists, and numbers[1] exists, so this iteration goes through fine and i is incremented.
Now i == 1. Now the loop checks its boundary condition. i <= j - 1 == true, so the loop continues. Now when you hit that if statement, it tries to access numbers[i + 1], i.e., numbers[2], which does not exist, throwing an IndexOutOfRangeException.
Edit: Came back and realized that I left out the solution (to the exception, anyway). For the bubble sort to work, your inner loop's boundary condition should be i <= j - 2, because j's initial value is == numbers.Length, which is not zero-based, while array indexes are.
Second Edit: Note that just using a List won't actually solve this problem. You have to use the right boundary condition. Trying to access list[list.Count()] will throw an ArgumentOutOfRangeException. Just because a List will dynamically resize doesn't mean that it will somehow let you access items that don't exist. You should always take time to check your boundary conditions, no matter what data structure you use.

Catch block does not catch exception, why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am coding a rogue-like console program but I have a question:
My code does not catch an exception. I have a void with for loops and arrays.
The error happens when the array is out of range. This happens because the void doesn't check if the array is bellow zero or over the maximum.
void lightUp(int pos)
{
//first and second
for (int i = 1; i > -2; i--)
{
int lolPos = pos + (i * columns);
for (int j = 0; j < 8; j++)
{
tiles[lolPos + j].isVisible = true;
tiles[lolPos - j].isVisible = true;
}
}
//third
for (int i = 2; i > -3; i -= 4)
{
int lolPos = pos + (i * columns);
for (int j = 0; j < 7; j++)
{
tiles[lolPos + j].isVisible = true;
tiles[lolPos - j].isVisible = true;
}
}
//fourth
for (int i = 3; i > -4; i -= 6)
{
int lolPos = pos + (i * columns);
for (int j = 0; j < 6; j++)
{
tiles[lolPos + j].isVisible = true;
tiles[lolPos - j].isVisible = true;
}
}
//fifth
for (int i = 4; i > -5; i -= 8)
{
int lolPos = pos + (i * columns);
for (int j = 0; j < 5; j++)
{
tiles[lolPos + j].isVisible = true;
tiles[lolPos - j].isVisible = true;
}
}
for (int i = 5; i > -6; i -= 10)
{
int lolPos = pos + (i * columns);
for (int j = 0; j < 3; j++)
{
tiles[lolPos + j].isVisible = true;
tiles[lolPos - j].isVisible = true;
}
}
}
So I made a catch block, in case the error happens my progam does not crash.
try
{
lightUp(player);
}
catch { }
But, I am still getting IndexOutOfRange exceptions. They get not trapped by the catch block.
Why is that?
EDIT:
Thanks for all the answers. Thought, the problem does not lie in the debug mode options.
I figured out that this only happens when the program starts. I tested if I just walk to "out of range" (The void lights-up the tiles near the player), the catch block does actually work. But not when I start my program.(The position of the player is random, if it is near the side of the left screen, the exception happens at startup.)
ANOTHER EDIT: I fixed the "magic numbers"(not bellow zero and not over the maximum),
and that will always work, no matter what happens to it.
Do you want to try this one:
public void lightUp(int pos)
{
int loopcounter = -2;
int jcount = 8;
int stepcount=1;
int stepcountReflected=0;
try
{
for (int x = 1; x > -6; x--)
{
if (x == 1)
{
stepcountReflected=0.5*stepcount;
}
else
{
stepcountReflected = stepcount;
}
for (int i = stepcount; i > loopcounter; i =- (2 * stepcountReflected))
{
int lolPos = pos + (i * columns);
for (int j = 0; j < jcount; j++)
{
tiles[lolPos + j].isVisible = true;
tiles[lolPos - j].isVisible = true;
}
}
loopcounter = loopcounter - 1;
jcount = jcount - 1;
}
}
catch (Exception ex)
{
// do what yo need to do here
}
}
Currently you are attempting to catch exception outside of your sub/function and that is why you are not getting solid error description.
When you put none specific "Exception" instead of very specialized "StackOverflowException" you will see what and where is giving you headache.
Adding recorded log of line by line activity may help you as well but this is way outside of your question, just what I would do.
Check in VS whether you don't have the option to break on exceptions checked (keyboard shortcut: ctrl+d, e):
http://truncatedcodr.wordpress.com/2011/04/04/visual-studiodebugexceptions/
The row "Common Language Runtime Exceptions" is relevant here.
Two things beside the exception problem I can see:
There is too much code in that method. It will be hard to test and if it fails, hard to figure out why - which is what you are seeing now.
The code looks like c/p with a few corrections, so you would properly be better of abstracting so it. This will make it easier to change later, and less code. Less code is almost always good.
The problem you are facing is that you have to specifiy what error you want to catch, and do the necessary error handling. It is customary to not catch all exception(Exception class) because that will make it even harder to debug. It is evil!

bubble sort and foreach index

I have some code below for a button click event,
which uses bubble sort. I am a little bit unclear
of the use. Trying to sort an array in ascending
order. Also I have to use a foreach and need to
get an index from it some how.
An attempt int z = a.GetEnumerator(); does not work. int k = 0;//Cheat to get code working
int k = 0;//Cheat to get code working
foreach (BankAccount BankAccount in a)
//for (int i = 0; i < a.Length; i++)
{
//int z = a.GetEnumerator();
lstBefore.Items.Add(a[k].show());
k += 1;//Cheat to get code working
}
//if (a[0] is IComparable)
//{
//Sort.BubbleSort(a);//Sort a
k = 0;//Cheat to get code working
for (int i = 0; i < a.Length; i++)
{
lstAfter.Items.Add(a[k].show());
//else MessageBox.Show("unable to sort");
k += 1;//Cheat to get code working
}
//}
//else MessageBox.Show("unable to sort");
class Sort : IComparable
{
public static void BubbleSort(IComparable[] arr)
{
bool swap = true;
IComparable temp;
for (int i = 0; swap; i++)
{
swap = false;
for (int j = 0; j < (arr.Length - (i + 1)); j++)
{
//int test = arr[j].CompareTo(arr[j + 1]);
if (arr[j].CompareTo(arr[j + 1]) > 0)
//If this balance is < than next balance
{
temp = (IComparable)arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swap = true;
}
}
}
}
}
Also I have
public class BankAccount : IComparable, IComparable<BankAccount>//Class BackAccount - //Icomarable
{
private decimal balance;
private string FullName;
//...
public int CompareTo(BankAccount that)//Compare To
{
if (this.balance > that.balance) return -1;//If this balance is > than next balance
if (this.balance == that.balance) return 0;//If this balance is = to next balance
return 1;//If this balance is < than next balance
//return this.balance.CompareTo(that.balance);
}
}
Thanks,
Looks like you just need to implement CompareTo in your Sort class (not just the BankAccount class).
First, a foreach does not have an index in any way. If you need a index, use a for loop.
Second, The Sort class have not to implement IComparable (which causes the error). It's a Comparer, not compared. It can implement IComparer if you want to, or to be static.
And why do you diving into bubble sort implementation, when you have Array.Sort or List.Sort methods, that implements QuickSort and is sure faster and better? I would avoided this.

Bubble Sorting not Giving Correct Result Code Attached C#?

My sorting code not giving correct result it is not sortint the given list properly while i am not getting the error please check it,
static void Main(string[] args)
{
List<int> a = new List<int>(new int[] { 3, 7, 6, 1, 8, 5 });
int temp;
// foreach(int i in a)
for(int i=1; i<=a.Count; i++)
for(int j=0; j<a.Count-i; j++)
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
Console.WriteLine(a[j]);
}
Console.Read();
}
i could not understand your code and i do not know C#. But anyways, here is the sorting logic for bubble sort (written in c).
//assuming there are n elements in the array a[]
for(i=0; i<n; i++)
{ for(j=1; j<n-i; j++)
{ if(a[j] < a[j-1])
{ temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
and you can also refer to:
www.sorting-algorithms.com/bubble-sort
What you posted is not a implementation of the Bubble Sort algorithm. You forgot to loop while no number is swapped anymore. Here is a Bubble Sort implementation written by John Skeet. The stillGoing check is what at least is missing in your implementation:
public void BubbleSort<T>(IList<T> list);
{
BubbleSort<T>(list, Comparer<T>.Default);
}
public void BubbleSort<T>(IList<T> list, IComparer<T> comparer)
{
bool stillGoing = true;
while (stillGoing)
{
stillGoing = false;
for (int i = 0; i < list.Length-1; i++)
{
T x = list[i];
T y = list[i + 1];
if (comparer.Compare(x, y) > 0)
{
list[i] = y;
list[i + 1] = x;
stillGoing = true;
}
}
}
}
remove the console.write from the nested loops. place console.write outside the nested loops in a new for loop or foreach.
then you will get the correct order. otherwise, the logic of bubble sort is correct

Categories

Resources