How to reset or restart nested loops - c#

loop one
{
looptwo
{
if(condition=true)
{
reset values//restart both loops
}
}
}
and possibilities for reset values is 3
basically i want to compair two matrices
a= 1 2 3 4
1 2 3 4
b= 3 4 5 6
4 6 7 8
and when row 1 of a[] is matched with row 1 of b[].....i will add these rows and a[]
become = 2 4 6 8
for(i=0;i<rows;i++)
for(j=0;j<columns;j++)
{
a[i]=a[i]+b[i,j]
}
and again find my maches from restart with new a[] Matrix
and i have to insure that all rows of b[] matrix are checked with a[] which are 3 in this case

You have to use goto to break out of multiple loop levels in C#. For example:
RESTART:
while (a) {
while (b) {
if (that_other_thing)
goto RESTART;
}
}
Well, you don't have to use goto but the alternative might be using a bunch of flag variables to indicate that a restart is required. And that code will probably be pretty hard to follow.

The best choice here is to move the loops into their own method, and return from inside the inner loop. Example:
public void MyMehod(){
loop one{
looptwo{
if(condition=true){
return;
}
}
}
}
If this is not possible for some reason, you can use a bool value that you set in the inner loop to bail out of all of them, but this is a bit more messy:
bool endloop = false;
while(!endloop){
while(!endloop){
if(condition){
endloop = true;
}
}
}
For a while loop it looks ok, but even more messy for a for loop or a foreach loop.

Start:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if(j == 5)
goto Start;
}
}
Although structuring your code in a way to not use a goto is a much better approach...

If you can guarantee that you will have a condition that will tell you that you don't need to restart, you could wrap the whole thing in one more loop.
bool keepLooping = true;
while (keepLooping)
{
keepLooping = false;
for (int x = 0; x < maxx; x++)
{
for (int y = 0; y < maxy; y++)
{
if (DoSomething(x, y))
{
keepLooping = true;
break;
}
}
if (keepLooping)
{
break;
}
}
}
If you are checking a list for duplicates and modifying them do make all entries unique, you might do something like this (assuming string values):
List<string> a = GetNamesFromeSomewhere();
bool duplicateFound = true;
while (duplicateFound )
{
duplicateFound = false;
for (int x = 0; x < a.Length; x++)
{
for (int y = x + 1; y < a.Length; y++)
{
if (a[x].Equals(a[y]))
{
//Change a[y], but now we have to recheck for duplicates...
a[y] += "_";
duplicateFound = true;
break;
}
}
if (duplicateFound)
{
break;
}
}
}

if you use numeric loop variables like i and j you can just reset the values
e.g.
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (var[i][j] == 'x') {
i=0; j=0; break;
}
}
}
you can also use the method approach as suggested earlier
void someFunction(params) {
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (var[i][j] == 'x') {
someFunction(params)
return;
}
}
}
}

Related

C# - Basic hangman game lives issue

I'll make it short: Basic hangman game, it loops through player 2 letter choice and if it doesn't match the first character of player 1's word, it'll remove a life, the the second, until it either finds a match or just removed however many lives the player 1 word length is.
I obviously don't want that, I want it to check the array - if none match then remove a life.
for (int i = 0; i < playerTwoGuesses.Length; i++)
{
Thread.Sleep(1400);
Console.Write("Guess: ");
count = 0;
do
{
try
{
playerTwoGuesses[i] = char.Parse(Console.ReadLine());
validGuess = true;
}
catch (Exception)
{
Console.WriteLine("Please enter a single character only.");
}
} while (validGuess == false);
for (int j = 0; j < playerOneDisguised.Length; j++)
{
if (playerOneCharacters[j] == playerTwoGuesses[i])
{
playerOneDisguised[j] = playerTwoGuesses[i];
}
else
{
lives = lives - 1;
}
}
if (lives == 0)
{
Console.WriteLine("Oh no! It seems you've lost. Closing game in 5 seconds.");
Thread.Sleep(5000);
Environment.Exit(0);
}
Console.WriteLine(playerOneDisguised);
for (int k = 0; k < playerOneDisguised.Length; k++)
{
if (playerOneDisguised[k] != '*')
{
count = count + 1;
if (count == playerOneDisguised.Length)
{
Console.WriteLine("Congratulations you've won!");
Thread.Sleep(1000);
Console.WriteLine("Closing game in 5 seconds.");
Thread.Sleep(5000);
Environment.Exit(0);
}
}
}
}
Try this:
bool match = false;
for (int j = 0; j < playerOneDisguised.Length; j++)
{
for (int y = 0; y < playerTwoGuesses.Length; y++)
{
if (playerOneCharacters[j] == playerTwoGuesses[y])
{
playerOneDisguised[j] = playerTwoGuesses[y];
match = true;
}
}
}
if (match == false) {
lives = lives - 1;
}
// Reset it back to false
match = false;
Rather than looping over the array yourself, you can just ask if the guessed char is present in it. You then only need an if statement to handle a guess
if (Array.Exists(playerTwoGuesses, element => element == lastGuess) {

Increment variable after third time something else happened

Excuse me for the silly question, but i can't manage to solve it.
How can i make something to happen every third time ?
Times(left number):
shipmentId=0
shipmentId=0
shipmentId=1
shipmentId=1
shipmentId=2
shipmentId=2 ....
int occurrence = 0;
int counter = 0;
foreach (var el in elmOrderData)
{
if (el.Name == "shipmentIndex")
{// we are entering here for every element that his name is "shipmentIndex"
el.SetValue(shipmentId);
secondTime++;
}
if ((secondTime % 2) == 0)
{// every third time we see "shipmentIndex"
secondTime = 1;
shipmentId++;
}
}
You could use a bool as in the following example. This will display messageboxes 1,3,5,7 and 9:
bool test = false;
for (int i = 0; i < 10; i++)
{
if (test)
MessageBox.Show(i.ToString());
test = !test;
}
Trying to piece together your notes - whether 'it' happens every time or not. How about this?
int occurrence = 0;
int counter = 0;
foreach(var a in list)
{
if(some_condition)
{
// do something..
occurrence++
if(occurrence % 2 == 0)
{
counter++
}
}
}
Why not just increment everytime and just divide by 2?
for(var i = 0; i<20; i++)
{
var j = i / 2; // or bit shift
//do work on j instead of i
}

C# How to I escape 2 lines of loops

This is my code:
while(true){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
break; //break out of while loop also
}
}
}
How should i do this please, sorry if my english is good,i still learning.
Change your while loop to a variable, then set that variable to false (your isDead variable for instance)
while(!isDead){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
break; //break out of while loop also
}
}
}
That way, your break will get you out of the for loop, then having the isDead set to true will stop the while loop executing.
create a function inline, and call it. use return from within the lambda.
var mt = () => {
while(true){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
return
}
}
}
}
mt();
So as I understand you wanted to break 2 Loops on one condition. You can do the following
bool DirtyBool = true;
while(DirtyBool)
{
for(int x = 0; x < 10; x++)
{
StringArray[x] = new string();
if(isDead)
{
DirtyBool = false;
break; //break out of while loop also
}
}
}
You could create a bool for example:
bool leaveLoop;
And if isDead is true then set leaveLoop to true, in the while loop then check if the leaveLoop is true to break from it.
Try below:
bool bKeepRunning = true;
while(bKeepRunning){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
bKeepRunning = false;
break;
}
}
}
My favorite approach to this sort of situation is to move the code into a separate routine and simply return from it when I need to break. Two loops is as much complexity as I like to include in a single routine anyway.
You can use goto:
while(true){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
goto EndOfWhile; //break out of while loop also
}
}
}
EndOfWhile: (continue your code here)

