IEnumerable which returns Prime Numbers: smallest implementation - c#

Recently I wondered what might be the smallest implementation of an IEumerable which returns a given number of prime numbers. It should fit in this program:
static int Main(string[] args)
{
while(true)
{
Console.WriteLine("How many Primes?");
string line = Console.ReadLine();
if (line.Trim() == "") break;
int numPrimes;
if(!int.TryParse(line.Trim(), out numPrimes)) continue;
int i = 1;
foreach(int p in PrimeNumbers(numPrimes))
{
Console.WriteLine("{0}: {1}", i++, p);
}
}
return 0;
}

My attempt looks like this:
static IEnumerable<int> PrimeNumbers(int numPrimes)
{
yield return 2; // first prime number
for(int n=1, p = 3; n < numPrimes; p+=2)
{
if (!checkIfPrime(p)) continue;
n++;
yield return p;
}
}
// p > 2, odd
private static bool checkIfPrime(int p)
{
for (int t = 3; t <= Math.Sqrt(p); t += 2)
{
if (p % t == 0) return false;
}
return true;
}
It is an Iterator which yield returns all the prime numbers.

Yet another example of smallest C# program:
static IEnumerable<int> PrimeNumbers(int n)
{
return Enumerable.Range(2, int.MaxValue - 2)
.Where(i => ParallelEnumerable.Range(2, Math.Max(0, (int)Math.Sqrt(i) - 1))
.All(j => i % j != 0))
.Take(n);
}

public static IEnumerable<int> PrimeNumbers(int NumberPrimes)
{
yield return 2;
for (int i = 3; i < NumberPrimes; i = i + 2)
{
bool IsPrime = true;
System.Threading.Tasks.Parallel.For(2, i, (o, state) =>
{
if (i % o == 0)
{
IsPrime = false;
state.Break();
}
});
if (IsPrime)
{
yield return i;
}
}
}

Related

Why is this yield break not breaking the loop?

I wrote a method that takes as input a sequence (it can also be an infinite sequence) and an integer count and returns a new sequence that contains count elements taken from the input sequence, that are in positions which are prime numbers.
For example, if I have a sequence {5,13,84,10,2,6} and count = 3, the result sequence is {84,10,6}.
The class I wrote:
public static class PrimeMethod
{
public static IEnumerable<T> TakePrime<T>(this IEnumerable<T> s, int count)
{
var result = new List<T>();
if (s == null)
throw new ArgumentNullException();
if (count <= 0)
throw new ArgumentOutOfRangeException();
int x = 0;
int y = 0;
foreach (var i in s)
{
if (checkIfPrime(x) && y < count)
{
result.Add(i);
y++;
}
x++;
}
return result;
}
public static bool checkIfPrime(int num)
{
if (num == 0 || num == 1)
return false;
bool flag = false;
for (int i = 2; i < num; i++)
if (num % i == 0)
{
flag = true;
break;
}
if (!flag)
return true;
return false;
}
}
Now I have to write a parameterized test that takes as input a sequence from 0 to infinite and a size integer. The test must make sure that the size of the resulting list is equal to the parameter size.
I wrote this:
[TestCase(7)]
[TestCase(182)]
public void Check_Size(int size)
{
var list = List_Integers(size);
var result = list.TakePrime(size);
Assert.That(()=>result.Count(),Is.EqualTo(size));
}
public IEnumerable<int> List_Integers(int size)
{
var i = 0;
var list = new List<int>();
while(true)
{
var j = i;
i++;
list.Add(j);
if (list.TakePrime(size).Count() > size)
yield break;
yield return j;
}
}
Although I used a yield break the test never stops. Why is this not working?
UPDATE:
I realized my mistake and I changed List_Integers to this:
public IEnumerable<int> List_Integers(int size)
{
var i = 0;
var list = new List<int>();
var incr = size+1;
while(true)
{
var j = i;
i++;
list.Add(j);
if (list.TakePrime(size).Count() >= incr)
yield break;
yield return j;
}
}
It's still not working and I don't understand why.
You call
list.TakePrime(size)
Which (as you described and implemented yourself) will return a maximum of size primes. Hence it will never be greater than size.
I found the solution which is this:
[TestCase(7)]
[TestCase(182)]
public void Check_Size(int size)
{
var incr = size + 1;
var list = List_Integers(incr);
var result = list.TakePrime(size);
Assert.That(()=>result.Count(),Is.EqualTo(size));
}
public IEnumerable<int> List_Integers(int size)
{
var i = 0;
var list = new List<int>();
while(true)
{
var j = i;
i++;
list.Add(j);
if (list.TakePrime(size).Count() >= size)
yield break;
yield return j;
}
}

