ForEach loop counter [duplicate] - c#

This question already has answers here:
Convert a list into a comma-separated string
(15 answers)
Closed 4 years ago.
I am doing some schema javascipt/C# coding and I have a question. I am doing breadcrumb schema for a little more reference. My goal is to find somehow to increment counter to be even to k in this example, so I can stop a comma from showing on the last iteration on the foreach loop. Right now, obviously they both increment at the same rate. I am having the biggest brain fart on where to place (counter++) to get it to increment and then end up even after the for each is completed. Both starting integer values should be as is. Just changing the counter to 1 is not what I am looking for :) Also the counter has to be in the ForEach loop.
Pseudo code below:
k = 1;
counter = 0;
foreach(string str in array1)
{
Schema Code
Schema Code
for(i = 0; i > 0; i++)
{
k++
counter++ (not right location, but reference)
}
if(k < counter)
{
print a coma
}
else if(k >= counter)
{
print space
}
}
Updated: My code would be where position is. I dont have access to my code at this moment. But the for each runs through the number on positions there are on the page. Then at the last position it will not write the comma.
<script type="application/ld+json">
{
"context": "http://schema.org",
"type": "BreadcrumbList",
"itemListElement": [{
"type": "ListItem",
"position": 5,
}
}
</script>

Rather than having two separate counters, I recommend starting by taking the length of the array and using a counter to print a comma while the counter is less than the number of total items in the array. That way, when you finish you'll have one less comma than array item, and you won't have a comma at the end of what you've printed.
This is kind of involved but, since you really don't want to have the comma at the end of what you've printed, it may best fit your needs.
Here's some pseudocode based on what you wrote above:
// the length of the array needs to be a constant because depending on
// what your code does it may change the array length as your loop runs
const arrayLength = the length of your array when you start
int commaCount = 0
foreach(string str in array1)
{
Schema Code
Schema Code
if (commaCount < (arrayLength -1))
// (< arrayLength -1) because then your last comma will reach
// (arrayLength -1) and then not increase any more the last time around
{
print a comma
}
}
Let me know if that helps.
(Please disregard my syntax. This is pseudocode, so definitely don't copy and paste what I just wrote.)

Related

How can I check for integers in list and print the index of them?

so my problem is that I don't know how to go forward in the list and print the next same integer if there is one.
Here is what I have at the moment:
while (list.Contains(input1))
{
Console.WriteLine(input1 + " is at index " + list.IndexOf(input1))
}
I am trying to list all of the integers that are in the list and print the index of them. But not remove after finding one of the integers (this was at least my first idea.).
IndexOf has an overload with two parameters, which allows you to start searching at a later position in the list.
Since this is obviously a learning exercise, I won't spoil it by providing the full code, but rather suggest that you try to implement the following algorithm:
Find the index of input starting at position 0.
If not found (i.e., IndexOf returns -1): we're done. Otherwise:
Print and remember that index.
Start again at step 1, but this time, don't start searching at 0 but at the index you remembered + 1.
You can do the following:
go through the list/array using for statement
for(int i=0; i < list.length; i++) // loop though list
then inside the loop check the value of the current item using if statement:
if(list[i] == input1)
//do smothing
The list[0] represent the first item in the array, which means the index is 0.
so in the example above the i will be the current index so long that you in the loop.
I didn't write the full code for learning purpose in reference to #Heinzi answer.
Hope that could be helpful!
This is an implementation possibility. It is longer than it has to be, but it makes it clearer for beginners how one could tackle this problem.
Since you wanted to only show numbers that come up more than once here is an implementation method. If you want to show numbers that come up only once too just erase everything about lastindex
List<int> yourlist = new List<int> { 1,1,1,1,1,11,2,3,3,4,4,5 };
int input = 0;
input = Convert.ToInt32(Console.ReadLine());
var index = yourlist.IndexOf(input);
//this checks if your input is in the list
var lastindex = yourlist.LastIndexOf(input);
//this does the same but it searches for the last implementation of your input
if (index != -1 && lastindex != index)
//this if checks if your number comes up more than once. IndexOf returns -1 if there is no occurence of your input
{
Console.Write($"the index of {input} is {index}");
for (int i = index+1; i <= yourlist.Count; i++)
//this loop takes the position of the first occurence of your number and then counts up from there
{
var tempindex = yourlist.IndexOf(input, i);
if (tempindex != -1)
//this if lets everything except -1 through
{
Console.Write($" and {tempindex}");
}
}
}
else
{
Console.WriteLine("your number cannot be found twice in the list");
}

Domino recursion

I have a recursion assignment where I have to input into console the following data:
On the first line a natural number equal with the number of tiles I have to input on the following lines (in my example the first number is 6).
On the following lines the domino tiles in the following order:
1 2
1 3
3 4
2 3
3 5
4 5
On the last line another number representing the number of tiles that needs to be returned on each separate line (in my example the number is equal with 3).
With this data I have to display all possible combinations of pairs. For each separate line the number the second number from the first pair has to be equal with the first number of the following pair and so on. I had a hint for this assignment where I have to declare an intermediary list that is equal with the function (using recursion from the start) but when I'm trying to run the code it gives me a null exception for the intermediaryList.
In the first instance I read the data as a 2d array but settled with a simple string array where.
This is my code so far, could you help me with a suggestion, how to avoid the null exception?
(sorry if I missed something from the explanation, this is my second post here so far and thank you in advance). Also I have to mention that I'm allowed to use just "using System;" Not allowed to use Linq or anything else.
enter code here
static string[] ReadDominoTiles(int n)
{
string[] input = new string[n];
for (int i = 0; i < n; i++)
{
input[i] = Console.ReadLine();
}
return input;
}
static string[] DominoSolution(string[] dominoTiles, int numberOfPairs)
{
string[] finalList = new string[numberOfPairs];
if (numberOfPairs == 1)
{
return finalList;
}
string[] intermediaryList = DominoSolution(dominoTiles, numberOfPairs - 1);
for (int i = 0; i < intermediaryList.Length; i++)
{
for (int j = 0; j < dominoTiles.Length; j++)
{
// This is where I get the nullref exception, every value from intermediaryList is null
if (intermediaryList[i] != dominoTiles[j] && intermediaryList[j][1] == dominoTiles[j][0])
{
finalList[j] += intermediaryList[j] + " " + dominoTiles[j];
}
}
}
return finalList;
}
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] dominoTiles = ReadDominoTiles(n);
int numberOfPairs = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(DominoSolution(dominoTiles, numberOfPairs));
}
This is where I get the nullref exception, every value from intermediaryList is null
That's correct, you call the function recursively after doing exactly zero work, besides adding a recursion termination condition which returns an array of nulls. So the first time you come out of your recursion you have in intermediaryList a number of null elements, so when you pretend they're strings and try to get intermediaryList[j][1] you'll get a null reference exception.
As to the solution, it's not exactly clear what's with all the arrays you're allocating. Use a List<> with an actual type and do your work properly. Though I hate to break it to you but if I understand your assignment correctly the solution will use backtracking and combinatorics, which is much more code and much better structured than what you have here.

