Generic Factorial function in C# - c#

I want to write a generic function to calculate factorial in C# ... like:
static T Factorial<T>(T n)
{
if (n <= 1)
return 1;
return Factorial<T>(n - 1);
}
but obviously having restriction that we can't perform operations on type 'T'. any alternative?

The problem is that generics don't support operators because they are static methods, and not part of an interface. However, you could probably use Generic Operators, which is available in the Miscellaneous Utility Library.

You would need to add a delegate parameter which performs the multiplication. Something like this
delegate T Multiply<T>(T a, T b);
So then your function would be defined like this:
static T Factorial<T>(T n, Multiply func)
{
... your code here
}
So when your factorial function is called, the caller would pass in the multiplication function:
int x = Factorial<int>(5, (a,b) => a * b);

There is no easy way to do this. I have seen some solutions that work around the problem, but they are fairly complicated. That said, if you really want to do this here are a few ideas:
If you can use .Net 4, you can cast n to dynamic and then perform the addition. You lose safety, of course - you could get an exception at runtime
You could always manually check the type from within your factorial function: If n is a short, cast to short, if n is a double, cast to double... etc. That is complicated and defeats part of the value of generics, but the outside API at least looks simple.

When's the last time you took the factorial of a string, or a character?
Why do you ever need a factorial of type T????
Besides this has been said numerous (prolly 1 million times now).
When you need to use a generic you need to tell the compiler the type.
For instance what if I had a generic stack class?
C# needs to know the elements type when I create my stack.
Otherwise it makes no sense for:
Stack<T> s = new Stack<T>();
s.Push(????); //how do I add items to the stack if we don't know what T is?
Instead you need to specify:
Stack<int> s = new Stack<int>();
s.Push(5);
s.Push(7);

This isn't specifically addressing your question about making the method generic, but your method as it stands will never return anything other than 1.
Supposing you were only working with integers, it should look like this:
static int Factorial(int n)
{
if (n <= 1)
return 1;
// note the multiplication in this step
return n * Factorial(n - 1);
}

public T Factorial<T>(T a, T b, Multiply<T> delegateMutliply, Difference<T> diffDelegate, BaseCondition<T> baseDelegate)
{
if (!baseDelegate(a, b))
return b;
return delegateMutliply(a, Factorial<T>(diffDelegate(a), b, delegateMutliply, diffDelegate, baseDelegate));
}
int y = p.Factorial(3, 1, (a, b) => a * b, (a) => --a, (a, b) => (a <= b) ? false : true);

Super old question but I'd like to add my 2 cents.
Factorial functions require f* = i
A quick function for the example above is:
class FindFactorial
{
static void Main()
{
Console.WriteLine("Please enter your number: ");
int n = int.Parse(Console.ReadLine());
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine(factorial);
}
}

Related

C# Recursive algorithm error using a.Skip(1) as input