Can somebody tell me why this code is not working? I am trying to find the 10001st prime number

The code gives me the answer 43739 which is wrong. I don't know which part of the code I messed up, help would be much appreciated.
{
int primenumbers = 4;
int thenumber = 2;
int finalnumber = 0;
while (primenumbers <= 10001)
{
for (int x = 2; x < 10; x++)
{
if (thenumber % x == 0)
{
x = 10;
}
if (x == 9)
{
finalnumber = thenumber;
primenumbers += 1;
break;
}
}
thenumber += 1;
}
Console.WriteLine(finalnumber);
}
Let's split the initial problem into smaller ones: first, check for being prime:
private static bool IsPrime(int value) {
if (value <= 1)
return false;
else if (value % 2 == 0)
return value == 2;
int n = (int) (Math.Sqrt(value) + 0.5);
for (int d = 3; d <= n; d += 2)
if (value % d == 0)
return false;
return true;
}
Then enumerate prime numbers (2, 3, 5, 7, 11...):
// Naive; sieve algorithm will be better off
private static IEnumerable<int> Primes() {
for (int i = 1; ; ++i)
if (IsPrime(i))
yield return i;
}
Finally, query with a help of Linq:
using System.Linq;
...
int result = Primes().Skip(10000).First();
Console.Write(result);
And you'll get
104743

Find permutation of one string into other string program

Trying to make an program where it just check, if permutation of string s1 exists in string s2 or not.
Created below program and it works for below test case.
Input:
s1 = "ab"
s2 = "eidballl"
Output:
True
Explanation: s2 contains one permutation of s1 (that is ba).
But this get fail when, input s2="sdfdadddbd" , s1="ab", expected as, false, but got true.
I'm trying to figure out what is missing here. Using a sliding window approach. Below my code in c#:
public bool CheckInclusion(string s1, string s2) {
var intCharArray = new int[256];
foreach(char c in s1)
{
intCharArray[c]++;
}
int start=0,end=0;
int count=s1.Length;
bool found=false;
while(end<s2.Length)
{
if (intCharArray[s2[end]]>0) { count--;}
intCharArray[s2[end]]--;
Console.WriteLine("end:" + end + " start:"+ start);
if(end-start==s1.Length) {
if (count==0) {return true;}
if (intCharArray[s2[start]]>=0)
{
count++;
}
intCharArray[s2[start]]++;
start++;
}
end++;
}
return false;
}
you need to check all characters of permutation exist in any range of [i, i + p.Length) of the string
static class StringExtensions
{
public static bool ContainsAnyPermutationOf(this string str, string p)
{
Dictionary<char, int> chars_count = p.CreateChar_CountDictionary();
for (int i = 0; i <= str.Length - p.Length; i++)
{
string subString = str.Substring(i, p.Length);
if (DictionaryMatch(chars_count, subString.CreateChar_CountDictionary()))
{
return true;
}
}
return false;
}
private static bool DictionaryMatch(Dictionary<char, int> dictionary1, Dictionary<char, int> dictionary2)
{
if (dictionary1.Count != dictionary2.Count)
{
return false;
}
foreach (var kvp in dictionary1)
{
if (!dictionary2.ContainsKey(kvp.Key))
{
return false;
}
dictionary2[kvp.Key] = dictionary2[kvp.Key] - 1;
if (dictionary2[kvp.Key] == 0)
{
dictionary2.Remove(kvp.Key);
}
}
return true;
}
private static Dictionary<char, int> CreateChar_CountDictionary(this string str)
{
Dictionary<char, int> dic = new Dictionary<char, int>();
for (int i = 0; i < str.Length; i++)
{
if (!dic.ContainsKey(str[i]))
{
dic.Add(str[i], default);
}
dic[str[i]] = dic[str[i]] + 1;
}
return dic;
}
}
usage:
static void Main(string[] args)
{
Console.WriteLine("sdfdadddbd".ContainsAnyPermutationOf("ab"));
}
I guess the question is similar to LeetCode 567. These are simple, efficient, low-complexity accepted solutions:
C#
class Solution {
public bool CheckInclusion(string s1, string s2) {
int lengthS1 = s1.Length;
int lengthS2 = s2.Length;
if (lengthS1 > lengthS2)
return false;
int[] countmap = new int[26];
for (int i = 0; i < lengthS1; i++)
countmap[s1[i] - 97]++;
int[] bCount = new int[26];
for (int i = 0; i < lengthS2; i++) {
bCount[s2[i] - 97]++;
if (i >= (lengthS1 - 1)) {
if (allZero(countmap, bCount))
return true;
bCount[s2[i - (lengthS1 - 1)] - 97]--;
}
}
return false;
}
private bool allZero(int[] s1, int[] s2) {
for (int i = 0; i < 26; i++) {
if (s1[i] != s2[i])
return false;
}
return true;
}
}
Java
class Solution {
public boolean checkInclusion(String s1, String s2) {
int lengthS1 = s1.length();
int lengthS2 = s2.length();
if (lengthS1 > lengthS2)
return false;
int[] countmap = new int[26];
for (int i = 0; i < lengthS1; i++) {
countmap[s1.charAt(i) - 97]++;
countmap[s2.charAt(i) - 97]--;
}
if (allZero(countmap))
return true;
for (int i = lengthS1; i < lengthS2; i++) {
countmap[s2.charAt(i) - 97]--;
countmap[s2.charAt(i - lengthS1) - 97]++;
if (allZero(countmap))
return true;
}
return false;
}
private boolean allZero(int[] count) {
for (int i = 0; i < 26; i++)
if (count[i] != 0)
return false;
return true;
}
}
Python
class Solution:
def checkInclusion(self, s1, s2):
count_map_s1 = collections.Counter(s1)
count_map_s2 = collections.Counter(s2[:len(s1)])
for i in range(len(s1), len(s2)):
if count_map_s1 == count_map_s2:
return True
count_map_s2[s2[i]] += 1
count_map_s2[s2[i - len(s1)]] -= 1
if count_map_s2[s2[i - len(s1)]] == 0:
del(count_map_s2[s2[i - len(s1)]])
return count_map_s2 == count_map_a
Reference
The codes are explained in the following links:
LeetCode 567 Solution
LeetCode 567 Discussion Board
These two answers are also useful to look into:
Link 1
Link 2
private static bool CheckPermutationInclusion(string s1, string s2)
{
return Enumerable.Range(0, s2.Length - s1.Length)
.Select(i => s2.Substring(i, s1.Length))
.Any(x => x.All(y => s1.Contains(y)));
}
Description:
Enumerable.Range(Int32, Int32) Method: Generates a sequence of integral numbers within a specified range.
Enumerable.Select Method: Projects each element of a sequence into a new form.
Enumerable.All Method: Determines whether all elements of a sequence satisfy a condition.
Enumerable.Any Method: Determines whether any element of a sequence exists or satisfies a condition.
Do not forget using System.Linq;.

