AshtonJones
-
Posts
2 -
Joined
-
Last visited
Content Type
Profiles
Forums
Events
Posts posted by AshtonJones
-
-
Hello, I'm struggling with constructing a momoized recursive function in C#
What I want is to find the sum of squares for n numbers.
What I want to memoize is an already found result of a number squared.
So in n numbers, if I have 3 instances of 2, I want to store (2*2)=4 and not call the function
recursively again to calculate (2*2), just return 4 and added it the sum. My function is below.
In playing around wiht the function, what keeps happening is that mem.Add(arr[index], calc); gives
me an exception saying key already exists in mem collection or it does not cycle through all
values in the array. Is this possible, and if so how?int total = 16;
Hashtable mem = new Hashtable();int[] arr = new int[7];
arr[0] = 2;
arr[1] = 3;
arr[2] = 2;
arr[3] = 4;
arr[4] = 3;
arr[5] = 2;
arr[6] = 4;var result = doSum(arr, mem, arr.Length - 1);
public int doSum(int[] arr, Hashtable mem, int index)
{
int sum = 0;if (index < 0)
return 0;
if (mem.ContainsKey(arr[index]))
return (int)mem[arr[index]];
else
calc = doSum(arr, mem, index - 1) + (int)Math.Round(Math.Pow(arr[index], 2));mem.Add(arr[index], calc);
return sum;
}0
Recursive memoized function help
in Computer Science
Posted