Friday, January 08, 2010

TekPub's Mastering LINQ Challenge

I have a subscription already to Tekpub, but I thought it’d be fun to participate in the challenge. Here is my solution:

 IEnumerable<int> primes = Enumerable
.Range(1, 100)
.Where(isPrime);
 private bool isPrime(int x)
{
return x==2 || (x!=1 && !Enumerable.Range(2, x/2).Any(y => x%y == 0));
}

So there you have it. I hope Justin Etheredge doesn’t consider the isPrime a custom LINQ method. If he does, then I guess my solution would look like this:

 IEnumerable<int> primes = Enumerable
.Range(1, 100)
.Where(x => x ==
2 || (x != 1 && !Enumerable.Range(2, x / 2).Any(y => x % y == 0)));

Check out the details of this challenge from Justin Etheredg’s Post.


Check out GREAT videos on Tekpub!


Here’s my test if you want to verify it’s working.

 [Test]
public void should_return_list_of_prime_numbers()
{
IEnumerable<int> primes = Enumerable
.Range(1, 100)
.Where(isPrime);

//2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
Assert.AreEqual(25, primes.Count());
Assert.AreEqual(2, primes.ToArray()[0]);
Assert.AreEqual(31, primes.ToArray()[10]);
Assert.AreEqual(73, primes.ToArray()[20]);
Assert.AreEqual(97, primes.ToArray()[24]);
}

private bool isPrime(int x)
{
return x==2 || (x!=1 && !Enumerable.Range(2, x/2).Any(y => x%y == 0));
}

kick it on DotNetKicks.com

blog comments powered by Disqus
Related Posts Plugin for WordPress, Blogger...