0

I have 3 problems, which are more or less similar.

  1. Given a integer array, I want to find the longest continuous subarray, such that the subarray is in increasing order of numbers.

  2. Given a integer array, I want to find the longest continuous subarray, such that the subarray have all same numbers.

  3. Given a character array, I want to find the longest continuous subarray, such that the subarray have all same characters.

I want to fully exploit concepts of reusability and extensibility in oops. I have implemented some code using templates. I have gave it a try and made a class template for problem 2 and 3 since they both can be done just comparing the ascii value of number or character. But I am not sure how to integrate the code for problem 1? I just want to know how tackle such problems from the perspective of reusability and extensibility using inheritance.

1 Answers1

0

Strategy pattern to the rescue: you can define an interface that encapsulates the matching strategy, say SubarrayMatcher and create two implementations, one that matches "increasing order of values" and another that matches "same values". Your main algorithm can then take the interface as a parameter and call out to it to do the matching.

High-level structure in pseudo-code:

Array<T> findLongestSubarray(Array<T> values, SubarrayMatcher<T> matcher);

interface SubarrayMatcher<T>
class IncreasingSubarrayMatcher<T> implements SubarrayMatcher<T>
class ConstantSubarrayMatcher<T> implements SubarrayMatcher<T>
casablanca
  • 69,683
  • 7
  • 133
  • 150