How to print a letter at a specific index of a string that is in an array in C#? [duplicate]

This question already has answers here:
How extract a specific character in a string in c# by index [duplicate]
(2 answers)
C# equivalent to Java's charAt()?
(6 answers)
Closed 1 year ago.
I have been trying to do an effect where the console types out each letter of a string array element one at a time with a slight delay in between. I cannot for the life of me figure out how to print a letter at a specific index of a string in an array (or if its even possible).
I have been trying to do this by using a for loop, increasing the index by 1 everytime it writes the full element and then goes onto the next. The problem is how to print each letter individually. Right now, it just prints the whole string element and then goes to the next and so on. I want it to print each letter individually and then increase the element index.
I have been researching this for hours but cant seem to find anything.
public string[] menuInputs = { };
public void TextAnimateScrollLeft()
{
menuInputs = File.ReadAllLines("../MenuInputs.txt");
menuInputs.Reverse();
int arrayIndex;
for(arrayIndex = 0; arrayIndex <= menuInputs.Length - 1; arrayIndex++)
{
Console.Write(menuInputs[arrayIndex]);
Thread.Sleep(50);
}
Console.ReadKey();
}
Notes are included as comments:
//it's not clear just from the ScrollLeft name:
// do you also want to scroll each string backwards?
// If so, you'll need to make use of the `SetPosition()` function
public void TextAnimateScrollLeft()
{
var menuInputs = File.ReadAllLines("../MenuInputs.txt");
//save the work reversing the array by iterating backwards
for(int arrayIndex = menuInputs.Length -1; arrayIndex >= 0; arrayIndex--)
{
// also loop through the characters in each string
foreach(char c in menuInputs[arrayIndex])
{
Console.Write(c);
Thread.Sleep(50); // 20 characters per second is still pretty fast
}
Console.WriteLine(); //don't forget the line break
}
Console.ReadKey();
}

