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...
Related
I'm learning C# and am trying to implement a versatile RandomVar class along with some methods for computing common statistics as practice. I'd like to be able form the arbitrary Joint probability RandomVariable from its components by instantiating a new variable of dimension N where N is passed into the constructor. I'd like to implement random Var X as two one dimensional lists of doubles, and the randomVar XY not as two lists of length n^2, but as a randomVar of type double[][] which otherwise can still use all of the same methods (ExpectedValue, Covariance, etc).
I'm having a lot of trouble implementing this. Other than the first naive approach (which had lots of copy and pasting), I've tried inheriting from a base RandomVar class into a JointRandomVar class -- still a lot of copy-pasting. Now I'm trying to the probabilities and outcomes arrays of Class RandomVar as Generics of type List -- this however produces a lot of problems as I can't figure out how to write the methods in an adaptable way (The std_Dev method can't iterate over the way it needs to in general -- so I need some flexible way to define the method so that if the "dimension" of the random Var is 2, the std_Dev method will do a double loop, or flatten out the array for the process of iterating).
Wanting some design help from more experienced programmers -- is having the probabilities/outcomes arrays List the best way to pass a parameter like this?
Thank you very much for your assistance.
EDIT: Here is the the version of the code for all doubles, so people can read it since the un-updated version seemed more confusing to people. I'd like to be able to have all of these methods work on objects of type double[] for any dimension of array, and it to be possible to instantiate the class with _values and _probs having any dimension.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter_3_GUI
{
class RandomVar
{
private double[] _values;
private double[] _probs;
private double _mean;
private double _stddev;
private int _length;
private double _evalue;
public RandomVar(double[] values, double[] probs)
{
_values = values;
_probs = probs;
_mean = meanCalc(_values);
_stddev = stddevCalc(_values, _mean);
_length = _values.Length;
_evalue = expectedVal(_probs, _values, _length);
}
public double[] Values
{
get { return _values; }
set { _values = value; }
}
public double Mean
{
get { return _mean; }
}
public double Stdev
{
get { return _stddev; }
}
public static double meanCalc(double[] var)
{
double mean = var.Sum();
return mean;
}
public static double stddevCalc(double[] var, double mean)
{
double[] varianceArr = new double[var.Length];
for (int i = 0; i <= var.Length; i++)
varianceArr[i] = (var[i] - mean) * (var[i] - mean);
double variance = varianceArr.Sum();
double stddev = Math.Sqrt(variance);
return stddev;
{
}
}
public static double[][] multiplyProbs(RandomVar X, RandomVar Y, double[][] cprobMatrix)
{
double[][] probArr = new double[X._length][Y._length];
for (int i=0; i <= probArr.Length; i++)
{
for (int j =0; j <= probArr.Length; j++)
{
probArr[i][j] = Y._probs[j] * cprobMatrix[i][j];
}
}
return probArr;
}
public static RandomVar multiplyVars(RandomVar X, RandomVar Y, Func<double,double> f)
{
double[][] productArr = new double[X._length][Y._length];
for (int i=0; i<= productArr.Length; i++)
{
for (int j=0; j <= productArr.Length; i=j++)
{
productArr[i][j] = f(X._values[i], Y._values[j]);
}
}
double[][] probArr = multiplyProbs(X, Y, cprobMatrix);
RandomVar product = new RandomVar(productArr, probArr);
return product;
}
public static double expectedVal(double[] _probs, double[] _values, int _length)
{
double[] expectedArr = new double[_length];
for (int i = 0; i <= expectedArr.Length; i++)
{
expectedArr[i] = _probs[i] * _values[i];
}
double evalue = expectedArr.Sum();
return evalue;
}
public static double covarianceCalc(RandomVar X, RandomVar Y, Func<double, double> f)
{
RandomVar VarXY = multiplyVars(X, Y, f);
double correlation = expectedVal(VarXY._probs, VarXY._values, VarXY._length);
double covariance = correlation - (X._mean * Y._mean);
return covariance;
}
}
}
Is the cardinality of each dimension going to be the same? Your comment about "treating it as one long array of size n^k" suggests it is. That is, n is the length of value/probability pairs in each dimension.
The other question I have is, what is the reasoning behind passing the values and probabilities in two different arrays? If it were me, I'd declare a struct that contains the pairs, e.g.:
struct ValueProbPair
{
public readonly double Value;
public readonly double Probability;
public ValueProbPair(double value, double probability)
{
Value = value;
Probability = probability;
}
}
Finally, as far as your specific question goes…well, it's not clear what the specific question is. You seem to have a broad question regarding a flexible way to implement this.
It seems to me that the biggest challenge here (i.e. the roadblock with the least intuitively obvious solution) is in the title of your question:
Passing the dimension of an Array as a Parameter
You can do this, i.e. create an appropriate array object, by using the Array.CreateInstance(Type, int[]) overload. IMHO, it will also work better if (but is not required that) you can consolidate the value/probability pairs into a single struct.
The other big caveat is that you won't get the benefit of compiler optimizations for accessing array elements. You'll have to use e.g. the GetValue() method, which will most likely prevent the compiler from accessing array elements directly (the optimization is theoretically possible, but seems unlikely to me).
So, for example, you could do something like:
Array Combine(ValueProbPair[] newDimension, Array previousDimensions)
{
int[] rankLengths = new int[previousDimensions.Rank + 1];
for (int j = 0; j < previousDimensions.Rank; j++)
{
rankLengths[j] = previousDimensions.GetLength(j);
}
rankLengths[previousDimensions.Rank] = newDimension.Length;
Array result = Array.CreateInstance(typeof(ValueProbPair), rankLengths);
// then fill in your matrix using GetValue and SetValue to
// access individual array elements...
// Finally, return the new multi-dimensional array:
return result;
}
The various array method overloads that access elements use params array parameters, so you can without too much difficulty write code that can handle matrices of arbitrary dimension. E.g.:
IEnumerable<double> GetAllValues(Array source)
{
int[] index = new int[source.Rank];
while (true)
{
yield return (double)source.GetValue(index);
int j = 0;
while (++index[j] == source.GetLength(j))
{
index[j] = 0;
if (++j == index.Length)
{
yield break;
}
}
}
}
One last note: for dealing with value/probability, depending on your scenario you might actually find it makes more sense to do all this using dictionaries. There are different complications, but the basic building block would be Dictionary<double, object>, where the value is either double or another Dictionary<double, object>. Then if you are looking for e.g. a combined probability, you don't have to scan lists of values, but rather can just look them up directly as the key in the dictionary.
For example if both values are int type it adds them.... ie 2+2=4
if both values are float....ie 2.2+2.3=4.5
or if one value is string and second is int...ie 1 + Pak=1Pak
We will get these two values from user using tfwo textboxes
This would be one way of doing it. Without having to convert to string and than back to numeric.
public object Add(IConvertible a, IConvertible b)
{
if(IsNumeric(a) && IsNumeric(b))
return a.ToDouble(CultureInfo.InvariantCulture) + b.ToDouble(CultureInfo.InvariantCulture);
return a.ToString() + b.ToString();
}
public static bool IsNumeric(object o)
{
var code = (int)Type.GetTypeCode(o.GetType());
return code >= 4 && code <= 15;
}
You can't do it using generics. You'll receive string from your textbox anyway. The only thing to do is to implement it "manually" exactly this way as you said:
public string TrySumTwoStrings(string input1, string input2)
{
double numeric1, numeric2;
if (Double.TryParse(input1, out numeric1) && Double.TryParse(input2, out numeric2))
return (numeric1 + numeric2).ToString();
return input1 + input2;
}
There's no way to use generics if we have no different types (everything is typed as string here).
You wouldn't, generics cannot be constrained in a way to support arithmetic operators (or concatenation). You would need to create overloads.
public int Add(int x, int y)
public double Add(double x, double y)
public decimal Add(decimal x, decimal y)
// etc.
Of course, you still have the problem of determining how exactly to parse your data. The source being a TextBox, the data will inherently be strings. You will have to determine which type of number it should be, if any.
If doing this for a real application, you shouldn't have this problem. Your textbox should be expected to receive input from the user in the form of an integer, or a decimal, or a string, etc. If it's not convertible to the proper type, it's an invalid input from your user. You wouldn't want the input to have to be magically deduced.
string Str1 = textBox1.Text.Trim();
string Str2 = textBox2.Text.Trim();
double Num1,num2;
bool isNum1 = double.TryParse(Str1, out Num1);
bool isNum2 = double.TryParse(Str2, out Num2);
if (isNum1 && isNum2)
MessageBox.Show((isNum1 + isNum2).ToString());
else
MessageBox.Show( Str1 + Str2);
Check out http://www.yoda.arachsys.com/csharp/miscutil/ The MiscUtil library. It contains some very clever Expression Tree stuff to allow operators with generics. It's not going to work exactly how you want (as others have stated, you can't constrain types to have operators) but it should do exactly what you want.
I don't know how it handles adding different types together though, I've not tried that.
I would think it would take some processing the values before hand in order with things like String.PArse, Int.Parse, etc...
Take them in order of compplexity first because 1 will convert to string, however x will not convert to integer or float.
Officially changed my answer to same as comment...
Best suggestion I have on that would be allow the user to select what type to interpret the data as and pass to the appropriate function based on what the user meant, there would be too many ways to interprets char strings to know what the users intention was, code processes logic not intent.
I'm familiar with the System.Numerics.BigInteger class, but in my app, I'm only ever dealing with positive integers. Negative integers are an error case, and it'd be nice if there was an unsigned equivalent of the BigInteger type so I could remove all of these checks. Does one exist?
There's nothing in the framework, no. I would try to centralize the checks in as small a public API as possible, and then treat the data as valid for the rest of the time - just as you would for something like null checking. Of course, you still need to be careful if you perform any operations which could create a negative value (e.g. subtracting one from another).
You may be able to make the code slightly neater by creating an extension method, e.g.
public static void ThrowIfNegative(this BigInteger value, string name)
{
if (value.Sign < 0)
{
throw new ArgumentOutOfRangeException(name);
}
}
... and use it like this:
input.ThrowIfNegative("input");
You could potentially create your own UBigInteger struct which contained a BigInteger, and perform operations between different values by using the BigInteger implementation and checks, but I suspect that would be quite a lot of work for relatively little benefit, and may have performance implications if you're using it for a lot of calculations.
Well, let's have a look at a simple example
uint a=1;
uint b=2;
uint c=a-b;
Console.WriteLine(c);
gives you the output 4294967295 (=2^32-1).
But what if you had an unsigned BigInteger with similar behaviour?
UBigInteger a(1);
UBigInteger b(2);
UBigInteger c=a-b;
Console.WriteLine(c.ToString());
What should that be? Of course, from what you wrote one can assume you might expect to get some kind of exception in this case, but such behaviour would not be consistent to int. Better introduce the checks for < 0 where you need them, for example, like the way Jon Skeet suggested.
If you only use a reasonably small subset of the the BigInteger API, writing your own wrapper class is easy if laborious. Here is some sample code to demonstrate that it needn't be that big an operation:
public struct UnsignedBigInteger
{
private BigInteger value;
private UnsignedBigInteger(BigInteger n) { value = n; }
public UnsignedBigInteger(uint n) { value = new BigInteger(n); }
// ... other constructors ...
public static UnsignedBigInteger operator+(UnsignedBigInteger lhs, UnsignedBigInteger rhs)
{
return new UnsignedBigInteger(lhs.value + rhs.value);
}
public static UnsignedBigInteger operator-(UnsignedBigInteger lhs, UnsignedBigInteger rhs)
{
var result = lhs.value - rhs.value;
if (result < BigInteger.Zero) throw new InvalidOperationException("value out of range");
return new UnsignedBigInteger(result);
}
// ... other operators ...
}
If negative values present such a problem, is possible to eliminate them somehow so that bad data(the negative values) doesn't even reach your logic ? This will eliminate the check all together. Could you post a short snippet of what you are doing ?
There isn't any support in the framework to declare BigInteger as unsigned. However, you could create a static method to check if the number is negative or not.
public static void ValidateBigIntForUnsigned(BigInteger bigInteger)
{
if(bigInteger.Sign < 0)
throw new Exception("Only unsigned numbers are allowed!");
}
I have a string that contains numbers separated by periods. When I sort it appears like this since it is a string: (ascii char order)
3.9.5.2.1.1
3.9.5.2.1.10
3.9.5.2.1.11
3.9.5.2.1.12
3.9.5.2.1.2
3.9.5.2.1.3
3.9.5.2.1.4
etc.
I want it to sort like this: (in numeric order)
3.9.5.2.1.1
3.9.5.2.1.2
3.9.5.2.1.3
...
3.9.5.2.1.9
3.9.5.2.1.10
3.9.5.2.1.11
3.9.5.2.1.12
I know that I can:
Use the Split function to get the individual numbers
Put the values into an object
Sort the object
I prefer to avoid all of that work if it is duplicating existing functionality. Is a method in the .net framework that does this already?
Here's my working solution that also takes care of strings that are not in the right format (e.g. contain text).
The idea is to get the first number within both strings and compare these numbers. If they match, continue with the next number. If they don't, we have a winner. If one if these numbers isn't a number at all, do a string comparison of the part, which wasn't already compared.
It would be easy to make the comparer fully compatible to natural sort order by changing the way to determine the next number.
Look at that.. just found this question.
The Comparer:
class StringNumberComparer : IComparer<string>
{
public int Compare(string x, string y)
{
int compareResult;
int xIndex = 0, yIndex = 0;
int xIndexLast = 0, yIndexLast = 0;
int xNumber, yNumber;
int xLength = x.Length;
int yLength = y.Length;
do
{
bool xHasNextNumber = TryGetNextNumber(x, ref xIndex, out xNumber);
bool yHasNextNumber = TryGetNextNumber(y, ref yIndex, out yNumber);
if (!(xHasNextNumber && yHasNextNumber))
{
// At least one the strings has either no more number or contains non-numeric chars
// In this case do a string comparison of that last part
return x.Substring(xIndexLast).CompareTo(y.Substring(yIndexLast));
}
xIndexLast = xIndex;
yIndexLast = yIndex;
compareResult = xNumber.CompareTo(yNumber);
}
while (compareResult == 0
&& xIndex < xLength
&& yIndex < yLength);
return compareResult;
}
private bool TryGetNextNumber(string text, ref int startIndex, out int number)
{
number = 0;
int pos = text.IndexOf('.', startIndex);
if (pos < 0) pos = text.Length;
if (!int.TryParse(text.Substring(startIndex, pos - startIndex), out number))
return false;
startIndex = pos + 1;
return true;
}
}
Usage:
public static void Main()
{
var comparer = new StringNumberComparer();
List<string> testStrings = new List<string>{
"3.9.5.2.1.1",
"3.9.5.2.1.10",
"3.9.5.2.1.11",
"3.9.test2",
"3.9.test",
"3.9.5.2.1.12",
"3.9.5.2.1.2",
"blabla",
"....",
"3.9.5.2.1.3",
"3.9.5.2.1.4"};
testStrings.Sort(comparer);
DumpArray(testStrings);
Console.Read();
}
private static void DumpArray(List<string> values)
{
foreach (string value in values)
{
Console.WriteLine(value);
}
}
Output:
....
3.9.5.2.1.1
3.9.5.2.1.2
3.9.5.2.1.3
3.9.5.2.1.4
3.9.5.2.1.10
3.9.5.2.1.11
3.9.5.2.1.12
3.9.test
3.9.test2
blabla
No, I don't believe there's anything in the framework which does this automatically. You could write your own IComparer<string> implementation which doesn't do any splitting, but instead iterates over both strings, only comparing as much as is required (i.e. parsing just the first number of each, then continuing if necessary etc) but it would be quite fiddly I suspect. It would also need to make assumptions about how "1.2.3.4.5" compared with "1.3" for example (i.e. where the values contain different numbers of numbers).
Since the comparison you want to do on the strings is different from how strings are normally compared in .Net, you will have to use a custom string string comparer
class MyStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
// your comparison logic
// split the string using '.' separator
// parse each string item in split array into an int
// compare parsed integers from left to right
}
}
Then you can use the comparer in methods like OrderBy and Sort
var sorted = lst.OrderBy(s => s, new MyStringComparer());
lst.Sort(new MyStringComparer());
This will give you the desired result. If not then just tweak the comparer.
What you are looking for is the natural sort order and Jeff Atwood bloged about it and has links to implementations in different languages. The .NET Framework does not contain an implementation.
Is it possible for you to pad your fields to the same length on the front with 0? If so, then you can just use straight lexicographic sorting on the strings. Otherwise, there is no such method built in to the framework that does this automatically. You'll have to implement your own IComparer<string> if padding is not an option.
Not really, though you may be able to use Regexes or Linq to avoid too much wheel-reinventing. Keep in mind it will cost you much the same computationally to use something built-in as to roll your own.
Try this:
List<string> myList = GetNumberStrings();
myList.Select(s=>s.Split('.')).ToArray().
.Sort((a,b)=>RecursiveCompare(a,b))
.Select(a=>a.Aggregate(new StringBuilder(),
(s,sb)=>sb.Append(s).Append(".")).Remove(sb.Length-1, 1).ToString())
.ToList();
...
public int RecursiveCompare(string[] a, string[] b)
{
return RecursiveCompare(a,b,0)
}
public int RecursiveCompare(string[] a, string[] b, int index)
{
return index == a.Length || index == b.Length
? 0
: a[index] < b[index]
? -1
: a[index] > b[index]
? 1
: RecursiveCompare(a,b, index++);
}
Not the most compact, but it should work and you could use a y-combinator to make the comparison a lambda.
Split each string by '.', iterate through the components and compare them numerically.
This code also assumes that the number of components is signficant (a string '1.1.1' will be greater than '2.1'. This can be adjusted by altering the first if statement in the Compare method below.
int Compare(string a, string b)
{
string[] aParts = a.Split('.');
string[] bParts = b.Split('.');
/// if A has more components than B, it must be larger.
if (aParts.Length != bParts.Length)
return (aParts.Length > bParts.Length) ? 1 : -1;
int result = 0;
/// iterate through each numerical component
for (int i = 0; i < aParts.Length; i++)
if ( (result = int.Parse(aParts[i]).CompareTo(int.Parse(bParts[i]))) !=0 )
return result;
/// all components are equal.
return 0;
}
public string[] sort()
{
/// initialize test data
string l = "3.9.5.2.1.1\n"
+ "3.9.5.2.1.10\n"
+ "3.9.5.2.1.11\n"
+ "3.9.5.2.1.12\n"
+ "3.9.5.2.1.2\n"
+ "3.9.5.2.1.3\n"
+ "3.9.5.2.1.4\n";
/// split the large string into lines
string[] arr = l.Split(new char[] { '\n' },StringSplitOptions.RemoveEmptyEntries);
/// create a list from the array
List<string> strings = new List<string>(arr);
/// sort using our custom sort routine
strings.Sort(Compare);
/// concatenate the list back to an array.
return strings.ToArray();
}
You can use the awesome AlphanumComparator Alphanum natural sort algorithm by David Koelle.
Code:
OrderBy(o => o.MyString, new AlphanumComparator())
If you're gonna use the C# version change it to:
AlphanumComparator : IComparer<string>
and
public int Compare(string x, string y)
In addition to implementing your own IComparer as Jon mentions, if you call ToList() on your array, you can call the .Sort() method and pass in a function parameter that compares two values, as shown here: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx
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);
}
}