How to search through a jagged array - c#

This code should search an array of decimals for elements that are in a specified range, and return the number of occurrences of the elements that matches the range criteria.
The problem is that I am having trouble in accessing the jagged array, my code:
public static int GetDecimalsCount(decimal[] arrayToSearch, decimal[][] ranges)
{
if (arrayToSearch is null)
{
throw new ArgumentNullException(nameof(arrayToSearch));
}
else if (ranges is null)
{
throw new ArgumentNullException(nameof(ranges));
}
else
{
int sum = 0;
for (int i = 0; i < arrayToSearch.Length; i++)
{
for (int j = 0; j < ranges.Length; j++)
{
for (int n = 0; n < ranges[j].Length; n++)
{
if (arrayToSearch[i] >= ranges[j][n] && arrayToSearch[i] <= ranges[j][n + 1])
{
sum++;
}
}
}
}
return sum;
}
}
The ranges are from lowest to highest so it will always be arrays of two decimals
I was also confident this at least should work:
if (arrayToSearch[i] >= ranges[j][0] && arrayToSearch[i] <= ranges[j][1])
How does it not compare the array, I don't understand.
EDIT 1: Data in Arrays from Test
Inserting some of the test code, if you need full I can send it. It's a little long and it has unimportant test cases for other assignments.
private static readonly decimal[] ArrayWithFiveElements = { 0.1m, 0.2m, 0.3m, 0.4m, 0.5m };
private static readonly decimal[] ArrayWithFifteenElements = { decimal.MaxValue, -0.1m, -0.2m, decimal.One, -0.3m, -0.4m, -0.5m, decimal.Zero, 0.1m, 0.2m, 0.3m, 0.4m, 0.5m, decimal.MinusOne, decimal.MinValue };
[Test]
public void DecimalCounter_FiveElementsOneRange_ReturnsResult()
{
// Arrange
decimal[][] ranges =
{
new[] { 0.1m, 0.2m },
};
// Act
int actualResult = DecimalCounter.GetDecimalsCount(DecimalCounterTests.ArrayWithFiveElements, ranges);
// Assert
Assert.AreEqual(2, actualResult);
}
[Test]
public void DecimalCounter_FiveElementsTwoRanges_ReturnsResult()
{
// Arrange
decimal[][] ranges =
{
new[] { 0.1m, 0.2m },
new[] { 0.4m, 0.5m },
};
// Act
int actualResult = DecimalCounter.GetDecimalsCount(DecimalCounterTests.ArrayWithFiveElements, ranges);
// Assert
Assert.AreEqual(4, actualResult);
}

After fixing the errors pointed out in the comments I don't find any problem in the code ; https://dotnetfiddle.net/F6Yjy0
public static int GetDecimalsCount(decimal[] arrayToSearch, decimal[][] ranges)
{
if (arrayToSearch == null)
{
throw new ArgumentNullException(nameof(arrayToSearch));
}
else if (ranges == null)
{
throw new ArgumentNullException(nameof(ranges));
}
else
{
int sum = 0;
for (int i = 0; i < arrayToSearch.Length; i++)
{
for (int j = 0; j < ranges.Length; j++)
{
//for (int n = 0; n < ranges[j].Length; n++)
//{
if (arrayToSearch[i] >= ranges[j][0] && arrayToSearch[i] <= ranges[j][1])
{
sum++;
}
//}
}
}
return sum;
}
}
The innermost loop is rather pointless; it only runs once and can be replaced with indexing 0/1. Removing it also removes the OOB problem

Related

How to turn a recursive algorithm into a parallel processing recursive algorithm