Print a string of fibonacci recursively in C#

Can that be done with no while loops?
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" #" + Fibonacci(number));
}
public static int Fibonacci(int number)
{
if (number <= 1)
{
return 1;
}
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
I can't even add a Console.WriteLine in the body of base case since it gets executed [number] number of times; Not sure how to do this without loops...
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Fibonacci(0, 1, 1, number);
}
public static void Fibonacci(int a, int b, int counter, int number)
{
Console.WriteLine(a);
if (counter < number) Fibonacci(b, a+b, counter+1, number);
}
public static int Fibonatchi(int position) {
if(position == 0) {
return 1;
}
if(position == 1) {
return 1;
} else {
return Fibonatchi(position - 2) + Fibonatchi(position - 1);
}
}
I didn't find a way to do it closest way is it to combine both loops + recursion
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
for(int counter=0;counter<number;counter++)
Console.WriteLine(" \n" + Fibonacci(counter) );
}
public static int Fibonacci(int number)
{
if (number == 0)
return 0;
else if(number ==1)
return 1;
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
namespace Algorithms
{
class Program
{
static void Main(string[] args)
{
string fibResult = "";
fibResult = FibCal(10);
Console.WriteLine(fibResult);
Console.ReadLine();
}
public static string FibCal(int n)
{
string series = "";
int k, f1, f2 , f = 0;
f1 = f2 = 1;
if (n < 2)
return n.ToString();
else
for (k = 0; k < n; k++)
{
f = f1 + f2;
f2 = f1;
f1 = f;
series += f.ToString() + ",";
}
return series;
}
}
}
Hope this helps
Using recursion in this fashion is a very bad idea. It will cause memory problems very quickly. I know you want to avoid using while/for loops, but an array is really the best way to go.
Using LINQ
public static void fibSeriesEx3()
{
List<int> lst = new List<int> { 0, 1 };
for (int i = 0; i <= 10; i++)
{
int num = lst.Skip(i).Sum();
lst.Add(num);
foreach (int number in lst)
Console.Write(number + " ");
Console.WriteLine();
}
}
That's a way to do it by returning a value into the main.
public static void Main() {
Console.WriteLine("Introduce the number");
int num = Convert.ToInt32(Console.ReadLine());
int num1 = 1, num2 = 1, counter = num-2;
//Take 2 out to match the list as first 2 numbers doesn't count in the function.
Console.WriteLine(Fibo(num1, num2, counter));
}
public static int Fibo(int num1, int num2, int counter) {
int temp = num1;
if (counter <= 0)
return num2;
else
return Fibo(num1 = num2, num2 += temp, counter-1);
}
public static class Golden
{
public static IEnumerable<long> Fibonacci()
{
var a = 0L;
var b = 1L;
var s = 0L;
yield return a;
while (a < long.MaxValue - b)
{
yield return b;
s = a + b;
a = b;
b = s;
}
}
public static IEnumerable<long> FibonacciR()
{
IEnumerable<long> Fibo(long a, long b)
{
yield return a;
if (a < long.MaxValue - b)
{
foreach (var v in Fibo(b, a + b))
{
yield return v;
}
}
}
return Fibo(0, 1);
}
}
I realize this may be an old thread, but oh well I think this kinda question is good in its nature.
Using while loop/or recursive way of doing is not the optimal way of doing as it takes a O(2^n) times. A better way to do this is using what is already in memory like below. This should take at most O(n) time.
Cheers!
static double fibDynamic(int n)
{
double[] array = new double[n];
array[0] = array[1] = 1;
for(int i = 2; i < n; i++)
{
array[i] = array[i - 1] + array[i - 2];
}
return array[n-1];
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
int n, i = 0, c;
Console.WriteLine("Enter the number of terms:");
n = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Fibonacci series\n");
for (c = 1; c <= n; c++)
{
int result = FibonacciFunction(i);
Console.Write(result + " " );
i++;
}
Console.WriteLine();
return 0;
}
public static int FibonacciFunction(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return (FibonacciFunction(n - 1) + FibonacciFunction(n - 2));
}
}
}
}
Simple and easy solution :
static void Main(string[] args)
{
int number;
Console.WriteLine("enter number");
number = int.Parse(Console.ReadLine());
Console.WriteLine(Recursive(number));
Console.ReadLine();
}
public static int Recursive(int number)
{
if (number <= 2)
{
return 1;
}
else
{
return Recursive(number - 1) + Recursive(number - 2);
}
}
Using one line code:
public static int Fibonacci(int i)
{
return i <= 2 ? 1 : Fibonacci(i - 1) + Fibonacci(i - 2);
}

