Why do I get the error 'unreachable code detected'? - c#

using System;
namespace G09 {
class Reverse {
static void Main()
{
Console.WriteLine(ReverseText(24));
Console.ReadKey();
}
static string ReverseText(int n) {
if (n < 1)
{
return "";
}
string index = "1";
string revIndex = "";
int count = 1;
string[] arr = new string[n];
for (int i = 0; i < n; i++)
{
arr[i] = index + revIndex;
for (int j = 0; j <= i; j++)
{
if (count > 8)
{
index = index + 0;
count = 0;
break;
}
index = index + (count++ + 1).ToString();
break;
}
revIndex = "";
for (int k = index.Length - 1; k >= 0; k--)
{
if (k == index.Length - 1)
{
continue;
}
revIndex += index[k];
}
}
return string.Join("\n", arr);
}
}
}
/tmp/csharp117013-18-5s54om.vh6mt2o6r/code.cs(10,41): warning CS0162:
Unreachable code detected
Can anyone tell me why this code is unreachable on line 23??
I can not understand... In visual studio it works fine, but in other shows error.

The j++ is pointless because of the break at the end, remove one of both
for (int j = 0; j <= i; j++) {
...
break;
}

You will never increment j because you break the iteration after the first loop
for (int j = 0; j <= i; j++) //<- Error here, j++ will never be reached
{
if (count > 8)
{
index = index + 0;
count = 0;
break;
}
index = index + (count++ + 1).ToString();
break; //you leave the for loop here
}

Your issue is with this for loop:
for (int j = 0; j <= i; j++) {
if (count > 8) {
index = index + 0;
count = 0;
break;
}
index = index + (count++ + 1).ToString();
break;
}
I'm guessing the for loop starts on line 23. Because you have all paths inside the for loop containing break statements the j++ part of the for loop will never be hit. The loop will execute once and break out before ever hitting the increment for variable j.

Related

How to Break a For Loop From an If Statement Inside the Loop (C#)

I am working on an A* Pathfinding method that uses a custom class instead of nodes, but am having issues with my loops. The first for loop using int i is able to go up to 3 (Player1.instance.movement = 3), but I need to use an if statement inside of that loop to check if the target position has already been found. I am wondering if it is possible to break my for loop when my If statement is false.
public void GetNeighbors(Tile originTile)
{
Tile originalTile = originTile;
nextTile.Clear();
int minX = 0;
int minY = 0;
var originCostFunc = Mathf.Infinity;
for (int i = 0; i < Player1.instance.movement; i++)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x != y && y != x)
{
var costX = Mathf.Abs((originTile.transform.position.x + x) - originalTile.transform.position.x);
var costY = Mathf.Abs((originTile.transform.position.y + y) - originalTile.transform.position.y);
var distanceX = Mathf.Abs(targetPos.transform.position.x - (originTile.transform.position.x + x));
var distanceY = Mathf.Abs(targetPos.transform.position.y - (originTile.transform.position.y + y));
var costFunc = costX + costY + distanceX + distanceY;
if (costFunc <= originCostFunc)
{
originCostFunc = costFunc;
minX = x;
minY = y;
Debug.Log($"x: {x}, y: {y}");
}
}
}
}
nextTile.Add(GridManagerHandPlaced.instance.GetTileAtPosition(new Vector2(originTile.transform.position.x + minX, originTile.transform.position.y + minY)));
if (nextTile[i] != targetPos)
{
originTile = nextTile[i];
}
else
{
break;
}
}
DisplayPath();
}
You can break loop several times by condition.
bool breakLoop = false;
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
for (int k = 0; k < length; k++)
{
breakLoop = nextTile == target;
if (breakLoop)
break;
}
if (breakLoop)
break;
}
if (breakLoop)
break;
}
Or move search logic to separated method and return a value from any number of nested loops
string path = FindPath();
Display(path);
string FindPath()
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
for (int k = 0; k < length; k++)
{
if (nextTile == target)
return nextTile;
}
}
}
return null;
}
Never use goto operator.
This is one of the few valid cases where I'd use goto. In-fact, this is the example given in the docs for when it should be used.
void CheckMatrices(Dictionary<string, int[][]> matrixLookup, int target)
{
foreach (var (key, matrix) in matrixLookup)
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == target)
{
goto Found;
}
}
}
Console.WriteLine($"Not found {target} in matrix {key}.");
continue;
Found:
Console.WriteLine($"Found {target} in matrix {key}.");
}
}
Note the syntax for the label is simply myLabel: and you can place it anywhere in procedurally executable code.
For sake of covering other ways of handling this situation, here is the boolean solution.
bool breakLoops = false;
for (int i = 0; i < length1; i++)
{
for (int ii = 0; ii < length2; ii++)
{
for (int iii = 0; iii < length3; iii++)
{
if (breakingCondition)
{
breakLoops = true;
break;
}
}
if (breakLoops) break;
}
if (breakLoops) break;
}
Simple and straightforward, but requires a break condition check at the end of each loop that you want to break out of.