using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
public static bool Aa(int[] a, int k)
{
for (int i = 1; i < a.Length; i++)
if (a[0] + a[i] == k)
return true;
if (a.Length != 1)
Aa(a.Skip(1), k);
return false;
}
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 2, 3, 2, 1 };
Console.WriteLine(Aa(a, 10));
Console.ReadLine();
}
}
The following build error occurs on the recursive method call Aa(a.Skip(1), k);
Argument 1: cannot convert from 'System.Collections.IEnumerable' to 'int[]'
you need to pass an Array obj to Aa Like this :
a.Skip().ToArray();
Like most LINQ methods,
Skip
is designed to work with enumerables, not arrays.
public static System.Collections.Generic.IEnumerable<TSource> Skip<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);
It is OK to pass in an array, but it will implicitly be
upcast
to the more generalized type
IEnumerable,
and that is also the type that will be returned by Skip.
int[] whatGoesIn = {1, 2, 3};
IEnumerable<int> whatComesOut = whatGoesIn.Skip(1);
You cannot safely
downcast
the return value to int[].
As proposed by others, LINQ has a convenient method
ToArray,
but think twice before using it.
The method will create a completely new array object, which is often a total waste of memory as well as CPU time.
Only use this method
when you really need an array.
In your case, ToArray would have to be called once for every element of the original array.
This will put a lot of strain on the heap.
With a big array, you will be seeing a lot of GC.
Make up your mind: either use Skip, or use arrays. Don't do both.
Option 1: Skip, without arrays
Follow the LINQ philosophy and use enumerables all the way.
This has the advantage that it will work on any enumerable: arrays, collections, lists, dictionaries...
So instead of declaring parameter a as an array:
public static bool Aa(int[] a, int k)
declare a as an enumerable:
public static bool Aa(IEnumerable<int> a, int k)
Notice this will immediately eliminate your error. It will introduce a few new ones though. Like in the for loop; IEnumerable<int> has no property Length.
for (int i = 1; i < a.Length; i++)
if (a[0] + a[i] == k)
return true;
Upon close inspection, you are basically looking for an array element that equals k - a[0]. Just use
Contains:
bool found = a.Skip(1).Contains(k - a.First());
if (found) return true;
Another reference to Length:
if (a.Length != 1)
Aa(a.Skip(1), k);
return false;
That's weird; you call Aa but don't do anything with its return value. You probably meant this:
if (a.Length != 1)
return Aa(a.Skip(1), k);
return false;
I will not use Count,
as it is potentially expensive on long enumerables.
I am not actually interested in the exact length; we can stop counting after the second element.
return a.Skip(1).Any() && Aa(a.Skip(1), k);
After refactoring, the whole function becomes a one-liner:
public static bool Aa(IEnumerable<int> a, int k)
{
return a.Skip(1).Contains(k - a.First()) || (a.Skip(1).Any() && Aa(a.Skip(1), k));
}
I'd recommend to make the function robust against zero-length arrays by moving the 'Any' check to the front.
public static bool Aa(IEnumerable<int> a, int k)
{
return a.Any() && (a.Skip(1).Contains(k - a.First()) || Aa(a.Skip(1), k));
}
Option 2: arrays, without Skip
Arrays have one big advantage over enumerables: they are fast.
OP's for loop is faster than my call to Contains.
There is no need to use Skip; just start iterating at a different index.
public static bool Aa(int[] a, int k, int start = 0)
{
for (int i = start + 1; i < a.Length; i++)
if (a[start] + a[i] == k)
return true;
if (start < a.Length)
return Aa(a, k, start + 1);
return false;
}
This is twice as fast as the ToArray solution, and three times as fast as enumerables.
Note
I'm not too thrilled about the use of recursion here,
because nesting depth is proportional to array length.
For long arrays, this may cause a stack overflow.
In theory, the compiler could optimize away the tail recursion, but even in .NET 6, it doesn't
(although this answer suggests otherwise).

Function definition in case of different type of arguments?

