Skip to content

Instantly share code, notes, and snippets.

@pocketberserker
Last active December 19, 2015 03:29
Show Gist options
  • Save pocketberserker/5890266 to your computer and use it in GitHub Desktop.
Save pocketberserker/5890266 to your computer and use it in GitHub Desktop.
LINQ勉強会 (http://atnd.org/events/39864) で書いたもの
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqStudy
{
public class LinqStudy
{
public static int Euler1(int max)
{
return Enumerable.Range(0, max).Where(j => j % 3 == 0 || j % 5 == 0).Sum();
}
public static readonly double SqrtFive = Math.Sqrt(5.0);
public static readonly double Phi = (1.0 + SqrtFive) / 2.0;
private static IEnumerable<int> Infinite()
{
var value = 0;
while (true)
yield return value++;
}
public static int Euler2(int limit)
{
return Infinite()
.Select(i => (int)Math.Floor(Math.Pow(Phi, i) / SqrtFive + 0.5))
.Where(i => i % 2 == 0)
.TakeWhile(i => i < limit)
.Sum();
}
}
}
module LinqStudy
open System
let euler1 num =
[ 0 .. num - 1 ]
|> List.filter (fun x -> x % 3 = 0 || x % 5 = 0)
|> List.sum
let sqrtFive = sqrt 5.0
let phi = (1.0 + sqrtFive) / 2.0
let infiniteIntSeq = Seq.unfold (fun i -> Some(i + 1, i + 1)) 0 |> Seq.cache
let euler2 limit =
infiniteIntSeq
|> Seq.map(fun x -> pown phi x / sqrtFive + 0.5 |> floor |> int)
|> Seq.filter (fun x -> x % 2 = 0)
|> Seq.takeWhile (fun x -> x < limit)
|> Seq.sum
// using MSTest and ChainingAssetion
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinqStury
{
[TestClass]
public class LinqStudyTest
{
[TestMethod]
public void Euler1のテスト()
{
LinqStudy.LinqStudy.Euler1(1000).Is(233168);
}
[TestMethod]
public void Euler2のテスト()
{
LinqStudy.LinqStudy.Euler2(4000000).Is(4613732);
}
}
}
// use FsUnit
module LinqStudy.Test
open NUnit.Framework
open FsUnit
open LinqStudy
[<Test>]
let ``Euler1のテスト``() =
euler1 1000 |> should equal 233168
[<Test>]
let ``Euler2のテスト``() =
euler2 4000000 |> should equal 4613732
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment