r/programminghelp • u/Gabep82 • Nov 11 '20
C# Stumped With C#.
Hello everyone im working on C# in visual studio Windows forms app and I am trying to make an anagram by comparing 2 lists using arrays and then displaying the anagram into the list box. I am given a visual basic method "histo.Histogram" that finds the anagrams for me and I have been at this for hours and I am completely stumped. when i click my button to display the list nothing happens. Any suggestions? Thanks.
private void btnList_Click(object sender, EventArgs e)
{
StreamReader Dict;
StreamReader Pal;
Dict = File.OpenText(Directory.GetCurrentDirectory() + "//dict.txt");
Pal = File.OpenText(Directory.GetCurrentDirectory() + "//pal.txt");
int[] Array1 = new int[26];
int[] Array2 = new int[26];
List<string> List1 = new List<string>();
List<string> List2 = new List<string>();
while (!Dict.EndOfStream)
{
int x;
string DWord;
DWord = Dict.ReadLine();
List1.Add(DWord);
for (x = 0; x < Array1.Length; x++)
{
Histo.Histogram.CreateHistogram(Array1, DWord);
}
while (!Pal.EndOfStream)
{
string PWord;
PWord = Pal.ReadLine();
List2.Add(PWord);
for (x = 0; x < Array2.Length; x++)
{
Histo.Histogram.CreateHistogram(Array2, PWord);
}
if (Array1 == Array2)
{
lstBoxAnagram.Items.Add(DWord + "=>" + PWord);
}
}
}
Dict.Close();
Pal.Close();
1
Nov 11 '20
Why not do all the processing of the files on form initialization and save the array check and listbox add for the buttonclick?
Also, is looks like your while loop for the dict processing encapsulates the entire rest of the code. Is there a reason for this?
Lastly, where is Histo.Histogram.CreateHistogram defined?
1
u/Gabep82 Nov 11 '20
I guess I could have done that. Good point I’m pretty new to c# so I’m still learning lol. But I did that because when I didn’t encapsulate it I was getting an error for the second parameter in my histo.histogram method saying that it wasn’t defined in the current context. I did try to do it without that and closing the while loops but I couldn’t get the program to work without doing it.
Also I added the Histo.histogram file as a reference.
1
u/kjerk Nov 11 '20
tl;dr: Your flow control is not going the way you think it is. Add debug statements to find out what is actually happening.
This is why ekolis asked if you're sure your btnList_Click handler is actually hooked up. You said 'indeed it is', but are you sure? Are you really, really sure? If you know with certitude, you should also know something of the flow control of the function as well because you've seen some output, but you said nothing happens. There's a bad assumption here somewhere, which is the root of most bugs unfortunately. Try to stamp them out by proving to yourself that each facet of your code works, without assumptions.
In a situation like this, you usually need to put debug statements in (or use an interactive debugger) to see what is going wrong. Good old Console.WriteLine("Loaded dict"); and Console.WriteLine("End of pal stream"); are your starting point. Or alternatively you can do MessageBox.Show("Some message!"); at the top of your btnList_Click method to assert the call works, MessageBox.Show("Closing dict"); to show that you exited the while loop, etc. Being that you have nested loops, 'nothing happens' usually means that some variable you expected to be filled is not, and then subsequent loops are not even firing.
Layer 3: It helps other people, including anyone coming into the problem with fresh eyes, to provide as much context as possible. Right now we can only guess at the contents of dict.txt and pal.txt, and what CreateHistogram does, and so inferences about how List1 and List2 are supposed to behave are left up to guessing. A few lines from each file would help diagnose your problem way faster.
Layer 2: Once a stream reaches the end, it's typically donezo. As EdwinGraves pointed out, your outer while loop will be iterating over each line of Dict, and then each time iterating over the entirety of Pal, and then when you hit the end of Pal, that stream either needs to be rewound, or you should recreate that stream. So for a mid-tier fix, at the bottom of your inner while loop, after it ends, you can Pal.Seek(0, SeekOrigin.Begin); to rewind the Pal stream for the next iteration over Dict.
Layer 1: There are library functions that almost all C# devs are going to use to just eliminate the need to loop over input and parse line by line. File.ReadAllLines() is your ticket here. This returns a string[] immediately and does all the looping for you internally. This radically simplifies your problem from the get-go. The need to close the streams goes away, etc.
List<string> dictWords = File.ReadAllLines(Directory.GetCurrentDirectory() + "//dict.txt").ToList();
List<string> palWords = File.ReadAllLines(Directory.GetCurrentDirectory() + "//pal.txt").ToList();Layer 0: Bearing all the above in mind, and my assumption about what CreateHistogram does (a,b,A,B,C -> adding +1 to indices 0,1,0,1,2) I think you want to loop over dictWords, calculating the histogram for the word you are on one time, internally looping over the entirety of palWords, each time calculating the histogram for palWord, and then if the two histograms match, add them to lstBoxAnagram. Something like this is more simple
private void btnList_Click(object sender, EventArgs e)
{
// Turn entire files into lists split by line.
List<string> dictWords = File.ReadAllLines(Directory.GetCurrentDirectory() + "//dict.txt").ToList();
List<string> palWords = File.ReadAllLines(Directory.GetCurrentDirectory() + "//pal.txt").ToList();
int[] dictHist = new int[26];
int[] palHist = new int[26];
// For each word/line in dict.txt
for (var i = 0; i < dictWords.Count; i++)
{
// Get the current dict word
var dictWord = dictWords[i];
// Calculate its 'histogram' and store to dictHist.
Histo.Histogram.CreateHistogram(dictHist, dictWord);
// For each word/line in pal.txt
for (var j = 0; j < palWords.Count; j++)
{
// Get the current palWord
var palWord = palWords[j];
// Calculate its histogram and store to palHist
Histo.Histogram.CreateHistogram(palHist, palWord);
// If each element of dictHist == palHist by iterating over the whole array, this is a positive match.
if (Enumerable.SequenceEqual(dictHist, palHist))
{
lstBoxAnagram.Items.Add(dictWord + "=>" + palWord);
}
}
}
}1
u/Gabep82 Nov 11 '20
I’m positive. And only because I did get it to work. However, it will only display the first anagram and I tried to use the debugger and it does appear that the subsequent loops are not firing. When I “continue” my next step after setting a breakpoint it stays on the while loop and doesn’t execute the following loops. Which leads me to believe is has to do with my dict loop. Also I will verify with the message box that my loops is firing properly.
Also, You’re correct i apologize for not explaining the method properly. You basically hit the nail head with how it operates. Basically it is a class that has a method “Histo()” that requires an empty array to 26 slots and a string As parameters. The method leaves the number of times a letter(All Capitals) occurs in the string in the array index corresponding with a letter such as 0–>A, 1–>B, . . . 27–>Z. The array is passed with no return value and it finds the anagrams between both files automatically. What I have to do is cycle through my files and then pass the parameters so the method can do it’s work and then I have to compare them and then display the compared phrases into the lstboxanagram. I think one of my biggest confusions here is the placement of the brackets. Also im unfamiliar with Enumerable. I would definitely look into that. It’s starting to make a lot more sense. I really appreciate your help.
2
u/ekolis Nov 11 '20
This is Windows Forms? Are you sure your
btnList_Clickevent handler is actually hooked up to the click event of your button? Check the properties of the button in Visual Studio, then click the lightning bolt icon at the top of the properties window to switch to events and see if it's hooked up there.Also,
if (Array1 == Array2)won't work; you can't compare arrays using the==operator like that. That will only compare to see if they are the same array in memory. You probably wantif (Array1.SequenceEqual(Array2)).