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.
Related
I'm trying to find a long string in another string. For this I've been using G[i].Contains(P[arr]) but for some reason the code just skips that condition. In my case : G[I] is 1000 character long and P[arr] is 475. When I debug I can see strings are not trimmed and also I have verified that P[ARR] is part of G[I] in Notepad++ so it should definitely satisfy a condition.
for (int arr = 0; arr < P.Length; arr++)
{
for (int i = a; i < G.Length; i++)
{
if (G[i].Contains(P[arr]))
{
if (!(b == 0))
{
a = i + 1;
continue;
}
primary_1 = (a == 0) ? G[i].IndexOf(P[arr]) : primary;
++count;
a = i + 1;
Console.WriteLine("Counter: " + i);
break;
}
}
}
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
}
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.
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);
}
I am doing my homework and I have to do a program that extends simple letters from a file, like E and F, to continuous productions, given also in the folder, such as E+T E-F etc. Anyway the code shown below gives me an argument out of range exception. I crafted the same code in java and all works fine. I don't know why in C# it gives me this exception. Please give me some advice!!
I forgot to put the file that I'm reading from:
EFT
a+()
E
E+T|E-T|T
T*F|T/F|F
a|(E)
public void generare(){
String N = null;
String T = null;
String S = null;
String[] P = null;
TextReader tr = new StreamReader("dateIntrare.txt");
try
{
N = tr.ReadLine();
T = tr.ReadLine();
S = tr.ReadLine();
P = new String[N.Length];
for (int i = 0; i < N.Length; i++)
{
P[i] = tr.ReadLine();
}
tr.Close();
Console.WriteLine("Neterminale: N = " + N);
Console.WriteLine("Terminale: T = " + T);
Console.WriteLine("Productii ");
for (int i = 0; i < P.Length; i++)
Console.WriteLine("\t" + P[i]);
Console.WriteLine("Start: S = " + S);
Boolean gata = false;
String iesire = S.Substring(0, S.Length);
Console.WriteLine("\nRezultat");
Console.Write("\t");
while ((gata == false) && (iesire.Length < 50))
{
Console.Write(iesire);
Boolean ok = false;
for (int i = iesire.Length - 1; i >= 0 && ok == false; i--)
{
for (int j = 0; j < N.Length && ok == false; j++)
if (N[j] == iesire[i])
{
String s1 = iesire.Substring(0, i);
String s2 = iesire.Substring(i + 1, iesire.Length); // HERE IS THE EXCEPTION TAKING PLACE
String inlocuire = P[N.IndexOf(iesire[i])];
String[] optiuni = null;
String[] st = inlocuire.Split('|');
int k = 0;
foreach (String now in st)
{
k++;
}
optiuni = new String[k];
st = inlocuire.Split('|');
k = 0;
foreach (string next in st)
{
optiuni[k++] = next;
}
Random rand = new Random();
int randNr = rand.Next(optiuni.Length);
String inlocuireRandom = optiuni[randNr];
iesire = s1 + inlocuireRandom + s2;
ok = true;
}
}
if (ok == false)
{
gata = true;
}
else
{
if (iesire.Length < 50)
Console.Write(" => ");
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("Eroare, fisierul nu exista!");
}
Console.WriteLine();
}
But why in java works and here not? I'm confused
When in doubt, read the documentation. In Java, the 2-parameter overload of substring takes a start index and an end index. In .NET, the second parameter is the number of characters to take, not an end index.
So you probably want
String s2 = iesire.Substring(i + 1, iesire.Length - i - 1);
Or to be simpler about it, just use the 1-parameter version, which takes all the characters from the specified index onwards:
String s2 = iesire.Substring(i + 1);
(I'd use that in Java too...)
Fundamentally though, it's worth taking a step back and working out why you couldn't work this out for yourself... even if you missed it before:
Look at the line that threw the exception in your code
Look at which method actually threw the exception (String.Substring in this case)
Look at the exception message carefully (it's a really good hint!) and also any nested exceptins
Read the documentation for the relevant method carefully, especially the sections describing the parameters and exceptions
This is a common mistake while porting codes from Java to c#.
Substring in Java takes start & end parameters but in c# they are start and length