How to fix this for loop to compare two char arrays?

I'm pretty new to C# and still learning about arrays. I got a problem where I have to compare two strings, and what I have to compare is how many times the same letter is in the same place in both strings. I made a for loop and an if statement that I feel should work, but it doesn't add to the counter and I can't see the problem myself.
I've searched how to compare char arrays and i found that the for loop I have would probably be best for this problem, but after it stopped working I'm not sure what I should do. I've gone into the debugging mode on visual studio and looked at the values as the code runs, and everything seems fine up until the if statement, which I think is the source of the problem I have.
//counter for the answer: how many parking spaces shared
int counter = 0;
//int for the number of spaces
int num = 0;
//takes number from textbox into num
int.TryParse(txtNumber.Text, out num);
//parking spaces from first day
string yesterday = txtYesterday.Text;
//parking spaces from second day
string today = txtToday.Text;
//my idea was to put both days into char arrays and compare
each spot in a for loop
char[] y = yesterday.ToCharArray();
char[] t = today.ToCharArray();
for(int i = 0; i < num; i++)
{
//so if the first spot is the same as the first spot on the
other day, and the spot has the correct letter then it should work
if(y[i] == t[i] && y[i].Equals("C"))
{
counter++;
}
}
MessageBox.Show(counter.ToString());
an example input would be
3
.CC
..C
the answer should be 1, because one spot was occupied on both days.
Your problem lies in the following line
if(y[i] == t[i] && y[i].Equals("C"))
You are taking a character at time in your loop. So it needs to be compare with a character rather than string.
if(y[i] == t[i] && y[i].Equals('C'))
You have char array so you'll need to see if y[i].Equals("C") by comparing chars not strings:
y[i].Equals('C')

Pre-decrement of value in a for loop is not correctly decreasing value on first loop

I have the following for loop in my code (using C#)
for (int i = 150; i >= 75; --i)
{
print("I holds " + i);
images[i].gameObject.SetActive(false);
}
trying to run through each item in a list, and disable the object. The list holds 150 objects (but since it starts at value zero, the final reference position is 149)
So, I figured a for loop was a good way to iterate through them all. Yet, I try to decrease the value of i to 149 for the first run of the loop, but it still passes a value of 150 into the loop in the first run, which throws the expected ("Argument is out of range") error.
Can anyone work out why the decreased value isn't correctly being passed to the loop?
I tried both decreasing it before and after the first run of the loop, but both times it passes a value of 150 into the loop.
I feel this should be a relatively simple issue to solve, yet it's not working as I expected it to do!
for (int i = 10; i >= 0; --i)
is the same as
for (int i = 10; i >= 0; i--)
i does not decrease/increase on the first loop. This is for many languages. Just start with 149 and it works.
Answer for "Can anyone work out why the decreased value isn't correctly being passed to the loop?"
Another way to loop through all items of an array without caring of actual indices is to make use of a foreach statement:
foreach(var image in images)
{
image.gameObject.SetActive(false);
}
If you want to use a for statement. I would suggest you write it as below:
for(var i=0; i<images.Length; i++)
{
image[i].gameObject.SetActive(false);
}
Doing so, you are pretty confident that you are not going to be out of the array's size. You start at the element at the position with index of 0 and you read the last item stored in the array, in the position of images.Length-1.
Update
If you want to update only the first 75 items (where 75 is half the total items in the array) in your array you could try this:
for(var i=0; i<images.Length/2; i++)
{
image[i].gameObject.SetActive(false);
}

Categories