I'm doing my homework for Algorithms and I stumbled into a problem. I was not able to transform a recursive algorithm to parallel process recursive algorithm.
This is the given equation I was given:
Equation
This is my code for this equation without parallel processing:
class Program
{
static void Main(string[] args)
{
List<int> p = new List<int> { 1, 2, 3, 4};
Console.WriteLine(F(4, 4, p));
}
public static int F(int k, int n, List<int> p)
{
List<int> maxList = new List<int>();
int ats = 0;
if (n == 0) { return 0; }
else if (k == 1)
{
ats = 0;
for (int i = 0; i < n; i++)
{
ats += p[i];
}
return ats;
}
else
{
for (int i = 0; i < n; i++)
{
ats = 0;
for (int j = i; j < n; j++)
{
ats += p[j];
}
int funkcija = F(k - 1, n - 1, p);
if (ats > funkcija)
{
maxList.Add(ats);
}
else
{
maxList.Add(funkcija);
}
}
}
ats = maxList.Min();
return ats;
}
}
I need to make this code to process parallel.
I tried changing for cycles into
I tried like this
public static int FPara(int k, int n, List<int> p)
{
List<int> maxList = new List<int>();
int ats = 0;
if (n == 0) { return 0; }
else if (k == 1)
{
ats = 0;
for (int i = 0; i < n; i++)
{
ats += p[i];
}
return ats;
}
else
{
Parallel.For(0, n - 1, i =>
{
ats = 0;
for (int j = i; j < n; j++)
{
ats += p[j];
}
int funkcija = F(k - 1, n - 1, p);
if (ats > funkcija)
{
maxList.Add(ats);
}
else
{
maxList.Add(funkcija);
}
});
}
ats = maxList.Min();
return ats;
}
however, it doesn't work.

calling merge sort c#