permutation in c#

Is it possible to generate all permutations of a collection in c#?
char[] inputSet = { 'A','B','C' };
Permutations<char> permutations = new Permutations<char>(inputSet);
foreach (IList<char> p in permutations)
{
Console.WriteLine(String.Format("{{{0} {1} {2}}}", p[0], p[1], p[2]));
}
I've already faced the problem and I wrote these simple methods:
public static IList<T[]> GeneratePermutations<T>(T[] objs, long? limit)
{
var result = new List<T[]>();
long n = Factorial(objs.Length);
n = (!limit.HasValue || limit.Value > n) ? n : (limit.Value);
for (long k = 0; k < n; k++)
{
T[] kperm = GenerateKthPermutation<T>(k, objs);
result.Add(kperm);
}
return result;
}
public static T[] GenerateKthPermutation<T>(long k, T[] objs)
{
T[] permutedObjs = new T[objs.Length];
for (int i = 0; i < objs.Length; i++)
{
permutedObjs[i] = objs[i];
}
for (int j = 2; j < objs.Length + 1; j++)
{
k = k / (j - 1); // integer division cuts off the remainder
long i1 = (k % j);
long i2 = j - 1;
if (i1 != i2)
{
T tmpObj1 = permutedObjs[i1];
T tmpObj2 = permutedObjs[i2];
permutedObjs[i1] = tmpObj2;
permutedObjs[i2] = tmpObj1;
}
}
return permutedObjs;
}
public static long Factorial(int n)
{
if (n < 0) { throw new Exception("Unaccepted input for factorial"); } //error result - undefined
if (n > 256) { throw new Exception("Input too big for factorial"); } //error result - input is too big
if (n == 0) { return 1; }
// Calculate the factorial iteratively rather than recursively:
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
Usage:
var perms = Utilities.GeneratePermutations<char>(new char[]{'A','B','C'}, null);
There's nothing built in.
I've found a a couple of Code Project articles here and here which might help you implement your own class.
public static void Recursion(char[] charList, int loBound, int upBound )
{
for (int i = loBound; i <= upBound; i++)
{
swap(ref charList[loBound], ref charList[i]);
if (loBound == upBound)
{
Console.Write(charList);
Console.WriteLine("");
}
Recursion(charList, loBound + 1, upBound);
swap(ref charList[loBound], ref charList[i]);
}
}
public static void swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
public static void Main(string[] args)
{
string c = "123";
char[] c2 = c.ToCharArray();
Recursion(c2, 0, c2.Length-1);
Console.ReadKey();
}
I built these Extensions Methods for Enumerable<T>
The following Generics Methods can find Permutations as well as Combinations of an IEnumerable of any type.
Visit http://github.com/MathewSachin/Equamatics for more
using System;
using System.Collections.Generic;
using System.Linq;
namespace Equamatics
{
public static class Combinatorics
{
#region Permute
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> Input, int r = -1)
{
int n = Input.Count();
if (r == -1) foreach (var item in new Permutor<T>(Input).Recursion(0))
yield return item;
if (r > n) throw new ArgumentOutOfRangeException("r cannot be greater than no of elements");
foreach (var list in Input.Combinations(r))
foreach (var item in new Permutor<T>(list).Recursion(0))
yield return item;
}
class Permutor<T>
{
int ElementLevel = -1;
int[] PermutationValue;
T[] Elements;
public Permutor(IEnumerable<T> Input)
{
Elements = Input.ToArray();
PermutationValue = new int[Input.Count()];
}
public IEnumerable<IEnumerable<T>> Recursion(int k)
{
ElementLevel++;
PermutationValue[k] = ElementLevel;
if (ElementLevel == Elements.Length)
{
List<T> t = new List<T>();
foreach (int i in PermutationValue) t.Add(Elements[i - 1]);
yield return t;
}
else
for (int i = 0; i < Elements.Length; i++)
if (PermutationValue[i] == 0)
foreach (IEnumerable<T> e in Recursion(i))
yield return e;
ElementLevel--;
PermutationValue[k] = 0;
}
}
public static double P(int n, int r)
{
if (r < 0 | n < 0 | n < r) return Double.NaN;
else if (r == 0) return 1;
else if (n == r) return Factorial(n);
else
{
double Product = 1;
for (int i = n - r + 1; i <= n; ++i) Product *= i;
return Product;
}
}
#endregion
#region Combinations
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> Input, int r = -1)
{
if (r == -1)
{
yield return Input;
yield break;
}
int n = Input.Count();
if (r > n) throw new ArgumentOutOfRangeException("r cannot be greater than no of elements");
int[] Indices = Enumerable.Range(0, r).ToArray();
yield return Indices.Select(k => Input.ElementAt(k));
while (true)
{
int i;
for (i = r - 1; i >= 0; --i)
if (Indices[i] != i + n - r)
break;
if (i < 0) break;
Indices[i] += 1;
for (int j = i + 1; j < r; ++j)
Indices[j] = Indices[j - 1] + 1;
yield return Indices.Select(k => Input.ElementAt(k));
}
}
public static double C(int n, int r)
{
if (r < 0 | n < 0 | n < r) return Double.NaN;
else if (n - r == 1 | r == 1) return n;
else if (n == r | r == 0) return 1;
else if (n - r > r) return (P(n, n - r) / Factorial(n - r));
else return (P(n, r) / Factorial(r));
}
#endregion
public static double Factorial(int n)
{
if (n < 0) return Double.NaN;
else if (n == 0) return 1;
else
{
double Product = 1;
for (int i = 1; i <= n; ++i) Product *= i;
return Product;
}
}
public static int Derangement(int n)
{
double x = 0;
for (int i = 2; i <= n; ++i)
{
if (i % 2 == 0) x += (1 / Factorial(i));
else x -= (1 / Factorial(i));
}
return (int)(Factorial(n) * x);
}
public static int Catalan(int n) { return (int)C(2 * n, n) / (n + 1); }
}
}
`
A simple implementation using recursion
static void Main(string[] args)
{
char[] inputSet = { 'A', 'B', 'C' };
var permutations = GetPermutations(new string(inputSet));
foreach (var p in permutations)
{
Console.WriteLine(String.Format("{{{0} {1} {2}}}", p[0], p[1], p[2]));
}
}
public static List<string> GetPermutations(string str)
{
List<string> result = new List<string>();
if (str == null)
return null;
if (str.Length == 0)
{
result.Add("");
return result;
}
char c = str.ElementAt(0);
var perms = GetPermutations(str.Substring(1));
foreach (var word in perms)
{
for (int i = 0; i <= word.Length; i++)
{
result.Add(word.Substring(0, i) + c + word.Substring(i));
}
}
return result;
}

Categories