Jump to content

Recursive memoized function help

Featured Replies

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;
  }

  • Author
public int doSum(int[] arr, Hashtable mem, int index)
{
  int sum = 0;

  if (index < 0)
    return 0;

   int sqVal;
   if (mem.ContainsKey(arr[index]))
     sqVal = (int)mem[arr[index]];
   else
   {
     sqVal = (int)Math.Round(Math.Pow(arr[index], 2));
     mem.Add(arr[index], sqVal);
   }

   sum = doSum(arr, mem, index - 1) + sqVal;
   return sum;
 }
On 3/12/2019 at 2:40 PM, AshtonJones said:

sqVal = (int)Math.Round(Math.Pow(arr[index], 2));

Isn't the same but easier? (without conversion from integer to float, and float to integer)

sqVal = arr[index] * arr[index];

 

 

The easiest would be to use debugger. Compile in debug mode, set break point, and start debugging with real-time observation of variables and arrays to check what values are read/written/calculated.

Old-school way to debug is by printing variables to e.g. console. You will see what happens step-by-step.

 

Archived

This topic is now archived and is closed to further replies.

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.