Many else and if statements?

I am reading a csv file which has column names in first line and values in line >1. I need to get the position of the column name. The only way I can think of is to do either switch or ifs. I read it somewhere that in my case , it is faster (better) to do the ifs. However the file has many columns (~120). Just wondering if there is an alternative(s).
private static void Get_Position(string line, performance p)
{
string[] line_split = line.Split(',');
for (int i = 0; i < line_split.Length; i++)
{
if (line_split[i].Contains(#"(0)\% Processor Time"))
{
p.percore[0] = i;
}
else if (line_split[i].Contains(#"(1)\% Processor Time"))
{
p.percore[1] = i;
}
else if (line_split[i].Contains("Private Bytes"))
{}
else if (line_split[i].contains("DPC")
{
}
//on and on and on with else ifs
What is preventing you from using a loop?
for (int i = 0; i < line_split.Length; i++)
{
for(var j = 0; j < 120; j++)
{
if(line_split[i].Contains(#"(" + j + ")\% Processor Time"))
{
p.percore[j] = i;
}
}
...
To maintain the same functionality as if else if then you could use a break inside the conditional.
Edit: The edit now made it clear that there is no clear pattern to the string in contains. Still, if you are writing out 120 if/else if statements you should store what you will be looking for in some type of collection. For example, a List would work. Then access the index j of the collection in your loop:
...
var listOfSearchItems = new List<string>() { "Private Bytes", "DPC" };
for (int i = 0; i < line_split.Length; i++)
{
for(var j = 0; j < 120; j++)
{
if(line_split[i].Contains(listOfSearchItems[j])
{
p.percore[j] = i;
}
}
...

List/Array member can't be addressed - Euler 14

I have the below code. I create a list (tried with array as well) with one million and one members. All of them has the value 0 by default. It should work like a multidimensional array, but it's not necessary as the first 'column' has to be numbers from 1-1.000.000. To make life easier I made 1.000.001 members to avoid using the 0th place.
At a certain point I have to use a member of this list addressed by a variable: list[n], and to avoid issues this only happens if n < 1.000.000. As there are members from 0-1.000.000 I think it's OK, but still my program crashes after a while with error code ArgumentOutOfRangeException.
What am I missing here?
int highestCount = 0;
int highestNum = 0;
List<int> list = new List<int>();
for(int j = 0; j <= 1000001; j++)
{
list.Add(0);
}
for (int i = 2; i < 1000000; i++)
{
int count = 0;
int number = i;
do
{
if (i % 2 == 0)
{
number = number / 2;
if (number < 1000000)
{
if (list[number] != 0)
{
count += list[number];
break;
}
else
{
count++;
}
}
else { count++; };
}
else
{
number = (number * 3) + 1;
if (number < 1000000)
{
if (list[number] != 0) //program dies here
{
count += list[number];
break;
}
else
{
count++;
}
}
else { count++; };
}
} while (number > 1);
list[i] = count;
if (count > highestCount)
{
highestCount = count;
highestNum = i;
}
}
MessageBox.Show(highestNum.ToString());
I think it's just a problem with your logic.
When i == 3 (on the second run), it will go into the do-while block.
Since i % 2 != 0 at that point, it will hit the else.
The number is multiplied by 3 and you add 1.
It is less than 1000000, but....
if(list[number] != 0)
never evaluates to true and you are stuck in an infinite do-while loop and it never breaks out because A) number will always be greater than 1 (satisfying the while condition); and B) you set every element of the array to zero in the code above this loop (thus never satisfying the above if condition):
for(int j = 0; j <= 1000001; j++)
{
list.Add(0);
}

Categories

Resources