- #1
SlurrerOfSpeech
- 141
- 11
One way that I often write recursive functions in my work is by having an optional parameter that is used for all calls after the first. For example, here's how I might implement the classic "Find the largest palindrome in a given string" interview-type problem:
This is an alternative to writing it like
Let me explain what I think are the advantages and disadvantages of the first way.
Advantages:
* Fancier
* Slightly less code
Disadvantages:
* Although its intent is for the caller to use it with empty pamarameters, the call with a parameter is public and so it can be used as not intended. It could be argued that this violates OOP religious commandements.
Code:
using System;
public static class Extensions
{
private static string Reverse(this string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public static string LargestPalindrome(this string s, int k = -1)
{
if(k == -1) // If function was called for the first time
{
return s.LargestPalindrome(s.Length);
}
// Try to find palindrome in all substrings of length k
for(int i = 0, j = s.Length - k; i <= j; ++i)
{
string ss = s.Substring(i, k);
if(ss == ss.Reverse())
return ss;
}
// If here, didn't find a palindrome. Try all substrings
// of length k - 1.
return s.LargestPalindrome(k - 1);
}
}
public class Program
{
public static void Main()
{
string s = "kandasndddsk";
Console.WriteLine(s.LargestPalindrome()); // Expected output: "ddd"
}
}
This is an alternative to writing it like
Code:
using System;
public static class Extensions
{
private static string Reverse(this string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
private static string LargetsPalindrome_Subroutine(this string s, int k)
{
// Try to find palindrome in all substrings of length k
for(int i = 0, j = s.Length - k; i <= j; ++i)
{
string ss = s.Substring(i, k);
if(ss == ss.Reverse())
return ss;
}
// If here, didn't find a palindrome. Try all substrings
// of length k - 1.
return s.LargestPalindrome(k - 1);
}
public static string LargestPalindrome(this string s)
{
return s.LargestPalindrome(s.Length);
}
}
public class Program
{
public static void Main()
{
string s = "kandasndddsk";
Console.WriteLine(s.LargestPalindrome()); // Expected output: "ddd"
}
}
Let me explain what I think are the advantages and disadvantages of the first way.
Advantages:
* Fancier
* Slightly less code
Disadvantages:
* Although its intent is for the caller to use it with empty pamarameters, the call with a parameter is public and so it can be used as not intended. It could be argued that this violates OOP religious commandements.