public static bool IsAnagramOf(this string word1, string word2)
{
return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
}
public static void Main()
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
string test = Console.ReadLine();
string[] split = test.Split(new Char[] { ',', '.', ' ' },
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < split.Length; i++)
{
foreach (string s in split)
{
if (split[i] != s)
if (split[i].IsAnagramOf(s))
{
Console.WriteLine(s);
}
}
}
Console.ReadLine();
}
\$\begingroup\$
\$\endgroup\$
1
-
\$\begingroup\$ I really don't see how could this have too high memory footprint. I think you need to include some more details. \$\endgroup\$ – svick Aug 8 '13 at 22:42
Add a comment
|
\$\begingroup\$
\$\endgroup\$
and just shortening it up Jesse's answer...
private static bool IsAnagramOf(this string word1, string word2)
{
return word1
.OrderBy(x => x)
.SequenceEqual(word2.OrderBy(x => x));
}
static void Main(string[] args)
{
using (var si = new StreamReader(Console.OpenStandardInput(8192)))
{
Console.SetIn(si);
var split = (Console.ReadLine() ?? "").Split(new[] {',', '.', ' '}, StringSplitOptions.RemoveEmptyEntries);
split.SelectMany(t => split.Where(s => (t != s) && t.IsAnagramOf(s))).ToList().ForEach(Console.WriteLine);
Console.ReadLine();
}
}
\$\begingroup\$
\$\endgroup\$
2
Not sure what memory issue you're having with this, but there is a simpler way to write this, since you're already employing LINQ:
private static bool IsAnagramOf(this string word1, string word2)
{
return word1
.OrderBy(x => x)
.SequenceEqual(word2.OrderBy(x => x));
}
private static void Main()
{
using (var si = new StreamReader(Console.OpenStandardInput(8192)))
{
Console.SetIn(si);
var test = Console.ReadLine();
var split = test == null
? Enumerable.Empty<string>().ToArray()
: test.Split(new[] { ',', '.', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in split.SelectMany(t => split.Where(s => (t != s) && t.IsAnagramOf(s))))
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
-
\$\begingroup\$ Will you please shed some light how using LINQ will be more beneficial than my code? \$\endgroup\$ – Rajiv Prathapan Aug 9 '13 at 8:00
-
\$\begingroup\$ It's shorter, more concise, and indicates intent rather than the way to get to the results. Optimized LINQ libraries may also give you the memory and/or speed you are looking for. Measure early and often! \$\endgroup\$ – Jesse C. Slicer Aug 9 '13 at 13:32