Home > front end >  I ran into memory problems using this function
I ran into memory problems using this function

Time:11-14

I want to change the "$" characters in P to S in a way for example if S is "e" and P is "$agl$" the first input would be eagle and the second is eagleagleagle and so on.

This little function solves this until my N(the times I want to repeat this method) is a bit bigger. That's when I run into memory problems. I would gladly take any suggestions on how to make it work.

using System;

namespace SZTF1HF_new {
  class Program {
    static void Main(string[] args) {
      string S = Console.ReadLine();
      string P = Console.ReadLine();
      int N = int.Parse(Console.ReadLine());
      int MIN = int.Parse(Console.ReadLine());
      int MAX = int.Parse(Console.ReadLine());

      string Funct(string S, string P) {
        string temp = P.Replace("$", S);
        N--;
        if (N > 0) {
          return Funct(temp, P);
        }
        return temp;
      }
    }
  }
}

CodePudding user response:

Use the while loop which loops through a block of code as long as a specified condition is true over recursion.

The concept of Recursion and Iteration is to execute a set of instructions repeatedly and the difference between them is that recursion is simply a method call in which the method being called is the same as the one making the call while iteration is when a loop is repeatedly executed until a certain condition is met. one of the key difference between then is that recursion can cause infinite recursion which can lead to system crash whereas, infinite iteration consumes CPU cycles. Recursion also repeatedly invokes the mechanism, and consequently the overhead, of method calls and this can be quite expensive in both processor time and memory space while iteration doesn’t.

string Funct(string S, string P) {
    while(N > 0){
        P = P.Replace("$", S);
        N--;
     }

    return P;
}

  •  Tags:  
  • c#
  • Related