I wrote a merge sort program, but I have problems calling It from another class. I need help. For some reason after I enter the size and the max number a get a black screen in the output. I believe that the solution is pretty easy, but I can't find the solution by myself
This is the class where It sorts the numbers
class MergeSort
{
public int[] Sort(int[] unsortedSequence)
{
int[] left;
int[] right;
int[] result = new int[unsortedSequence.Length];
if (unsortedSequence.Length <= 1)
return unsortedSequence;
int midPoint = unsortedSequence.Length / 2;
left = new int[midPoint];
if (unsortedSequence.Length % 2 == 0)
right = new int[midPoint];
else
right = new int[midPoint + 1];
for (int i = 0; i < midPoint; i++)
left[i] = unsortedSequence[i];
int x = 0;
for (int i = midPoint; i < unsortedSequence.Length; i++)
{
right[x] = unsortedSequence[i];
x++;
}
left = Sort(left);
right = Sort(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] left, int[] right)
{
int resultLength = right.Length + left.Length;
int[] result = new int[resultLength];
int indexLeft = 0, indexRight = 0, indexResult = 0;
while (indexLeft < left.Length || indexRight < right.Length)
{
if (indexLeft < left.Length && indexRight < right.Length)
{
if (left[indexLeft] <= right[indexRight])
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
else if (indexLeft < left.Length)
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else if (indexRight < right.Length)
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
return result;
}
}
And this is the class where I'm trying to call the mergesort
class Program
{
static void Main(string[] args)
{
Console.Write("How Many Random Numbers Would you like to Generate : ");
int n = Convert.ToInt32(Console.ReadLine());
Console.Write("What is the Maximum Random Number Would you like to Generate : ");
int max = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int[] unsortedSequence = generateRandomSequence(n, max);
MergeSort mergeSortEngine = new MergeSort();
int[] mergeSortedArray = mergeSortEngine.Sort(unsortedSequence);
Console.Write("Output for Merge Sort: \n\n");
OutputSequence(mergeSortedArray);
Console.WriteLine("\n\nPress Any Key to Continue...");
Console.ReadKey();
Console.Clear();
Because you didn't provide them, I wrote the missing generateRandomSequence() and OutputSequence methods in order to test your code and I can't reproduce your issue. Perhaps you should compare these to your own:
static int[] generateRandomSequence(int count, int max)
{
Random rn = new Random();
int[] seq = new int[count];
for (int i = 0; i < count; ++i)
{
seq[i] = rn.Next(0, max + 1);
}
return seq;
}
static void OutputSequence(int[] array)
{
for (int i = 0; i < array.Length; ++i)
{
if (i > 0)
{
Console.Write(", ");
}
Console.Write(array[i]);
}
Console.WriteLine();
}
Output from your code using the above methods:
It looks like you missing generateRandomSequence(n, max);
It might be like
public static int[] generateRandomSequence(int n, int max)
{
var rnd = new Random();
int[] seq = new int[n];
for (int ctr = 0; ctr < n; ctr++)
{
seq[ctr] = rnd.Next(1, max + 1);
}
return seq;
}
Then, in Program/Test class after Console.Write("Output for Merge Sort: \n\n"); you can iterate with foreach loop to display the sorted array.
foreach (var item in mergeSortedArray)
{
Console.WriteLine("{0}", item);
}
//OutputSequence(mergeSortedArray);

How do i skip same values between 2 arrays

I'm stuck at "sorting" 2 different arrays.
My goal is to get rid of numbers that are included in array1 and array2.
Here is an example:
int [] arr1 = {1,2,3,4,5,6 } ;
int [] arr2 = {3,4} ;
Values in array arr1 should be like this : 1,2,5,6 (without 3 and 4)
My code so far:
static int[] test(int[]a,int[]b)
{
int i = 0;
int g = 0;
int d = 0;
int indexB = 0;
while( i < a.Length)
{
bool dvojnost = false;
int j = 0;
while (j<b.Length)
{
if (a[i] == b[j])
{
dvojnost = true;
indexB = j;
break;
}
else
j++;
}
int trenutniElementB = 0;
if(dvojnost==true)
{
while (trenutniElementB < b.Length)
{
if (trenutniElementB != indexB)
{
b[g] = b[trenutniElementB];
g++;
trenutniElementB++;
}
else
{
trenutniElementB++;
}
}
}
int h = 0;
if (dvojnost == true)
{
while (h < a.Length)
{
if (h != i)
{
a[d] = a[h];
d++;
h++;
}
else
{
h++;
}
}
}
i++;
}
return a;
}
This coding is only for extending my knowledge with arrays :)
Use LINQ :-)
int[] result = array1.Except(array2).ToArray();
If you are determined on using only loops and no Linq or Lists you could go for this...
static void Main(string[] args)
{
int[] arr1 = { 1, 2, 3, 4, 5, 6 };
int[] arr2 = { 3, 4 };
int[] result = test(arr1, arr2);
}
static int[] test(int[] a, int[] b)
{
int k = 0;
bool toAdd;
int[] output = new int[] { };
for (int i = 0; i < a.Length; i++)
{
toAdd = true;
for (int j = 0; j < b.Length; j++)
{
if (a[i] == b[j])
{
toAdd = false;
break;
}
}
if (toAdd)
{
Array.Resize(ref output, k + 1);
output[k] = a[i];
k++;
}
}
return output;
}
If you are treating second array as exclusion list for your result then maybe using generic List<> class will be enough to create simple code like this:
static int[] test(int[] a, int[] b)
{
List<int> result = new List<int>();
List<int> exclusion = new List<int>(b);
for (int i = 0; i < a.Length; i++)
{
if (exclusion.IndexOf(a[i]) >= 0)
continue;
result.Add(a[i]);
}
return result.ToArray();
}
Split your method into 2 parts.
First get rid of duplicates and then sort the array:
public int[] RemoveAndSort(int[] a, int[] b){
List<int> temp = new List<int>();
for(int i = 0; i < a.Length; i++){
bool found = false;
for(int j = 0; j < b.Length; j++){
if(a[i] == b[j]){
found = true;
}
}
if(!found) temp.Add(a[i]);
}
temp.Sort();
return temp.ToArray();
}
I used a List in my solution but you could also use a new empty array that is the same length of a at the start of the method.
Don't reinvent the wheel, use LINQ. Anyhow, if you are doing this as an excercise to understand arrays, here is an impementation that avoids LINQ altoghether:
public static T[] Except<T>(this T[] first, T[] second)
{
if (first == null)
throw new ArgumentNullException(nameof(first));
if (second == null)
throw new ArgumentNullException(nameof(second));
if (second.Length == 0)
return first;
var counter = 0;
var newArray = new T[first.Length];
foreach (var f in first)
{
var found = false;
foreach (var s in second)
{
if (f.Equals(s))
{
found = true;
break;
}
}
if (!found)
{
newArray[counter] = f;
counter++;
}
}
Array.Resize(ref newArray, counter);
return newArray;
}
You can try this, without any generics collections :) Only arrays:
public class Program
{
static void Main(string[] args)
{
int resultLength = 0;
int[] arr1 = { 1, 2, 3, 4, 5, 6 };
int[] arr2 = { 3, 4 };
int[] result = new int[resultLength];
for(int i = 0; i < arr1.Length; i++)
{
if(!arr2.Exists(arr1[i]))
{
resultLength++;
Array.Resize(ref result, resultLength);
result[resultLength- 1] = arr1[i];
}
}
}
}
public static class MyExtensions
{
public static bool Exists(this int[] array, int value)
{
for(int i = 0; i < array.Length; i++)
{
if (array[i] == value)
return true;
}
return false;
}
}

c# list permutations with limited length

I have a list of Offers, from which I want to create "chains" (e.g. permutations) with limited chain lengths.
I've gotten as far as creating the permutations using the Kw.Combinatorics project.
However, the default behavior creates permutations in the length of the list count. I'm not sure how to limit the chain lengths to 'n'.
Here's my current code:
private static List<List<Offers>> GetPerms(List<Offers> list, int chainLength)
{
List<List<Offers>> response = new List<List<Offers>>();
foreach (var row in new Permutation(list.Count).GetRows())
{
List<Offers> innerList = new List<Offers>();
foreach (var mix in Permutation.Permute(row, list))
{
innerList.Add(mix);
}
response.Add(innerList);
innerList = new List<Offers>();
}
return response;
}
Implemented by:
List<List<AdServer.Offers>> lst = GetPerms(offers, 2);
I'm not locked in KWCombinatorics if someone has a better solution to offer.
Here's another implementation which I think should be faster than the accepted answer (and it's definitely less code).
public static IEnumerable<IEnumerable<T>> GetVariationsWithoutDuplicates<T>(IList<T> items, int length)
{
if (length == 0 || !items.Any()) return new List<List<T>> { new List<T>() };
return from item in items.Distinct()
from permutation in GetVariationsWithoutDuplicates(items.Where(i => !EqualityComparer<T>.Default.Equals(i, item)).ToList(), length - 1)
select Prepend(item, permutation);
}
public static IEnumerable<IEnumerable<T>> GetVariations<T>(IList<T> items, int length)
{
if (length == 0 || !items.Any()) return new List<List<T>> { new List<T>() };
return from item in items
from permutation in GetVariations(Remove(item, items).ToList(), length - 1)
select Prepend(item, permutation);
}
public static IEnumerable<T> Prepend<T>(T first, IEnumerable<T> rest)
{
yield return first;
foreach (var item in rest) yield return item;
}
public static IEnumerable<T> Remove<T>(T item, IEnumerable<T> from)
{
var isRemoved = false;
foreach (var i in from)
{
if (!EqualityComparer<T>.Default.Equals(item, i) || isRemoved) yield return i;
else isRemoved = true;
}
}
On my 3.1 GHz Core 2 Duo, I tested with this:
public static void Test(Func<IList<int>, int, IEnumerable<IEnumerable<int>>> getVariations)
{
var max = 11;
var timer = System.Diagnostics.Stopwatch.StartNew();
for (int i = 1; i < max; ++i)
for (int j = 1; j < i; ++j)
getVariations(MakeList(i), j).Count();
timer.Stop();
Console.WriteLine("{0,40}{1} ms", getVariations.Method.Name, timer.ElapsedMilliseconds);
}
// Make a list that repeats to guarantee we have duplicates
public static IList<int> MakeList(int size)
{
return Enumerable.Range(0, size/2).Concat(Enumerable.Range(0, size - size/2)).ToList();
}
Unoptimized
GetVariations 11894 ms
GetVariationsWithoutDuplicates 9 ms
OtherAnswerGetVariations 22485 ms
OtherAnswerGetVariationsWithDuplicates 243415 ms
With compiler optimizations
GetVariations 9667 ms
GetVariationsWithoutDuplicates 8 ms
OtherAnswerGetVariations 19739 ms
OtherAnswerGetVariationsWithDuplicates 228802 ms
You're not looking for a permutation, but for a variation. Here is a possible algorithm. I prefer iterator methods for functions that can potentially return very many elements. This way, the caller can decide if he really needs all elements:
IEnumerable<IList<T>> GetVariations<T>(IList<T> offers, int length)
{
var startIndices = new int[length];
var variationElements = new HashSet<T>(); //for duplicate detection
while (startIndices[0] < offers.Count)
{
var variation = new List<T>(length);
var valid = true;
for (int i = 0; i < length; ++i)
{
var element = offers[startIndices[i]];
if (variationElements.Contains(element))
{
valid = false;
break;
}
variation.Add(element);
variationElements.Add(element);
}
if (valid)
yield return variation;
//Count up the indices
startIndices[length - 1]++;
for (int i = length - 1; i > 0; --i)
{
if (startIndices[i] >= offers.Count)
{
startIndices[i] = 0;
startIndices[i - 1]++;
}
else
break;
}
variationElements.Clear();
}
}
The idea for this algorithm is to use a number in offers.Count base. For three offers, all digits are in the range 0-2. We then basically increment this number step by step and return the offers that reside at the specified indices. If you want to allow duplicates, you can remove the check and the HashSet<T>.
Update
Here is an optimized variant that does the duplicate check on the index level. In my tests it is a lot faster than the previous variant:
IEnumerable<IList<T>> GetVariations<T>(IList<T> offers, int length)
{
var startIndices = new int[length];
for (int i = 0; i < length; ++i)
startIndices[i] = i;
var indices = new HashSet<int>(); // for duplicate check
while (startIndices[0] < offers.Count)
{
var variation = new List<T>(length);
for (int i = 0; i < length; ++i)
{
variation.Add(offers[startIndices[i]]);
}
yield return variation;
//Count up the indices
AddOne(startIndices, length - 1, offers.Count - 1);
//duplicate check
var check = true;
while (check)
{
indices.Clear();
for (int i = 0; i <= length; ++i)
{
if (i == length)
{
check = false;
break;
}
if (indices.Contains(startIndices[i]))
{
var unchangedUpTo = AddOne(startIndices, i, offers.Count - 1);
indices.Clear();
for (int j = 0; j <= unchangedUpTo; ++j )
{
indices.Add(startIndices[j]);
}
int nextIndex = 0;
for(int j = unchangedUpTo + 1; j < length; ++j)
{
while (indices.Contains(nextIndex))
nextIndex++;
startIndices[j] = nextIndex++;
}
break;
}
indices.Add(startIndices[i]);
}
}
}
}
int AddOne(int[] indices, int position, int maxElement)
{
//returns the index of the last element that has not been changed
indices[position]++;
for (int i = position; i > 0; --i)
{
if (indices[i] > maxElement)
{
indices[i] = 0;
indices[i - 1]++;
}
else
return i;
}
return 0;
}
If I got you correct here is what you need
this will create permutations based on the specified chain limit
public static List<List<T>> GetPerms<T>(List<T> list, int chainLimit)
{
if (list.Count() == 1)
return new List<List<T>> { list };
return list
.Select((outer, outerIndex) =>
GetPerms(list.Where((inner, innerIndex) => innerIndex != outerIndex).ToList(), chainLimit)
.Select(perms => (new List<T> { outer }).Union(perms).Take(chainLimit)))
.SelectMany<IEnumerable<IEnumerable<T>>, List<T>>(sub => sub.Select<IEnumerable<T>, List<T>>(s => s.ToList()))
.Distinct(new PermComparer<T>()).ToList();
}
class PermComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> x, List<T> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<T> obj)
{
return (int)obj.Average(o => o.GetHashCode());
}
}
and you'll call it like this
List<List<AdServer.Offers>> lst = GetPerms<AdServer.Offers>(offers, 2);
I made this function is pretty generic so you may use it for other purpose too
eg
List<string> list = new List<string>(new[] { "apple", "banana", "orange", "cherry" });
List<List<string>> perms = GetPerms<string>(list, 2);
result