I am writing a simple program in which I have defined a function which accepts certain type of argument , now new requirement I got has same procedures to be done which I had already in written in earlier function , but this time it should on different type of argument.I am not able to call straight way this same function for two different types of arguments. So my question is how I should modify my function to behave in such a way. I am hoping that it is possible. I would like something as ,I have function like Sum(int 1,int j) now I would like to use same function for double type arguments.
This is called overloading. What you can do is simply write two functions:
public double Sum(int 1, int j)
public double Sum(double 1, double j)
And your program will call the appropriate one based on the arguments you pass to it.
Simple with generics
T Sum<T>(T i,T j) { ... }
However, you won't be able to do i+j or anything, so it depends.
Why don't you define a method with double as parameter type and later you can call it for integer values as well.
private double Sum(double a, double b)
{
return a+b;
}
and later you can call it like:
int a = 1;
int b = 2;
int Sum = (int) Sum(a,b);
Since an integer can be passed to a double type parameter. But if your method involves complex calculation then you are better of with multiple overloads of the Sum method with different types.
In .NET there is no type encompassing different numeric types. So you need two overloads of the same method, one that takes int arguments, one that takes double arguments.
You declare a new method with the same amount of parameters but different types.
public Int32 Sum(Int32 i, Int32 j)
{
return i + j;
}
public Double Sum(Double i, Double j)
{
return i + j;
}
So you have a method that takes int parameters
public int Sum(int val1,int val2)
{
return val1 + val2;
}
Now you need a method that takes doubles:
public double Sum(double val1,double val2)
{
return val1 + val2;
}
If you want a generic class which supports all "numeric" types you can have a look here:
http://www.codeproject.com/Articles/33617/Arithmetic-in-Generic-Classes-in-C
You can write GENERIC METHODS for different datatypes.
check this Link
Look more into this link. It shows how o create a function that can handle several datatypes.
int a = 2, b = 3;
double c = 2.345, d = 3.45;
object inta = a, intb = b;
object doublec = c, doubled = d;
Console.WriteLine(Sum(inta, intb).ToString());
Console.WriteLine(Sum(doublec, doubled).ToString());
public object Sum(object a, object b)
{
object sum = null;
if (a.GetType().ToString() == "System.Int32" && b.GetType().ToString() == "System.Int32")
{
sum = Convert.ToInt32(a.ToString()) + Convert.ToInt32(b.ToString());
}
if (a.GetType().ToString() == "System.Double" && b.GetType().ToString() == "System.Double")
{
sum = Convert.ToDouble(a.ToString()) + Convert.ToDouble(b.ToString());
}
return sum;
}

Clarification about delegates

