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')
Related
I am new here. I'm trying a C# problem on Leetcode about Longest Common Prefix. I know this problem has been solved MANY times. I'm just having a hard time understanding why my code doesn't work under certain conditions. When the input ["flower","flow","flight"] is put in, it works just fine and get the output "fl". However, when I get to the input ["ab", "a"], I suddenly get an IndexOutOfRangeException. Anyone know why? Here's my code:
public class Solution {
public string LongestCommonPrefix(string[] strs) {
StringBuilder sb = new StringBuilder();
int h = 1;
int count = 0;
if (strs.Length == 1){
return strs[0];
}
for (int i = 0; i<strs[0].Length; i++)
{
if ((strs[0])[i].Equals((strs[h])[i])){
count++;
if (h<strs.Length-1){
h++;
}
}
}
for (int j = 0; j < count; j++)
{
sb.Append((strs[0])[j]);
}
return sb.ToString();
}
}
You can debug by making a simple console app in Visual Studio. I added a Console.Writeline(strs[0] + strs[h]) to your code to demonstrate the logic as is. Running your code in debug, you can step through and see where the exception gets thrown:
Notice that the console prints the same thing each time, and that the strs[h] is only one character long. When you increment the i to 1, you're trying to access the second element of a one element array.
When the input ["flower","flow","flight"] is put in, it works just fine and get the output "fl". However, when I get to the input ["ab", "a"], I suddenly get an IndexOutOfRangeException. Anyone know why?
Because the algorithm as written loops until i has reached the length of the first string, not the shortest string. This is fine for flower/flow/flight because all these strings will find the common prefix "fl" before i comes close to running off the end of the shortest string; i is 2 by the time the algorithm determines that the o in flower is different to the i in flight and hence the code doesn't go out of bounds.
In the ab/a case, i is 1 and the algorithm hasn't yet determined the prefixes have diverged, you attempt to access the nonexistent index 1 on string "a" and get a crash
As comments have pointed out you also have a problem on your h logic; h should be cycled starting from 1 in a loop of its own inside the i loop. As it is now h just increments up to the number of strings-1 and stays there so in essence you end up only looking for prefixes in the first and last strings. If your strings were flower/flight/float/flowing/flowers you'd declare a prefix of "flower" because flight/float/flowing would only be considered when i was 0, 1 and 2 respectively
I suggest you write out the algorithm in comments, in the language you think in then have a go at turning it into 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.)
I am in the process of learning C# and I'm building a hangman game from scratch as one of my first projects.
Everything works except for the part that replaces the dashes of the hidden word with the correctly guessed letters.
For example: ----- becomes G-EA- after you guess G, E, and A.
I have a for loop that logically seems like it'd do the job except I can't use the == operator for strings or chars.
for (int i = 0; i <= answer.Length; i++) //answer is a string "theword"
{
if (answer[i] == passMe) //passMe is "A" for example
{
hiddenWord = hiddenWord.Remove(i, 1);
hiddenWord = hiddenWord.Insert(i, passMe);
}
}
I've scoured the net trying to find a good solution. Most recommend using Regex or other commands I haven't learned yet and therefore don't fully understand how to implement.
I've tried converting both to char format in the hope that it would fix it, but no luck so far. Thanks in advance for any help.
If passMe is a string of only one char then
if (answer[i] == passMe[0])
In this way you compare the character at i-th position with the character at the first position of your user input
There is also a serious error in your code.
Your loop goes off by one, change it to
for (int i = 0; i < answer.Length; i++)
The arrays in NET start at index zero and, the max index value possible, is always one less than the length of the array.
answer[i] refers to a character and passMe is a single character string. (not a character)
Try this
for (int i = 0; i <= answer.Length; i++) //answer is a string "theword"
{
if (answer[i] == passMe[0]) //passMe is "A" for example
{
hiddenWord = hiddenWord.Remove(i, 1);
hiddenWord = hiddenWord.Insert(i, passMe);
}
}
you need to compare a character with a character.
So, what I'm trying to do this something like this: (example)
a,b,c,d.. etc. aa,ab,ac.. etc. ba,bb,bc, etc.
So, this can essentially be explained as generally increasing and just printing all possible variations, starting at a. So far, I've been able to do it with one letter, starting out like this:
for (int i = 97; i <= 122; i++)
{
item = (char)i
}
But, I'm unable to eventually add the second letter, third letter, and so forth. Is anyone able to provide input? Thanks.
Since there hasn't been a solution so far that would literally "increment a string", here is one that does:
static string Increment(string s) {
if (s.All(c => c == 'z')) {
return new string('a', s.Length + 1);
}
var res = s.ToCharArray();
var pos = res.Length - 1;
do {
if (res[pos] != 'z') {
res[pos]++;
break;
}
res[pos--] = 'a';
} while (true);
return new string(res);
}
The idea is simple: pretend that letters are your digits, and do an increment the way they teach in an elementary school. Start from the rightmost "digit", and increment it. If you hit a nine (which is 'z' in our system), move on to the prior digit; otherwise, you are done incrementing.
The obvious special case is when the "number" is composed entirely of nines. This is when your "counter" needs to roll to the next size up, and add a "digit". This special condition is checked at the beginning of the method: if the string is composed of N letters 'z', a string of N+1 letter 'a's is returned.
Here is a link to a quick demonstration of this code on ideone.
Each iteration of Your for loop is completely
overwriting what is in "item" - the for loop is just assigning one character "i" at a time
If item is a String, Use something like this:
item = "";
for (int i = 97; i <= 122; i++)
{
item += (char)i;
}
something to the affect of
public string IncrementString(string value)
{
if (string.IsNullOrEmpty(value)) return "a";
var chars = value.ToArray();
var last = chars.Last();
if(char.ToByte() == 122)
return value + "a";
return value.SubString(0, value.Length) + (char)(char.ToByte()+1);
}
you'll probably need to convert the char to a byte. That can be encapsulated in an extension method like static int ToByte(this char);
StringBuilder is a better choice when building large amounts of strings. so you may want to consider using that instead of string concatenation.
Another way to look at this is that you want to count in base 26. The computer is very good at counting and since it always has to convert from base 2 (binary), which is the way it stores values, to base 10 (decimal--the number system you and I generally think in), converting to different number bases is also very easy.
There's a general base converter here https://stackoverflow.com/a/3265796/351385 which converts an array of bytes to an arbitrary base. Once you have a good understanding of number bases and can understand that code, it's a simple matter to create a base 26 counter that counts in binary, but converts to base 26 for display.
the code below belongs to binary search algorithm,user enter numbers in textbox1 and enter the number that he want to fing with binarysearch in textbox2.i have a problem with it,that is when i enter for example 15,21 in textbox1 and enter 15 in textbox2 and put brakpoint on the line i commented below,and i understood that it doesnt put the number in textbox2 in searchnums(commented),for more explanation i comment in code.thanks in advance
public void button1_Click(object sender, EventArgs e)
{
int searchnums = Convert.ToInt32(textBox2.Text);//the problem is here,the value in textbox2 doesnt exist in searchnums and it has value 0.
int result = binarysearch(searchnums);
MessageBox.Show(result.ToString());
}
public int binarysearch(int searchnum)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first =0;
int last = nums.Length-1;
while (1<= nums.Length)
{
int mid = (int)Math.Floor(first+last / 2.0);
if (first > last)
{
break;
}
if (searchnum < nums[mid])
{
last = mid - 1;
}
if (searchnum > nums[mid])
{
first = mid + 1;
}
else
{
return nums[mid];
}
}
return -1;
}
First, when you know you can place a breakpoint on a line, you sure know you can step through the whole program and see what values are in each variable or property. So, go ahead, and debug. Among other things you are probably missing data input validation in your program.
Second, your binary search implementation is missing mid recalculation after first or last is updated and a stop condition in case the number being looked for is not found in the array. You have to break the loop in case first == last, regardless if nums[mid] matches or not — nobody said the number from textbox2 must be in the array.
What does it have to do with binary search? The problem seems to be that you can't read the number out of a textbox. Are you sure it's the right textbox? What is it's Text? Also, if you put the breakpoint ON the line that assigns the value to searchnums, it will be 0, because it hasn't been assigned yet, put the breakpoint on the line AFTER.
OK, first of all, I hope you know that binary search won't work if nums isn't sorted.
That said, there are a few problems in the algorithm. First of all, you're not changing any of the key elements in the loop. You're only changing first and last in the loop and they aren't even used there, so the loop's state doesn't change.
So i guess you meant to have this line in the beginning of the loop:
mid = (first +last)/2;
Besides that, you need to check for the very likely event that the number doesn't exist. which means adding this in the beginning of the loop to:
if (last < first) break;
Which of course means that the first point of the array block has passed the last point, which means the block size is negative. first == last may be legal when you get to the last cell in the array.
And the last point is to initiate last as size-1:
int last = nums.Length - 1;
We're talking about array indexes after all.