четверг, 17 января 2008 г.

LINQанем анаграммы.

Задача (подсмотренно у Брэда Фитзпатрика)

Last night at Beau's party, one of Beau's guests mentioned he's expecting twins shortly, which is why is wife wasn't at the party.

I drunkenly suggested he name his kids two names that were anagrams of each other. I then wandered off downstairs to find such suitable names.



ЛИНКану решение:

   var pairs = from pair in
from name in
from name in File.ReadAllLines("d:\\dist.male.first") select name.Split(' ')[0]
group name by name.Sort()
where pair.Count() > 1
select pair;

foreach (var pair in pairs)
Console.WriteLine(String.Join(",", pair.ToArray()));


К сожалению в .NET Framework нет встроенной функции сортировки строки...
Поэтому полный вариант выглядит не так красиво. Опять же обрамление из using...

using System;
using System.IO;
using System.Linq;

namespace anagram
{
static class Program
{
public static string Sort(this string s)
{
char[] arr = s.ToArray();
Array.Sort(arr);
return new string(arr);
}

static void Main(string[] args)
{
var pairs = from pair in
from name in
from name in File.ReadAllLines("d:\\dist.male.first") select name.Split(' ')[0]
group name by name.Sort()
where pair.Count() > 1
select pair;

foreach (var pair in pairs)
Console.WriteLine(String.Join(",", pair.ToArray()));
}
}
}

Комментариев нет: