Показаны сообщения с ярлыком LINQ. Показать все сообщения
Показаны сообщения с ярлыком LINQ. Показать все сообщения

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

Ударим LINQом по Project Eiler

Задача 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.


Решение.

static void eiler1(){
Console.WriteLine((from i in Enumerable.Range(0, 1000) where (i % 3 == 0) || (i % 5 == 0) select i).Sum());
}


такие дела.

Задача 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed one million.


Решение (понадобилась дополнительная функция)

using System;
using System.Linq;
using System.Collections.Generic;

namespace eiler{
class Program
{
public static IEnumerable fibonator(int max){
int prev = 1;
int curr = 2;
while (true){
yield return curr;
int nprev = prev + curr;
curr += nprev;
prev = nprev;
if (curr >= max)
yield break;

}
}
static void Main(string[] args){
Console.WriteLine(
(from i in fibonator(1000000) select i).Sum() );
}
}
}

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()));
}
}
}

пятница, 4 января 2008 г.

"wwwdot - google = dotcom" - LINQy way

        static void Main(string[] args)

        {

            //"wwwdot - google = dotcom"

            var result = from w in Enumerable.Range(0,9)

                    from d in Enumerable.Range(0,9)

                    from o in Enumerable.Range(0,9)

                    from t in Enumerable.Range(0,9)

                    from g in Enumerable.Range(0,9)

                    from l in Enumerable.Range(0,9)

                    from e in Enumerable.Range(0,9)

                    from c in Enumerable.Range(0,9)

                    from m in Enumerable.Range(0,9)

                    where (w*100000+w*10000+w*1000+d*100+o*10+t-g*100000-o*10000-o*1000-g*100-l*10-e == d*100000+o*10000+t*1000+c*100+o*10+m)

                    select new {w,d,o,t,g,l,e,c,m};

            result.ToList().ForEach((x) => Console.WriteLine(x));

        }

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

Вдогонку - 101 пример использования Linq

Вдогонку - 101 пример использования Linq от MicroSoft

Забавы с Linq

Навеяно дискуссией в RSDN MIT переходи со схемы на...

Разговор каким-то образом перекинулся на краткость которая сестра таланта и bash.
самопроизвольно возникла задача переписать вот такую команду
grep -h USER *.log | gawk "{ print $2 }" | sort | uniq

на Немерле.

В результате получилось вот что:

using Nemerle.List;

using System.IO.Directory;

using System.IO.File;

 

def search = "USER";

def files = GetFiles(folder).ToList().Filter(_.EndsWith(".log"));

def lines = Flatten(files.Map(ReadAllLines(_).ToList().Filter(_.Contains(search)));

def lines = lines.Map(line => line.Substring(line.IndexOf(search) + search.Length));

def lines = lines.Sort().RemoveDuplicates();



Интереса ради решил переписать этот пример с использованием Linq.
Вот что получилось (отбрасывая всякие using и прочее):

var x = (from n in Directory.GetFiles(@"D:\temp\!!!") where n.EndsWith(".log")

        from line in n.LinesFromFile() where line.Contains("USER")

        orderby line  select line).Distinct();


Результат не совсем "чистый" поскольку стандартной функции LinesFromFile нет. Пришлось написать свою. Поэтому для полноты картины стоит наверно также добавить код этой функции. Вообщем в целом код (включая заголовок) выглядит следующим образом:

using System;

using System.Collections.Generic;

using System.Linq;

using System.IO;

 

 

namespace test_bash

{

    public static class StreamReaderSequence

    {

        public static IEnumerable<string> LinesFromFile(this string path)    {

            using (StreamReader source = new StreamReader(path)){

                String line;

                while ((line = source.ReadLine()) != null)

                    yield return line;

            }

        }

    }

 

    class Program

    {

        static void Main(string[] args)    {

            var x = (from n in Directory.GetFiles(@"D:\temp\!!!") where n.EndsWith(".log")

                    from line in n.LinesFromFile() where line.Contains("USER")

                    orderby line  select line).Distinct();

 

            foreach (var i in x)

                Console.WriteLine(i);

        }

    }

}

среда, 7 ноября 2007 г.

Hellow World с использованием LINQ и Reflection

Забавы...

using System;

using System.Linq;

using System.Reflection;

 

namespace sillytests

{

    class Program

    {

        static void Main(string[] args)

        {

            foreach (var t in from fi in typeof(Reflect).GetFields() where !fi.IsStatic select fi.Name + " ")

                Console.Write(t.ToUpper());

 

        }

 

        class Reflect

        {

            public bool Hello;

            public int World;

            public string from;

            public double LINQ;

            public byte and;

            public float reflection;

            public static double BlaBlaber;

        }

    }

}