How to fix this implementaion of the Merge Sort in c#

I've read the CLRS and tried to implement the recursive merge sort algorithm . cant see what the error is but everytime i run it gives me an "Index out of bounds error "
i've been trying for 5h now
static public void MergeSort(int[] input, int IndexStanga, int IndexDreapta)
{
if (IndexStanga < IndexDreapta)
{
int IndexMijloc = (IndexDreapta + IndexStanga) / 2;
MergeSort(input, IndexStanga, IndexMijloc);
MergeSort(input, IndexMijloc + 1, IndexDreapta);
Merge(input, IndexStanga, IndexDreapta, IndexMijloc);
}
}
static public void Merge(int[] input, int stanga, int dreapta, int mijloc)
{
int lungDR = 0;
int lunST = 0;
lungDR = dreapta - mijloc;
lunST = mijloc - stanga + 1;
int[] valDreapta = new int[lungDR + 1];
int[] valStanga = new int[lunST + 1];
valDreapta[valDreapta.Length - 1] = int.MaxValue;
valStanga[valStanga.Length - 1] = int.MaxValue;
int i = 0;
int j = 0;
for (i = stanga; i <= mijloc; i++) valStanga[i] = input[i];
for (i = 0; i < lungDR; i++) { valDreapta[i] = input[i + mijloc + 1]; }
i = 0;
j = 0;
for (int k = 0; k < input.Length; k++)
{
if (valStanga[i] <= valDreapta[j]) //error out of bounds
{
input[k] = valStanga[i];
i++;
}
else
{
input[k] = valDreapta[j];
j++;
}
}
}
Fixes noted in comments below. First fix for moving data from input to valStanga. Second fix for the range on merging back to input. The parameters for merge are in an unusual order, first, last, middle. Normally the order is first, middle, last.
Comments: The program will have issues if the array to be sorted contains elements equal to max integer. It would be more efficient to do a one time allocation of a working array, rather than allocate new sub-arrays on every call to merge. The copy operations can be avoided by changing the direction of merge with each level of recursion.
int i = 0;
int j = 0;
for (i = 0; i < lungDR; i++) { valDreapta[i] = input[i + mijloc + 1]; }
for (i = 0; i < lunST; i++) { valStanga[i] = input[i + stanga]; } // fix
i = 0;
j = 0;
for (int k = stanga; k <= dreapta; k++) // fix
{
if (valStanga[i] <= valDreapta[j])

C#, Windows application, draw a square with side N

for school practice I have to make a windows application in C# that takes a input number and draws a square of X's with side N. I have to do it with a loops and i can't use any preset commands. (For example math.pow i cannot use) (I've included a picture of the assignment.) I've already mode this program in a console application and there it worked fine.
I think that i'm very close of solving it but can't figure out what the last step is. I would love to know what i'm missing and how i should solve this.
See the assignment
This is my code now:
int n;
n = int.Parse(txt_input.Text);
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text = "X";
lbl_output.Text = "\n";
}
//middel part
for (int i = 0; i < n - 2; i++)
{
lbl_output.Text = "X";
for (int j = 0; j < n - 2; j++) lbl_output.Text = " ";
lbl_output.Text = "X";
lbl_output.Text = "\n";
}
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text = "X";
lbl_output.Text = "\n";
}
Try this:
int n = int.Parse(txt_input.Text);
var sb = new StringBuilder();
for (int j = 0; j < n; j++)
{
sb.Append('X');
}
sb.AppendLine();
for (int i = 0; i < n - 2; i++)
{
sb.Append('X');
for (int j = 0; j < n - 2; j++)
{
sb.Append(' ');
}
sb.Append('X');
sb.AppendLine();
}
for (int j = 0; j < n; j++)
{
sb.Append('X');
}
lbl_output.Text = sb.ToString();
Try this;
int n = int.Parse(txt_input.Text);
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text += "X";
}
lbl_output.Text += "\n";
//middel part
for (int i = 0; i < n - 2; i++)
{
lbl_output.Text += "X";
for (int j = 0; j < n - 2; j++)
lbl_output.Text += " ";
lbl_output.Text += "X";
lbl_output.Text += "\n";
}
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text += "X";
}
You forget to use += which will append the text with the previous assigned text. Also you had some unnecessary new lines in your code.
Need to append to the string. There's a couple ways of doing this. Tho '+=' should work fine. += is short for variable = variable + newValue
int n = int.Parse(txt_input.Text);
string output = "";
for(int x = 0; x < n; x++) //rows
{
if (x == 0 || x == n-1) //first / last row all x
for(int y = 0; y < n; y++)
{
output += "x";
}
else //other rows
for(int y = 0; y < n; y++)
{
output += (y == 0 || y == n - 1) ? "x" : " "; //if first or last column "X" else " "
}
output += "\n"; //at the end of each row a return
}
lbl_output.Text = output;
You can see it run in the browser here: https://dotnetfiddle.net/wiYfjX
Use two loops. One for the width of the square and one for the height of the square.
Give this a try and replace the parameter from what is in the txt_input control. (Just place the function whereever you want in your code (button_click for example) instead of the form load.
private void Form1_Load(object sender, EventArgs e)
{
lblOutput.Text = GenerateSquare(5);
}
private string GenerateSquare(int n)
{
string square = "";
for (int w = 0; w < n; w++)
{
for (int h = 0; h < n; h++)
{
// top or bottom line
if (w == 0 || w == n - 1)
{
square += "x";
}
else // sides
{
if (h == 0 || h == n - 1)
{
square += "x";
}
else square += " ";
}
// change line
if (h == n - 1)
square += "\n";
}
}
return square;
}

How do I set the debugger to catch what changed the variable

I am implementing the NEH algorithm following this slide and video:
http://mams.rmit.edu.au/b5oatq61pmjl.pdf
https://www.youtube.com/watch?v=TcBzEyCQBxw
My problem during the test is the variable Sorted_list got changed which cause different results from what I expect:
This the portion where I have the problem but I couldn't know what it changes it(I used breakpoints and watch variable window):
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
Complete implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FINAL_NEH
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("entre the nmbr of jobs : ");
string row = Console.ReadLine();
Console.WriteLine("entre the nmbr of machines : ");
string column = Console.ReadLine();
int job = int.Parse(row.ToString());
int machine = int.Parse(column.ToString());
List<int[]> list = new List<int[]>();
// read the nmbrs and put it in list-----------------------------------------------------
for (int i = 0; i < job; i++)
{
list.Add(new int[machine + 1]);
for (int j = 0; j < machine; j++)
{
list[i][j] = int.Parse(Console.ReadLine());
}
list[i][list[i].Length - 1] = int.Parse((i + 1).ToString()); //Last Elemnt Is Job Number-
}
// show the list----------------------------------------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// sort the list------------------------------------------------------------------------------
for (int i = 0; i < list.Count; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
int sumI = 0, sumJ = 0;
for (int a = 0; a < list[i].Length - 1; a++)
{
sumI += list[i][a];
}
for (int a = 0; a < list[j].Length - 1; a++)
{
sumJ += list[j][a];
}
if (sumI < sumJ)
{
int[] temp = new int[int.Parse(job.ToString())];
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
Console.Write("\n\n-----------------after sorting ------------------------------------\n\n");
// shaw the list after sorting------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// clculate the maxpane of the first 2 jobs---------------------------------------
List<int[]> initMaxpane = new List<int[]>();
initMaxpane.Add((int[])list[0].Clone());
initMaxpane.Add((int[])list[1].Clone());
// calculer maxspan of first jobs..............................................
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane[0][0] = list[i][j];
else if (i == 0)
initMaxpane[0][j] = (int)(initMaxpane[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane[i][0] = (int)(initMaxpane[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane.Count; i++)
{
for (int j = 1; j < initMaxpane[i].Length - 1; j++)
{
if ((initMaxpane[i][j - 1] > initMaxpane[i - 1][j]))
initMaxpane[i][j] = (int)(initMaxpane[i][j - 1] + list[i][j]);
else
initMaxpane[i][j] = (int)(initMaxpane[i - 1][j] + list[i][j]);
}
}
int Cmax = initMaxpane[initMaxpane.Count - 1][initMaxpane[initMaxpane.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane offirst jobs----------");
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> initMaxpane2 = new List<int[]>();
initMaxpane2.Add(list.ElementAt(1));
initMaxpane2.Add(list.ElementAt(0));
// calculer maxspan of first jobs reverse..............................................
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane2[0][0] = list[i][j];
else if (i == 0)
initMaxpane2[0][j] = (int)(initMaxpane2[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane2[i][0] = (int)(initMaxpane2[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane2.Count; i++)
{
for (int j = 1; j < initMaxpane2[i].Length - 1; j++)
{
if ((initMaxpane2[i][j - 1] > initMaxpane2[i - 1][j]))
initMaxpane2[i][j] = (int)(initMaxpane2[i][j - 1] + list[i][j]);
else
initMaxpane2[i][j] = (int)(initMaxpane2[i - 1][j] + list[i][j]);
}
}
int Cmax2 = initMaxpane2[initMaxpane2.Count - 1][initMaxpane2[initMaxpane2.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane of first jobs (reverse)----------");
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane2[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> MaxpaneList = new List<int[]>();
if (Cmax > Cmax2)
{
MaxpaneList.Add((int[])list[1].Clone());
MaxpaneList.Add((int[])list[0].Clone());
}
else
{
MaxpaneList.Add((int[])list[0].Clone());
MaxpaneList.Add((int[])list[1].Clone());
}
List<int[]> bestSequenceList = null;
List<int[]> kmsList = null;
List<int[]> Sorted_list = list.ToList();
int bestCma = 0;
//int maxspan = 0;
for (int jo = 2; jo < job; jo++)
{
for (int ins = 0; ins <= MaxpaneList.Count; ins++)
{
MaxpaneList.Insert(ins, list[jo]);
kmsList = MaxpaneList.ToList();
int Cma = 0;
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
for (int i = 1; i < kmsList.Count; i++)
{
for (int j = 1; j < kmsList[i].Length - 1; j++)
{
if ((kmsList[i][j - 1] > kmsList[i - 1][j]))
kmsList[i][j] = kmsList[i][j - 1] + Sorted_list[i][j];
else
kmsList[i][j] = kmsList[i - 1][j] + Sorted_list[i][j];
}
}
Cma = kmsList[kmsList.Count - 1][kmsList[kmsList.Count - 1].Length - 2];
Console.WriteLine("\n\n\n------- the maxpane sequence ----------");
for (int i = 0; i < MaxpaneList.Count; i++)
{
for (int j = 0; j < MaxpaneList[i].Length; j++)
{
Console.Write("\t" + "[" + MaxpaneList[i][j] + "]");
}
Console.WriteLine();
}
Console.WriteLine("MAX : " + Cma + "\n\n\n");
if (ins == 0)
{
bestCma = Cma;
}
if (jo == 2 && ins == 0)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
else
{
if (bestCma > Cma)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
}
MaxpaneList.RemoveAt(ins);
}
MaxpaneList = bestSequenceList.ToList();
}
Console.ReadLine();
}
}
}
The issue lies in the following code (snippet):
List<int[]> Sorted_list = list.ToList();
ToList will create a new list, but because in this case int[] is a reference type then the new list will contain references to the same arrays as the original list.
Updating a value (of an array) referenced in the new list will also affect the equivalent value in the original list.
kmsList[0][0] = Sorted_list[0][0];
The solution is to create a real copy of 'list' and its items (in this case int[]):
List<int[]> Sorted_list = list.ConvertAll(myArray => (int[])myArray.Clone());
This piece of code clones all arrays within the list to a new variable Sorted_list.
A useful link that explains the difference between value and reference types is: https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
Reference Types
A reference type contains a pointer to another memory location that holds the data.
Reference types include the following:
String
All arrays, even if their elements are value types Class
types, such as Form
Delegates
When you create a List<> (or any other container) from another container (as you do when you call list.ToList()) you do not create copies of all of the elements in the container. You create new references to the items in the list that you're copying. In CS parlance it's a shallow copy and not a deep copy.
So, if you do this:
int[] ia = new[] {0, 1, 2, 3, 4};
int[] ib = new[] {5, 6, 7, 8, 9};
List<int[]> la = new List<int[]>() { ia, ib };
List<int[]> lb = la.ToList();
Both lists refer to the same two arrays, and if you change one array like this:
la[1][4] = 10;
Then lb[1][4] will also be 10 because the two lists each contain the same arrays. Copying the list does not copy the elements in the list.

To solve upside-down rendering?

I have written this segment of C# to help me understand how nested for loops can be used to render 2 dimensional data.
Here is what the output looks like.
████
███
██
█
I would like to make it so that the 4 blocks up top are rendered at the bottom, basically in the reverse order so that the steps ascend. However the console window only renders downward, so the conventional thinking won't be right. The following is my code.
static void Main(string[] args)
{
int i = 0;
int j = 0;
for (i = 0; i < 4; i++)
{
Console.Write('\n');
for (j = i; j < 4; j++)
{
Console.Write("█");
}
}
Console.ReadKey();
}
This is what I'd like the output to look like.
█
██
███
████
You need to reverse your loop condition from inremant to decremant..
for (i = 0; i < 4; i++)
{
Console.Write('\n');
for (j = i; j >= 0; j--)
{
Console.Write("█");
}
}
Output will be;
Here is a DEMO.
UPDATE: Since you change your mind, you need to add space every column (column number isi) 4 - 1 times.
public static void Main(string[] args)
{
int i = 0;
int j = 0;
for ( i = 0; i < 4; i++ )
{
for ( j = 0; j < 4; j++ )
{
if ( j < 3 - i )
Console.Write(" ");
else
Console.Write("█");
}
Console.Write('\n');
}
Console.ReadKey();
}
Here is a DEMO.
class Program
{
const int Dimension = 4;
static void Main(string[] args)
{
char[] blocks = new char[Dimension];
for (int j = 0; j < Dimension; j++)
blocks[j] = ' ';
for (int i = 0; i < Dimension; i++)
{
blocks[Dimension - i - 1] = '█';
for (int j = 0; j < Dimension; j++)
Console.Write(blocks[j]);
Console.WriteLine();
}
Console.ReadKey();
}
}
Should be:
for (j = 3 - i; j < 4; j++)
{
Console.Write("█");
}
The easiest way would be: just reverse your inner loop condition and decrement the counter instead of incrementing it:
for (i = 0; i < 4; i++)
{
Console.Write('\n');
for (j = i; j >= 0; j--)
{
Console.Write("█");
}
}
Console.ReadKey();
returning:
█
██
███
████
And for right-to-left version:
for (i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
if(j < 3 - i)
Console.Write(" ");
else
Console.Write("█");
}
Console.Write('\n');
}
Console.ReadKey();
with a result:
█
██
███
████

Categories

Resources