Increment variable after third time something else happened - c#

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
}

Related

How can I add the value of an item in a list box to a local variable in C#?

So I'm doing a practical that involves asking the user to input a score between 0 and 100. The program will keep track of the number of scores that have been entered, the total score (sum of all scores) and the average score.
To calculate the total score, I've come up of the idea of using a for loop that will cycle through my listbox and add each score to a variable (below).
int sTotal = 0;
for(int i = 0; i < lstScores.Items.Count; i++)
{
//Calculation occurs here
}
txtScoreTotal.Text = Convert.ToString(sTotal);
Thing is, I don't exactly know how to do it. I've tried searching to no avail. Any help would be greatly appreciated.
int sTotal = 0;
int Average = 0;
for(int i = 0; i < lstScores.Items.Count; i++)
{
bool result = Int16.TryParse(lstScores.Items[i],out int res);
if (result)
{
sTotale += res;
}
}
Average = sTotal / lstScores.Items.Count;
txtScoreTotal.Text = Convert.ToString(sTotal);
See this
int i = 0, result = 0;
while (i < lstScores.Items.Count)
{
result += Convert.ToInt32(lstScores.Items[i++]);
}
txtScoreTotal.Text = Convert.ToString(result);
I havent tried following, but you can try 1 line solution too
var sum = lstScores.Items.OfType<object>().Sum(x => Convert.ToInt32(x));
You need to handle exception if sum exceedes int.Max
Easiest is it to do with a foreach loop like this:
int sTotal = 0;
foreach (string item in lstScores.Items)
{
sTotal += Int32.Parse(item);
}
txtScoreTotal.Text = Convert.ToString(sTotal);

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.

C#: Cannot reassign variable within For loop

I am writing a program to to calculate a specific value in Fibonacci sequence. The recursive method works perfectly, but when I try to use for loop, it doesn't work so well:
class Program
{
static int loopF(int n)
{
int result=0;
if (n == 1)
{
result = n;
}
else if (n == 2)
{
result = n;
}
else if (n>2)
{
int S1 = 1; int S2 = 2;
for (int i = 3; i>n; i++) {
result = S1 + S2;
S1 = S2;
S2 = result;
}
}
else{
Console.WriteLine("Input Error");
}
return (result);
}
static void Main()
{
Console.WriteLine(loopF(10)); //it gives me 0; wrong
Console.WriteLine(loopF(1)); //it gives me 1; correct.
}
}
Does anybody know where I go wrong? Thanks in advance.
Your loop is not executing
for (int i = 3; i>n; i++)
Variable i starts at 3 - in your test case n = 10.
(10 < 3) = false so the loop does not execute.
try using less than instead
for (int i = 3; i < n; i++)
Your loop's exit condition is wrong. It should be
for (int i = 3; i < n ; 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);
}

How to reset or restart nested loops

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;
}
}
}
}

Categories

Resources