What is the below code doing? I think the pointer will be changed to the multiply method.
But what is "+=" doing here. I am confused.
delegate int calc(int a , int b);
static void Main(string[] args)
{
calc c = new calc(Add);
c += new calc(Multiply);
Console.WriteLine(c(3, c(4, 2)));
Console.Read();
}
public static int Add(int a, int b)
{
return (a + b);
}
public static int Multiply(int a, int b)
{
return (a * b);
}
The + and += operator
Similar to how you use the + operator to add values, you can use the += operator to both add and assign back to the same value.
An example of these operators applied to ints:
int a = 5;
a += 7; // a is now 12
a = a + 11;
Console.WriteLine(a);
24
Combining delegates
As AVD mentioned, you use the + and += operators to combine delegates.
When you apply these operators to delegates, you aren't doing a mathematical "sum" or "sum and assign", like my example with ints. Instead you are modifying a list of methods to be called when you invoke the delegate.
From that article:
Delegates can be combined such that when you call the delegate, a whole list of methods are called - potentially with different targets
So when you add/combine delegates, you'll end up calling multiple methods.
If you change your code to:
public static int Add(int a, int b)
{
Console.WriteLine("From Add");
return (a + b);
}
public static int Multiply(int a, int b)
{
Console.WriteLine("From Multiply");
return (a * b);
}
Then you will see this output when you run the program:
From Add
From Multiply
From Add
From Multiply
24
This is because:
You combined the Add and Multiply delegates, so both get called when you call c(x, y)
Multiply is the last delegate you added to that chain of delegates
You are calling c(x, y) twice. This is similar to if you had called: Multiply(3, Multiply(4, 2))
Return values from combined delegates
That point about the last delegate you added to the chain is also mentioned in the article:
If a delegate type is declared to return a value (i.e. it's not declared with a void return type) and a combined delegate instance is called, the value returned from that call is the one returned by the last simple delegate in the list.
The last method you added to the chain was Multiply, so all other return values are thrown out, and only the return value from Multiply is used when you call c(x, y).
You can see this demonstrated in your program. 3 * 4 * 2 is 24, which is your program's output. None of your calls to Add impact the final result.
+= is like appending multiple calls to the delegate object. Since its a multicast delegates, you can append multiple destination calls to the a single delegate. To append to a delegate, you need new delegate objects. And thats whats been doing in the second line.
Its similar to,
CalcDelegate C1, C2;
C1 = new CalcDelegate(Add);
C2 = new CalcDelegate(Multiply);
C1 = C1 + C2;
Its called Combining the delegates.
You can think of delegates as a cross between value types (like int or double) and arrays of method addresses.
You know that if you write this code:
var x = 5;
var y = x + 2;
y += 3;
Then afterwards x == 5 & y == 10 even though y had an intermediate value of 7 this was "thrown away" when the final assignment occurred.
Quite clearly the final value of y isn't 3.
In your code you wrote this:
calc c = new calc(Add);
c += new calc(Multiply);
As with y, the final value of c isn't Multiply. It's really more like this:
c == { Add, Multiply }
When you then call something like c(4, 2) you are effectively calling both Add & Multiply and because the delegate returns a value you only get back the final delegate's value - in this case from Multiply - and that's what makes it appear that the "pointer" changed to the Multiply method.
You could try adding in this code before you call c:
c -= new calc(Multiply);
and this will effectively return c back to this:
c == { Add }
And this is why delegates appear to behave like arrays of method addresses.
Now if you change your Add & Multiply methods to look like this:
public static int Add(int a, int b)
{
Console.WriteLine("Add({0}, {1})", a, b);
return (a + b);
}
public static int Multiply(int a, int b)
{
Console.WriteLine("Multiply({0}, {1})", a, b);
return (a * b);
}
you can then watch the calls as they occur. Your original code runs like this:
Add(4, 2)
Multiply(4, 2)
Add(3, 8)
Multiply(3, 8)
24
I hope this helps.

How to get the sum of list of shorts using the extension method Sum()?

I was trying to do something like this -
List<short> listofshorts= new List<short>();
int s = listofshorts.Sum();
//this does not work...but same code works for a list of ints..
I got this compilation error -
'System.Collections.Generic.List' does not contain a definition for 'Sum' and the best extension method overload 'System.Linq.Queryable.Sum(System.Linq.IQueryable)' has some invalid arguments
Can anyone suggest how can I use an extension method to calculate the sum of shorts? For some reason the extension method does not support it ...
int s = listofshorts.Sum(d => d);
You can provide the lambda for the method:
List<short> listofshorts= new List<short>();
int s = listofshorts.Sum(a => (int)a);
// This throws an InvalidCastException in .NET 3.5 SP1+
// DO NOT USE THIS CODE
listOfShorts.Cast<int>().Sum();
In the interest of posterity, and pointing out this seemingly obvious solution doesn't work - I'm going to leave this answer with the following links about .NET 3.5 SP1+ behavior:
Puzzling Enumerable.Cast InvalidCastException
http://blogs.msdn.com/b/dinesh.kulkarni/archive/2008/08/10/net-fx-3-5-sp1-two-perf-improvements-linq-to-objects-and-linq-to-sql.aspx
http://blogs.msdn.com/b/ed_maurer/archive/2008/02/16/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx
You could do
int s = listofshorts.Aggregate((i1,i2) => i1+i2);
Like the others have suggested, you will need to cast the short objects to a type which is supported by the Enumerable.Sum method. Unfortunately there are no overloaded Sum method for some of the types like ulong, etc.
If you're gonna be needing it very often though, I'd recommend writing an extension method yourself, here's one I did a while back for ulong and ulong?, you can do something very similar for short or any other types you need:
public static ulong Sum(this IEnumerable<ulong> source)
{
var sum = 0UL;
foreach (var number in source)
{
sum += number;
}
return sum;
}
public static ulong? Sum(this IEnumerable<ulong?> source)
{
var sum = 0UL;
foreach (var nullable in source)
{
if (nullable.HasValue)
{
sum += nullable.GetValueOrDefault();
}
}
return sum;
}
P.S. my implementations are based on the Enumerable.Sum implementation after I took a peek with reflector purely out of curiosity :-P
I would probably chose the .ForEach() extension, you don't need any casting here
short sum = 0;
myListOfShort.ForEach(val => sum += val)

Mathematical Expression generation preferably without using stacks or queues

Given the allowed operators of +, /, -, *, and given a user inputted list of single digit numbers (any length allowed), how can I output all possible combinations of mathematical expressions (and the resulting values) that can be formed with the numbers and the given constant set of operators? I also want allow for scalability, for example, so that I can easily be able to add another operator in the mix (if possible).
Preferably the solution wouldn't use a stack or queue but they are not unacceptable.
For example, if the input is:
{1,3,5,7}
then possible output would be
(1+3)-(5+7) = -8
(1+5)-(3-7) = 10
etc...
(13+57) is not a possible combination since combining of the digits should not be allowed.
Also note: I was able to write something similar using Scheme to do this, but I can't seem to do it with Java or C#.
I'm not a Java or C# programmer, so here goes with a language-ignorant answer. Neither of your chosen languages seems to have an eval function. I'd suggest that you take on board Reverse Polish Notation. Capture the inputs as characters in a string or whatever you wish; encode the operators as characters too. Then, using iterators or whatever, generate all possible orderings of the input digits, followed by all possible orderings of the right number of binary operators. Then use a couple or so switch statements to translate each string into a result.
Sorry I can't be more explicit, got to rush.
Classic permutation problem.
The trick is to pass in a set of function pointers to create an operators array (stack, list, etc...). In C# and Java, function pointers can be implemented by objects and interfaces.
You then need to come up with all the various orderings of each list.
Note also that you can only have 3 operators and that it's ambiguous whether some of the operators can be applied to the sets on either side in different ways.
Eg//
a+b / c - d <> (a+b) / (c-d)
I'm not sure if brackets are also to be considered. If they are, the solution is a little trickier (though the principles are the same). Simply include a set of brackets and permeate those too (though you'll also have to consider the constraint that a left bracket must have a closing right bracket). I'll not cover that here.
Permutation algorithms abound for inputs, so just pick one and use it to generate all the various collections of operators and of numbers.
To calculate all the results simply iterate the list of operators, passing the list of numbers sequentially and you're done.
Eg//
public interface Operator {
public Double calc(int val1, int val2);
}
public class Add implements Operator {
public Double calc(int val1, int val2){
return Double(val1 + val2);
}
}
public class Sub implements Operator {
public Double calc(int val1, int val2){
return Double(val1 - val2);
}
}
public class Mul implements Operator {
public Double calc(int val1, int val2){
return Double(val1 * val2);
}
}
public class Div implements Operator {
public Double calc(int val1, int val2){
return Double(val1 / val2);
}
}
public static Double calc(Operator[] operator_list, int[] value_list)
{
Double ret_val = Double(value_list[0]);
for (int j = 0; j < operator_list.length(); j++){
Operator oper = operator_list[j];
ret_val = oper.calc(ret_val, value_list[j+1]);
}
return ret_val;
}
public static void main(String[] args)
{
int[] values = {1,2,3,4};
Operator add = new Add();
Operator div = new Div();
Operator mul = new Mul();
Operator sub = new Sub();
Operator[] operators = {add, div, sub, mul};
// Calculate from permutation algorithm...
// Don't forget to only generate three values for each permutation!
// out_perm_1 = {add, div, sub};
// out_perm_2 = {div, add, sub};
Operator[] operator_permutations = perm(operators);
// Calculate from permutation algorithm...
// val_perm_1 = {1,2,3,4};
// val_perm_2 = {2,1,3,4};
int[] value_permutations = perm(values);
// Interleave the two lists...
for (int i=0; i < output_permutations.length(); i++)
{
for (int j=0; j < value_permutations.length(); j ++)
{
System.out.println(calc(output_permutations[i], output_permutations[j]));
}
}
}
etc...

Categories