a regular expression generator for number ranges

前端 未结 9 2159
长情又很酷
长情又很酷 2021-02-04 05:56

I checked on the stackExchange description, and algorithm questions are one of the allowed topics. So here goes.

Given an input of a range, where begin and ending number

9条回答
  •  梦毁少年i
    2021-02-04 06:23

    I've finally arrived at the following. The overall idea is to start with the beginning of the range, produce a regular expression that will match from that up to but not including the next multiple of 10, then for hundreds, etc. until you have matched things up to the end of the range; then start with the end of the range and work downwards, replacing increasing numbers of digits with 0s to match against similar numbers of 9s, to match the specific end-of-range. Then generate one regular expression for the part of the range if they don't already cover it all.

    Special note should be taken of bezmax's routine to convert two numbers to the regular expression that will match them - MUCH easier than dealing with strings or character arrays directly, I think.

    Anyway, here it is:

    package numbers;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    
    /**
     * Has methods for generating regular expressions to match ranges of numbers.
     */
    public class RangeRegexGenerator
    {
      public static void main(String[] args)
      {
        RangeRegexGenerator rrg = new RangeRegexGenerator();
    
    //    do
    //    {
    //      Scanner scanner = new Scanner(System.in);
    //      System.out.println("enter start, , then end and ");
    //      int start = scanner.nextInt();
    //      int end = scanner.nextInt();
    //      System.out.println(String.format("for %d-%d", start, end));
    
          List regexes = rrg.getRegex("0015", "0213");
          for (String s: regexes) { System.out.println(s); }
    //    } 
    //    while(true);
      }
    
      /**
       * Return a list of regular expressions that match the numbers
       * that fall within the range of the given numbers, inclusive.
       * Assumes the given strings are numbers of the the same length,
       * and 0-left-pads the resulting expressions, if necessary, to the
       * same length. 
       * @param begStr
       * @param endStr
       * @return
       */
      public List getRegex(String begStr, String endStr)
      {
          int start = Integer.parseInt(begStr);
          int end   = Integer.parseInt(endStr);
          int stringLength = begStr.length();
          List pairs = getRegexPairs(start, end);
          List regexes = toRegex(pairs, stringLength);
          return regexes;
      }
    
      /**
       * Return a list of regular expressions that match the numbers
       * that fall within the range of the given numbers, inclusive.
       * @param beg
       * @param end
       * @return
       */
      public List getRegex(int beg, int end)
      {
        List pairs = getRegexPairs(beg, end);
        List regexes = toRegex(pairs);
        return regexes;
      }
    
      /**
       * return the list of integers that are the paired integers
       * used to generate the regular expressions for the given
       * range. Each pair of integers in the list -- 0,1, then 2,3,
       * etc., represents a range for which a single regular expression
       * is generated.
       * @param start
       * @param end
       * @return
       */
      private List getRegexPairs(int start, int end)
      {
          List pairs = new ArrayList<>();
    
          ArrayList leftPairs = new ArrayList<>();
          int middleStartPoint = fillLeftPairs(leftPairs, start, end);
          ArrayList rightPairs = new ArrayList<>();
          int middleEndPoint = fillRightPairs(rightPairs, middleStartPoint, end);
    
          pairs.addAll(leftPairs);
          if (middleEndPoint > middleStartPoint)
          {
            pairs.add(middleStartPoint);
            pairs.add(middleEndPoint);
          }
          pairs.addAll(rightPairs);
          return pairs;
      }
    
      /**
       * print the given list of integer pairs - used for debugging.
       * @param list
       */
      @SuppressWarnings("unused")
      private void printPairList(List list)
      {
        if (list.size() > 0)
        {
          System.out.print(String.format("%d-%d", list.get(0), list.get(1)));
          int i = 2;
          while (i < list.size())
          {
            System.out.print(String.format(", %d-%d", list.get(i), list.get(i + 1)));
            i = i + 2;
          }
          System.out.println();
        }
      }
    
      /**
       * return the regular expressions that match the ranges in the given
       * list of integers. The list is in the form firstRangeStart, firstRangeEnd, 
       * secondRangeStart, secondRangeEnd, etc.
       * @param pairs
       * @return
       */
      private List toRegex(List pairs)
      {
        return toRegex(pairs, 0);
      }
    
      /**
       * return the regular expressions that match the ranges in the given
       * list of integers. The list is in the form firstRangeStart, firstRangeEnd, 
       * secondRangeStart, secondRangeEnd, etc. Each regular expression is 0-left-padded,
       * if necessary, to match strings of the given width.
       * @param pairs
       * @param minWidth
       * @return
       */
      private List toRegex(List pairs, int minWidth)
      {
        List list = new ArrayList<>();
        String numberWithWidth = String.format("%%0%dd", minWidth);
        for (Iterator iterator = pairs.iterator(); iterator.hasNext();)
        {
          String start = String.format(numberWithWidth, iterator.next()); // String.valueOf(iterator.next());
          String end = String.format(numberWithWidth, iterator.next());
    
          list.add(toRegex(start, end));
        }
        return list;
      }
    
      /**
       * return a regular expression string that matches the range
       * with the given start and end strings.
       * @param start
       * @param end
       * @return
       */
      private String toRegex(String start, String end)
      {
        assert start.length() == end.length();
    
        StringBuilder result = new StringBuilder();
    
        for (int pos = 0; pos < start.length(); pos++)
        {
          if (start.charAt(pos) == end.charAt(pos))
          {
            result.append(start.charAt(pos));
          } else
          {
            result.append('[').append(start.charAt(pos)).append('-')
                .append(end.charAt(pos)).append(']');
          }
        }
        return result.toString();
      }
    
      /**
       * Return the integer at the end of the range that is not covered
       * by any pairs added to the list.
       * @param rightPairs
       * @param start
       * @param end
       * @return
       */
      private int fillRightPairs(List rightPairs, int start, int end)
      {
        int firstBeginRange = end;    // the end of the range not covered by pairs
                                      // from this routine.
        int y = end;
        int x = getPreviousBeginRange(y);
    
        while (x >= start)
        {
          rightPairs.add(y);
          rightPairs.add(x);
          y = x - 1;
          firstBeginRange = y;
          x = getPreviousBeginRange(y);
        }
        Collections.reverse(rightPairs);
        return firstBeginRange;
      }
    
      /**
       * Return the integer at the start of the range that is not covered
       * by any pairs added to its list. 
       * @param leftInts
       * @param start
       * @param end
       * @return
       */
      private int fillLeftPairs(ArrayList leftInts, int start, int end)
      {
        int x = start;
        int y = getNextLeftEndRange(x);
    
        while (y < end)
        {
          leftInts.add(x);
          leftInts.add(y);
          x = y + 1;
          y = getNextLeftEndRange(x);
        }
        return x;
      }
    
      /**
       * given a number, return the number altered such
       * that any 9s at the end of the number remain, and
       * one more 9 replaces the number before the other
       * 9s.
       * @param num
       * @return
       */
      private int getNextLeftEndRange(int num)
      {
        char[] chars = String.valueOf(num).toCharArray();
        for (int i = chars.length - 1; i >= 0; i--)
        {
          if (chars[i] == '0')
          {
            chars[i] = '9';
          } else
          {
            chars[i] = '9';
            break;
          }
        }
    
        return Integer.parseInt(String.valueOf(chars));
      }
    
      /**
       * given a number, return the number altered such that
       * any 9 at the end of the number is replaced by a 0,
       * and the number preceding any 9s is also replaced by
       * a 0.
       * @param num
       * @return
       */
      private int getPreviousBeginRange(int num)
      {
        char[] chars = String.valueOf(num).toCharArray();
        for (int i = chars.length - 1; i >= 0; i--)
        {
          if (chars[i] == '9')
          {
            chars[i] = '0';
          } else
          {
            chars[i] = '0';
            break;
          }
        }
    
        return Integer.parseInt(String.valueOf(chars));
      }
    }
    

    This one is correct as far as I've been able to test it; the one posted by bezmax did not quite work, though he had the right idea (that I also came up with) for an overall algorithm, and a major implementation detail or two that were helpful, so I'm leaving the 'answer' checkmark on his response.

    I was a little surprised at the amount of interest this generated, though not as much as by just how complex the problem turned out to be.

提交回复
热议问题