How to compare lines (one line random sequence)
I want to compare 2 lines, but the one line is in a random sequence. I use text boxes, like this:
Textbox1:
friends pals elephantTextbox2:
asplNow when I hit a button I want Textbox3 to show the following:
Textbox3:
palsWhat I got so far:
Textbox3.Clear();
string[] lines开发者_高级运维1 = Textbox2.Lines;
foreach (string line1 in lines1)
{
string[] lines = Textbox1.Lines;
foreach (string line in lines)
{
if (line.Contains(line1))
{
Textbox3.Text += line;
Textbox3.Text += "\r\n";
}
}
}
But this will only copy the line to Textbox3 if the line in Textbox1 and Textbox2 is totally identical, not just if the characters is identical.
So my question is: How do I do that?
Simply sort the strings and compare the results assuming they are equal length and not null this works:
private static bool IsPermutation(string one, string two)
{
var oneSorted = String.Join("", one.OrderBy(c => c).Select(x => x.ToString()).ToArray());
var twoSorted = String.Join("", two.OrderBy(c => c).Select(x => x.ToString()).ToArray());
return oneSorted == twoSorted;
}
EDIT: To answer the comment. Add that method to your class and replace the code inside your foreach with
if (line.Length == line1.Length && IsPermutation(line, line1))
{
Textbox3.Text += line;
Textbox3.Text += "\r\n";
}
The way I would go about this is
- Count the number of times each letter of your target word (textbox2) occurs
- Loop through the list of possible entries (textbox1) you have
- Count the number of times each letter of your possible entry occurs.
- If match, save word to textbox3, if not, continue.
To make this process even faster, as already pointed out, count the length of the string of the possible word first, if no match, then abandon this word and continue onto the next.
A further enhancement, when counting the letters of the possible entries, if you find a letter that is not in your target word, then abandon, and continue to the next word.
I would iterate through both lists. If the length of the strings is the same, continue (potential match). Given a potential match (same string lengths), then iterate through the characters in the source string, and ensure each exists in the string you are comparing it with.
You'll have to generate all the possible permutations of the random input and then compare each against the data. Like Nathaniel said you can optimize it by checking lengths first.
See http://msdn.microsoft.com/en-us/magazine/cc163513.aspx for code that generates string permutations (you'll want to get all character permutations of the random input string)
Edit
An answer to the question: Listing all permutations of a string/integer has a permutation generator that is more suited to your needs. Just add a List<string>
parameter to the go
and setper
methods and replace Console.Write (list);
with results.Add(list)
. When the method returns, the list you provided will have all the permutations.
精彩评论