How can I calculate a factorial in C# using a library call?

I need to calculate the factorial of numbers up to around 100! in order to determine if a series of coin flip-style data is random, as per this Wikipedia entry on Bayesian probability. As you can see there, the necessary formula involves 3 factorial calculations (but, interestingly, two of those factorial calculations are calculated along the way to the third).
I saw this question here, but I'd think that integer is going to get blown out pretty quickly. I could also make a function that is more intelligent about the factorial calculation (ie, if I have 11!/(7!3!), as per the wiki example, I could go to (11*10*9*8)/3!), but that smacks of premature optimization to me, in the sense that I want it to work, but I don't care about speed (yet).
So what's a good C# library I can call to calculate the factorial in order to get that probability? I'm not interested in all the awesomeness that can go into factorial calculation, I just want the result in a way that I can manipulate it. There does not appear to be a factorial function in the Math namespace, hence the question.
You could try Math.NET - I haven't used that library, but they do list Factorial and Logarithmic Factorial.
There has been a previous question on a similar topic. Someone there linked the Fast Factorial Functions web site, which includes some explanations of efficient algorithms and even C# source code.
Do you want to calculate factorials, or binomial coefficients?
It sounds like you want to calculate binomial coefficients - especially as you mention 11!/(7!3!).
There may be a library that can do this for you, but as a (presumably) programmer visiting stack overflow there's no reason not to write one yourself. It's not too complicated.
To avoid memory overflow, don't evaluate the result until all common factors are removed.
This algorithm still needs to be improved, but you have the basis for a good algorithm here. The denominator values need to be split into their prime factors for the best result. As it stands, this will run for n = 50 quite quickly.
float CalculateBinomial(int n, int k)
{
var numerator = new List<int>();
var denominator = new List<int>();
var denominatorOld = new List<int>();
// again ignore the k! common terms
for (int i = k + 1; i <= n; i++)
numerator.Add(i);
for (int i = 1; i <= (n - k); i++)
{
denominator.AddRange(SplitIntoPrimeFactors(i));
}
// remove all common factors
int remainder;
for (int i = 0; i < numerator.Count(); i++)
{
for (int j = 0; j < denominator.Count()
&& numerator[i] >= denominator[j]; j++)
{
if (denominator[j] > 1)
{
int result = Math.DivRem(numerator[i], denominator[j], out remainder);
if (remainder == 0)
{
numerator[i] = result;
denominator[j] = 1;
}
}
}
}
float denominatorResult = 1;
float numeratorResult = 1;
denominator.RemoveAll(x => x == 1);
numerator.RemoveAll(x => x == 1);
denominator.ForEach(d => denominatorResult = denominatorResult * d);
numerator.ForEach(num => numeratorResult = numeratorResult * num);
return numeratorResult / denominatorResult;
}
static List<int> Primes = new List<int>() { 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 };
List<int> SplitIntoPrimeFactors(int x)
{
var results = new List<int>();
int remainder = 0;
int i = 0;
while (!Primes.Contains(x) && x != 1)
{
int result = Math.DivRem(x, Primes[i], out remainder);
if (remainder == 0)
{
results.Add(Primes[i]);
x = result;
i = 0;
}
else
{
i++;
}
}
results.Add(x);
return results;
}
I can estimate n = 110, k = 50 (returns 6x10^31) but cannot run n = 120, k = 50.
The following can calculate the factorial of 5000 in 1 second.
public class Number
{
#region Fields
private static long _valueDivision = 1000000000;
private static int _valueDivisionDigitCount = 9;
private static string _formatZeros = "000000000";
List<long> _value;
#endregion
#region Properties
public int ValueCount { get { return _value.Count; } }
public long ValueAsLong
{
get
{
return long.Parse(ToString());
}
set { SetValue(value.ToString()); }
}
#endregion
#region Constructors
public Number()
{
_value = new List<long>();
}
public Number(long value)
: this()
{
SetValue(value.ToString());
}
public Number(string value)
: this()
{
SetValue(value);
}
private Number(List<long> list)
{
_value = list;
}
#endregion
#region Public Methods
public void SetValue(string value)
{
_value.Clear();
bool finished = false;
while (!finished)
{
if (value.Length > _valueDivisionDigitCount)
{
_value.Add(long.Parse(value.Substring(value.Length - _valueDivisionDigitCount)));
value = value.Remove(value.Length - _valueDivisionDigitCount, _valueDivisionDigitCount);
}
else
{
_value.Add(long.Parse(value));
finished = true;
}
}
}
#endregion
#region Static Methods
public static Number operator +(Number c1, Number c2)
{
return Add(c1, c2);
}
public static Number operator *(Number c1, Number c2)
{
return Mul(c1, c2);
}
private static Number Add(Number value1, Number value2)
{
Number result = new Number();
int count = Math.Max(value1._value.Count, value2._value.Count);
long reminder = 0;
long firstValue, secondValue;
for (int i = 0; i < count; i++)
{
firstValue = 0;
secondValue = 0;
if (value1._value.Count > i)
{
firstValue = value1._value[i];
}
if (value2._value.Count > i)
{
secondValue = value2._value[i];
}
reminder += firstValue + secondValue;
result._value.Add(reminder % _valueDivision);
reminder /= _valueDivision;
}
while (reminder > 0)
{
result._value.Add(reminder % _valueDivision);
reminder /= _valueDivision;
}
return result;
}
private static Number Mul(Number value1, Number value2)
{
List<List<long>> values = new List<List<long>>();
for (int i = 0; i < value2._value.Count; i++)
{
values.Add(new List<long>());
long lastremain = 0;
for (int j = 0; j < value1._value.Count; j++)
{
values[i].Add(((value1._value[j] * value2._value[i] + lastremain) % _valueDivision));
lastremain = ((value1._value[j] * value2._value[i] + lastremain) / _valueDivision);
//result.Add(();
}
while (lastremain > 0)
{
values[i].Add((lastremain % _valueDivision));
lastremain /= _valueDivision;
}
}
List<long> result = new List<long>();
for (int i = 0; i < values.Count; i++)
{
for (int j = 0; j < i; j++)
{
values[i].Insert(0, 0);
}
}
int count = values.Select(list => list.Count).Max();
int index = 0;
long lastRemain = 0;
while (count > 0)
{
for (int i = 0; i < values.Count; i++)
{
if (values[i].Count > index)
lastRemain += values[i][index];
}
result.Add((lastRemain % _valueDivision));
lastRemain /= _valueDivision;
count -= 1;
index += 1;
}
while (lastRemain > 0)
{
result.Add((lastRemain % _valueDivision));
lastRemain /= _valueDivision;
}
return new Number(result);
}
#endregion
#region Overriden Methods Of Object
public override string ToString()
{
string result = string.Empty;
for (int i = 0; i < _value.Count; i++)
{
result = _value[i].ToString(_formatZeros) + result;
}
return result.TrimStart('0');
}
#endregion
}
class Program
{
static void Main(string[] args)
{
Number number1 = new Number(5000);
DateTime dateTime = DateTime.Now;
string s = Factorial(number1).ToString();
TimeSpan timeSpan = DateTime.Now - dateTime;
long sum = s.Select(c => (long) (c - '0')).Sum();
}
static Number Factorial(Number value)
{
if( value.ValueCount==1 && value.ValueAsLong==2)
{
return value;
}
return Factorial(new Number(value.ValueAsLong - 1)) * value;
}
}
using System;
//calculating factorial with recursion
namespace ConsoleApplication2
{
class Program
{
long fun(long a)
{
if (a <= 1)
{
return 1;}
else
{
long c = a * fun(a - 1);
return c;
}}
static void Main(string[] args)
{
Console.WriteLine("enter the number");
long num = Convert.ToInt64(Console.ReadLine());
Console.WriteLine(new Program().fun(num));
Console.ReadLine();
}
}
}
hello everybody according to this solution i have my own solution where i calculate factorial of array 1D elements. the code is `int[] array = new int[5]
{
4,3,4,3,8
};
int fac = 1;
int[] facs = new int[array.Length+1];
for (int i = 0; i < array.Length; i++)
{
for (int j = array[i]; j > 0; j--)
{
fac *= j;
}
facs[i] = fac;
textBox1.Text += facs[i].ToString() + " ";
fac = 1;
}`
copy and paste the code above ^ in the button , it solves factorial of elements of array 1D. best regards.

Categories