This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Listing all permutations of a string/integer
For example,
aaa .. aaz .. aba .. abz .. aca .. acz .. azz .. baa .. baz .. bba .. bbz .. zzz
Basically, imagine counting binary but instead of going from 0 to 1, it goes from a to z.
I have been trying to get this working to no avail and the formula is getting quite complex. I'm not sure if there's a simpler way to do it.
Edit
I have something like this at the moment but it's not quite there and I'm not sure if there is a better way:
private IEnumerable<string> GetWordsOfLength(int length)
{
char letterA = 'a', letterZ = 'z';
StringBuilder currentLetters = new StringBuilder(new string(letterA, length));
StringBuilder endingLetters = new StringBuilder(new string(letterZ, length));
int currentIndex = length - 1;
while (currentLetters.ToString() != endingLetters.ToString())
{
yield return currentLetters.ToString();
for (int i = length - 1; i > 0; i--)
{
if (currentLetters[i] == letterZ)
{
for (int j = i; j < length; j++)
{
currentLetters[j] = letterA;
}
if (currentLetters[i - 1] != letterZ)
{
currentLetters[i - 1]++;
}
}
else
{
currentLetters[i]++;
break;
}
}
}
}
For a variable amount of letter combinations, you can do the following:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var q = alphabet.Select(x => x.ToString());
int size = 4;
for (int i = 0; i < size - 1; i++)
q = q.SelectMany(x => alphabet, (x, y) => x + y);
foreach (var item in q)
Console.WriteLine(item);
var alphabet = "abcdefghijklmnopqrstuvwxyz";
//or var alphabet = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (char)i);
var query = from a in alphabet
from b in alphabet
from c in alphabet
select "" + a + b + c;
foreach (var item in query)
{
Console.WriteLine(item);
}
__EDIT__
For a general solution, you can use the CartesianProduct here
int N = 4;
var result = Enumerable.Range(0, N).Select(_ => alphabet).CartesianProduct();
foreach (var item in result)
{
Console.WriteLine(String.Join("",item));
}
// Eric Lippert’s Blog
// Computing a Cartesian Product with LINQ
// http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
// base case:
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach (var sequence in sequences)
{
var s = sequence; // don't close over the loop variable
// recursive case: use SelectMany to build the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] { item });
}
return result;
}
You have 26^3 counts for 3 "digits". Just iterate from 'a' to 'z' in three loops.
Here's a very simple solution:
for(char first = 'a'; first <= (int)'z'; first++)
for(char second = 'a'; second <= (int)'z'; second++)
for(char third = 'a'; third <= (int)'z'; third++)
Console.WriteLine(first.ToString() + second + third);
Related
If we run the following (thanks to #octavioccl for help) LINQ Query:
var result = stringsList
.GroupBy(s => s)
.Where(g => g.Count() > 1)
.OrderByDescending(g => g.Count())
.Select(g => g.Key);
It gives us all the strings which occur in the list atleast twice (but exactly matched i.e. Hamming Distance =0).
I was just wondering if there is an elegant solution (all solutions I have tried so far either use loops and a counter which is ugly or regex) possible where we can specify the hamming distance in the Where clause to get those strings as well which lie within the specified Hamming Distance range?
P.S: All the strings are of equal length
UPDATE
Really thanks to krontogiannis for his detailed answer. As I mentioned earlier, I want to get list of strings with hamming distance below the given threshold. His code is working perfectly fine for it (Thanks again).
Only thing remaining is to take the strings out of the 'resultset' and insert/add into a `List'
Basically this is what I want:
List<string> outputList = new List<string>();
foreach (string str in patternsList)
{
var rs = wordsList
.GroupBy(w => hamming(w, str))
.Where(h => h.Key <= hammingThreshold)
.OrderByDescending(h => h.Key)
.Select(h => h.Count());
outputList.Add(rs); //I know it won't work but just to show what is needed
}
Thanks
Calculating the hamming distance between two strings using LINQ can be done in an elegant way:
Func<string, string, int> hamming = (s1, s2) => s1.Zip(s2, (l, r) => l - r == 0 ? 0 : 1).Sum();
You question is a bit vague about the 'grouping'. As you can see to calculate the hamming distance you need two strings. So you either need to calculate the hamming distance for all the words in your string list vs an input, or calculate the distance between all for the words in your list (or something different that you need to tell us :-) ).
In any way i'll give two examples for input
var words = new[] {
"hello",
"rellp",
"holla",
"fooba",
"hempd"
};
Case 1
var input = "hello";
var hammingThreshold = 3;
var rs = words
.GroupBy(w => hamming(w, input))
.Where(h => h.Key <= hammingThreshold)
.OrderByDescending(h => h.Key);
Output would be something like
hempd with distance 3
rellp holla with distance 2
hello with distance 0
Case 2
var hs = words
.SelectMany((w1, i) =>
words
.Where((w2, j) => i > j)
.Select(w2 => new { Word1 = w1, Word2 = w2 })) // all word pairs except with self
.GroupBy(pair => hamming(pair.Word1, pair.Word2))
.Where(g => g.Key <= hammingThreshold)
.OrderByDescending(g => g.Key);
Output would be something like
(holla, rellp) (fooba, holla) (hempd, hello) with distance 3
(rellp, hello) (holla, hello) with distance 2
Edit To get only the words from the first grouping you can use SelectMany
var output = rs.SelectMany(g => g).ToList();
OP asked for Hamming distance, my algorithm uses Levenshtein distance algorithm. But the code is easily transformable.
namespace Program
{
public static class Utils
{
public static string LongestCommonSubstring(this IEnumerable<string> arr)
{
// Determine size of the array
var n = arr.Count();
// Take first word from array as reference
var s = arr.ElementAt(0);
var len = s.Length;
var res = "";
for (var i = 0; i < len; i++)
{
for (var j = i + 1; j <= len; j++)
{
// generating all possible substrings
// of our reference string arr[0] i.e s
var stem = s.Substring(i, j - i);
var k = 1;
//for (k = 1; k < n; k++) {
foreach (var item in arr.Skip(1))
{
// Check if the generated stem is
// common to all words
if (!item.Contains(stem))
break;
++k;
}
// If current substring is present in
// all strings and its length is greater
// than current result
if (k == n && res.Length < stem.Length)
res = stem;
}
}
return res;
}
public static HashSet<string> GetShortestGroupedString(this HashSet<string> items, int distanceThreshold = 3, int minimumStringLength = 2)
{
var cluster = new Dictionary<int, List<Tuple<string, string>>>();
var clusterGroups = new HashSet<string>();
var itemCount = items.Count * items.Count;
int k = 0;
var first = items.First();
var added = "";
foreach (var item in items)
//Parallel.ForEach(merged, item => // TODO
{
var computed2 = new List<string>();
foreach (var item2 in items)
{
var distance = LevenshteinDistance.Compute(item, item2);
var firstDistance = LevenshteinDistance.Compute(first, item2);
if (!cluster.ContainsKey(distance)) // TODO: check false
cluster.Add(distance, new List<Tuple<string, string>>());
if (distance > distanceThreshold)
{
++k;
continue;
}
cluster[distance].Add(new Tuple<string, string>(item, item2));
if (firstDistance > distance)
{
var computed = new List<string>();
foreach (var kv in cluster)
{
if (kv.Value.Count == 0) continue;
var longest = kv.Value.Select(dd => dd.Item1).LongestCommonSubstring();
if (string.IsNullOrEmpty(longest)) continue;
computed.Add(longest);
}
var currentAdded = computed.OrderBy(s => s.Length).FirstOrDefault();
var diff = string.IsNullOrEmpty(added) || string.IsNullOrEmpty(currentAdded)
? string.Empty
: currentAdded.Replace(added, string.Empty);
if (!string.IsNullOrEmpty(currentAdded) && diff.Length == currentAdded.Length)
{
var ff = computed2.OrderBy(s => s.Length).FirstOrDefault();
if (ff.Length >= minimumStringLength)
clusterGroups.Add(ff);
computed2.Clear(); // TODO: check false
computed2.Add(diff);
}
else
{
if (diff.Length == 0 && !string.IsNullOrEmpty(added) && !string.IsNullOrEmpty(currentAdded))
computed2.Add(diff);
}
added = currentAdded;
cluster.Clear();
first = item;
}
++k;
}
var f = computed2.OrderBy(s => s.Length).FirstOrDefault();
if (f.Length >= minimumStringLength)
clusterGroups.Add(f);
}
//});
return clusterGroups;
}
}
/// <summary>
/// Contains approximate string matching
/// </summary>
internal static class LevenshteinDistance
{
/// <summary>
/// Compute the distance between two strings.
/// </summary>
public static int Compute(string s, string t)
{
var n = s.Length;
var m = t.Length;
var d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (var i = 0; i <= n; d[i, 0] = i++)
{
}
for (var j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (var i = 1; i <= n; i++)
{
//Step 4
for (var j = 1; j <= m; j++)
{
// Step 5
var cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
}
}
The code has two references:
The LevenshteinDistance class was extracted from: https://stackoverflow.com/a/2344347/3286975
The LongestCommonString method was extracted from: https://www.geeksforgeeks.org/longest-common-substring-array-strings/
My code is being reviewed at https://codereview.stackexchange.com/questions/272379/get-shortest-grouped-distinct-string-from-hashset-of-strings so I expect improvements on it.
You could do something like this:
int hammingDistance = 2;
var result = stringsList
.GroupBy(s => s.Substring(0, s.Length - hammingDistance))
.Where(g => g.Count() > 1)
.OrderbyDescending(g => g.Count())
.Select(g => g.Key);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Listing all permutations of a string/integer
For example,
aaa .. aaz .. aba .. abz .. aca .. acz .. azz .. baa .. baz .. bba .. bbz .. zzz
Basically, imagine counting binary but instead of going from 0 to 1, it goes from a to z.
I have been trying to get this working to no avail and the formula is getting quite complex. I'm not sure if there's a simpler way to do it.
Edit
I have something like this at the moment but it's not quite there and I'm not sure if there is a better way:
private IEnumerable<string> GetWordsOfLength(int length)
{
char letterA = 'a', letterZ = 'z';
StringBuilder currentLetters = new StringBuilder(new string(letterA, length));
StringBuilder endingLetters = new StringBuilder(new string(letterZ, length));
int currentIndex = length - 1;
while (currentLetters.ToString() != endingLetters.ToString())
{
yield return currentLetters.ToString();
for (int i = length - 1; i > 0; i--)
{
if (currentLetters[i] == letterZ)
{
for (int j = i; j < length; j++)
{
currentLetters[j] = letterA;
}
if (currentLetters[i - 1] != letterZ)
{
currentLetters[i - 1]++;
}
}
else
{
currentLetters[i]++;
break;
}
}
}
}
For a variable amount of letter combinations, you can do the following:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var q = alphabet.Select(x => x.ToString());
int size = 4;
for (int i = 0; i < size - 1; i++)
q = q.SelectMany(x => alphabet, (x, y) => x + y);
foreach (var item in q)
Console.WriteLine(item);
var alphabet = "abcdefghijklmnopqrstuvwxyz";
//or var alphabet = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (char)i);
var query = from a in alphabet
from b in alphabet
from c in alphabet
select "" + a + b + c;
foreach (var item in query)
{
Console.WriteLine(item);
}
__EDIT__
For a general solution, you can use the CartesianProduct here
int N = 4;
var result = Enumerable.Range(0, N).Select(_ => alphabet).CartesianProduct();
foreach (var item in result)
{
Console.WriteLine(String.Join("",item));
}
// Eric Lippert’s Blog
// Computing a Cartesian Product with LINQ
// http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
// base case:
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach (var sequence in sequences)
{
var s = sequence; // don't close over the loop variable
// recursive case: use SelectMany to build the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] { item });
}
return result;
}
You have 26^3 counts for 3 "digits". Just iterate from 'a' to 'z' in three loops.
Here's a very simple solution:
for(char first = 'a'; first <= (int)'z'; first++)
for(char second = 'a'; second <= (int)'z'; second++)
for(char third = 'a'; third <= (int)'z'; third++)
Console.WriteLine(first.ToString() + second + third);
I'm building a list of strings that contains all permutations of 2-letter strings, for instance "aa" to "zz". This is what I have:
public List<string> SomeMethod(int NumberOfChars) {
for (var i = 0; i < 26; i++)
{
char character1 = (char)(i + 97);
var Letter1 = character1.ToString();
for (var j = 0; j < 26; j++)
{
char character2 = (char)(j + 97);
var Letter2 = character2.ToString();
string TheString = Letter1 + Letter2;
TheList.Add(TheString);
}
}
return TheList;
}
Basically, it's a loop inside a loop that combines characters from the alphabet. Now suppose I want to include NumberOfChars as a parameter that determines the length of each string. For instance, if I pass in 2 it would return all 676 2-letter strings from "aa" to "zz" and if I pass in 3 it would return all 17,576 3-letter strings from "aaa" to "zzz".
For the moment, the easiest way to do it would be to have two different methods, one that returns 2-letter strings with two nested loops and another one that returns 3-letter strings with 3 nested loops.
What's a cleaner way to do this?
Thanks.
How about a method like this:
public IEnumerable<string> SomeMethod(int NumberOfChars)
{
if (NumberOfChars == 0)
{
yield return string.Empty;
}
else
{
for (var i = 'a'; i <= 'z'; i++)
{
foreach (var s in SomeMethod(NumberOfChars - 1))
{
yield return i + s;
}
}
}
}
And just for fun, here's another solution using Linq:
public IEnumerable<string> SomeMethod(int n)
{
var r = Enumerable.Range('a', 26).Select(x => ((char)x).ToString());
return (n > 1) ? r.SelectMany(x => SomeMethod(n - 1), (x, y) => x + y) : r;
}
Here's an alternative that uses a loop instead of recursion:
public static List<string> SomeMethod(int numberOfChars)
{
IEnumerable<string> results = new List<string> { "" };
for (int i = 0; i < numberOfChars; ++i)
results = from s in results
from c in Enumerable.Range('a', 26)
select s + (char)c;
return results.ToList();
}
I am developing a program in visual c# windows form application.
I need to find out the number of characters in a text box and display each characters' frequency in a list box. I have the following code:
private void btnCheckFrequency_Click(object sender, EventArgs e)
{
lstFreqMeter.Items.Clear();
string str;
int c = 1;
int strlen;
str = txtString.Text;
strlen = txtString.TextLength;
int[] counter = new int[strlen];
for (int i = 0; i < strlen; i++)
{
for (int j = i + 1; j < strlen; j++)
{
if (str[i] == str[j])
{
c += 1;
}
}
counter[i] = c;
c = 1;
}
for (int k = 0; k < counter.Length; k++)
{
lstFreqMeter.Items.Add(counter[k]);
}
}
In this code when I click the "Check Frequency" button the program gives, as output, the frequency of each character and repeated characters, and also spaces which we do not want.
3 loops to accomplish this is where you are going wrong. I think you are trying to make it too complicated.
Its frowned upon to give answers to homework questions, but some hints as to direction should help.
Declare a Dictionary<char, int>
Make only one loop. For each char in your string.
Inside the loop, populate a Dictionary<char, int> with your results.
If the char exists in the dictionary, set the int to int++, if not, add the char to the dictionary with int of 1.
Outside the loop, AddRange to your lstFreqMeter.Items.
You can get the number of chars in a string by using Count on the string.
Getting the frequency of each char you can iterate through the string and increment an integer. A dictionary (key/value list) would be a great datatype to hold this data.
const string textString = "aaabbbcccaaattteeevvvooo";
var numberOfChars = textString.Count();
var dictionary = new Dictionary<char,int>();
foreach (var letter in textString)
{
if (dictionary.ContainsKey(letter))
dictionary[letter]++;
else
dictionary[letter] = 1;
}
The Dictionary will contain a key (the char) and a value (the count).
Try something like this:
var letters = Enumerable.Range('A', 26).Select(i => (char)i);
var sourceChars = letters.Concat(myString.ToUpperInvariant());
var results = from c in sourceChars
group c by c into g
where char.IsLetter(g.Key)
orderby g.Key
select new { Char = g.Key, Count = g.Count() - 1 };
foreach (var result in results)
{
Console.WriteLine("There are {0} {1}'s.", result.Count, result.Char);
}
This will return you a class of how many times each letter appears in myString
Maintain a dictionary of the matched characters and increment each character count as it is matched.
Dictionary<char, int> count = new Dictionary<char,int>();
string str = textString.Text;
int len = str.Length;
for(int i = 0; i < len; i ++)
{
if (str[i] == ' ') continue;
if (count.ContainsKey(str[i]))
{
count[str[i]] += 1;
} else {
count.Add(str[i], 1);
}
}
foreach(char key in count.Keys)
{
Console.WriteLine("{0} : {1}", key, count[key]);
}
I dont know what iteration method to be used for more efficiency, Here i have listed my solution which i have tried. is there any other way to iterate, i mean any special methods or ways?
Method One :
Here i have used two for loops so the iteration goes for 2N times
public void CountChar()
{
String s = Ipstring();
int[] counts = new int[256];
char[] c = s.ToCharArray();
for (int i = 0; i < c.Length; ++i)
{
counts[c[i]]++;
}
for (int i = 0; i < c.Length; i++)
{
Console.WriteLine(c[i].ToString() + " " + counts[c[i]]);
Console.WriteLine();
}
}
Method 2 :
public void CountChar()
{
_inputWord = Ipstring();
char[] test = _inputWord.ToCharArray();
char temp;
int count = 0, tcount = 0;
Array.Sort(test);
int length = test.Length;
temp = test[0];
while (length > 0)
{
for (int i = 0; i < test.Length; i++)
{
if (temp == test[i])
{
count++;
}
}
Console.WriteLine(temp + " " + count);
tcount = tcount + count;
length = length - count;
count = 0;
if (tcount != test.Length)
temp = test[tcount];
//atchutharam. aaachhmrttu
}
}
Method three:
public void CountChar()
{
int indexcount = 0;
s = Ipstring();
int[] count = new int[s.Length];
foreach (char c in s)
{
Console.Write(c);
count[s.IndexOf(c)]++;
}
foreach (char c in s)
{
if (indexcount <= s.IndexOf(c))
{
Console.WriteLine(c);
Console.WriteLine(count[s.IndexOf(c)]);
Console.WriteLine("");
}
indexcount++;
////atchutharam
}
}
You can use LINQ methods to group the characters and count them:
public void CountChar() {
String s = Ipstring();
foreach (var g in s.GroupBy(c => c)) {
Console.WriteLine("{0} : {1}", g.Key, g.Count());
}
}
Your loops are not nested so your complexity is not N*N (O(n^2)) but 2*N which gives O(N) because you can always ignore constants :
for(){}
for(){} // O(2N) = O(N)
for()
{
for(){}
} // O(N*N) = O(N^2)
If you really want to know which one of these 3 solutions have the fastest execution time in a specific environment, do a benchmark.
If you want the one that is the most clean and readable (And you should almost always aim for that), just use LINQ :
String s = Ipstring();
int count = s.Count();
It will execute in O(N) too.
If you need the results in arrays:
var groups = s.GroupBy(i => i ).OrderBy( g => g.Key );
var chars = groups.Select(g => g.Key).ToArray();
var counts = groups.Select(g => g.Count()).ToArray();
Otherwise:
var dict = s.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
foreach (var g in dict)
{
Console.WriteLine( "{0}: {1}", g.Key, g.Value );
}