Jump to content

AshtonJones

Members
  • Posts

    2
  • Joined

  • Last visited

AshtonJones's Achievements

Lepton

Lepton (1/13)

0

Reputation

  1. 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; }
  2. 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; }
×
×
  • Create New...

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.