2010-05-25 12 views
5

No creo que sea difícil, solo tedioso de escribir: una pequeña biblioteca libre (como en la cerveza) donde puedo poner en una cadena como 1,2-9,33- y me puede decir si un número determinado coincide con esa expresión. Al igual que la mayoría de los programas tienen en sus diálogos de rango de impresión. Las funciones especiales para emparejar números impares o pares solamente, o hacer coincidir cada número que sea 2 mod 5 (o algo así) serían agradables, pero no necesarios.¿Hay alguna biblioteca para analizar "expresiones numéricas" como 1,2-9,33- en Java

La única operación que tengo que realizar en esta lista es si el rango contiene un valor entero dado (no negativo); más operaciones como valor máximo/mínimo (si existen) o un iterador sería bueno, por supuesto.

lo que sería necesario que no ocupa mucha memoria RAM si alguien entra en 1-10000000 pero el único número que lo haré jamás consulta es 12345 :-)

(Para ponerlo en práctica, me gustaría analizar una lista en varios pares (min/max/value/mod), como 1,10,0,1 para 1-10 o 11,33,1,2 para 1-33odd, o 12,62,2,10 para 12-62/10 (es decir, 12, 22, 32, ..., 62) y luego verifique cada número para todos los intervalos. Abra los intervalos usando Integer.MaxValue, etc. ¿Si no hay libs, alguna idea para hacerlo mejor/más eficiente?)

+0

Véase también http://stackoverflow.com/questions/1069659/how-to-find-if-a-number-is-contained-in-an-array-of- number-ranges-in-java –

Respuesta

3

Decidí codificar yo mismo de hecho. Utilice a su propio riesgo :-)

/* 
* NumberExpression.java - a simple number expression parser 
* 
* Copyright (c) 2010 Michael Schierl 
* 
* All rights reserved. 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions 
* are met: 
* 
* - Redistributions of source code must retain the above copyright notice, 
* this list of conditions and the following disclaimer. 
* 
* - Redistributions in binary form must reproduce the above copyright 
* notice, this list of conditions and the following disclaimer in the 
* documentation and/or other materials provided with the distribution. 
* 
* - Neither name of the copyright holders nor the names of its 
* contributors may be used to endorse or promote products derived from 
* this software without specific prior written permission. 
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS 
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/ 
package numberexpression; 

/** 
* An expression that matches nonnegative numbers. This supports cron-like 
* expressions, like <code>1,3-6,100-200,666,1000-3000/5,400-/7</code>, 
* <code>-100,102-</code> or <code>*</code>. Odd or even numbers can be 
* matched either by cron's step syntax, or by suffixing a simple range 
* (without step values) with <code>e</code> or <code>o</code>. 
* 
* @author Michael Schierl 
*/ 
public class NumberExpression { 

    private final NumberRange[] ranges; 
    private final int min, max; 

    /** 
    * Create a new {@link NumberExpression}. 
    * 
    * @param pattern 
    *   the expression pattern. 
    * @throws IllegalArgumentException 
    *    if the pattern is malformed 
    */ 
    public NumberExpression(String pattern) { 
     String[] parts = pattern.toLowerCase().split(",",-1); 
     ranges = new NumberRange[parts.length]; 
     int min = Integer.MAX_VALUE, max = 0; 
     for (int i = 0; i < ranges.length; i++) { 
      String part = parts[i]; 
      try { 
       if (part.equals("*")) { 
        ranges[i] = new NumberRange(0, Integer.MAX_VALUE, 0, 1); 
       } else if (part.matches("\\*/\\d+")) { 
        ranges[i] = new NumberRange(0, Integer.MAX_VALUE, 0, Integer.parseInt(part.substring(2))); 
       } else if (part.matches("\\d+")) { 
        int value = Integer.parseInt(part); 
        ranges[i] = new NumberRange(value, value, 0, 1); 
       } else if (part.matches("\\d*-\\d*")) { 
        String[] limits = part.split("-", -1); 
        int from = limits[0].length() == 0 ? 0 : Integer.parseInt(limits[0]); 
        int to = limits[1].length() == 0 ? Integer.MAX_VALUE : Integer.parseInt(limits[1]); 
        if (to < from) 
         throw new IllegalArgumentException("Invalid pattern: " + part); 
        ranges[i] = new NumberRange(from, to, 0, 1); 
       } else if (part.matches("\\d*-\\d*/\\d+")) { 
        String[] rangeAndModulus = part.split("/", -1); 
        String[] limits = rangeAndModulus[0].split("-", -1); 
        int from = limits[0].length() == 0 ? 0 : Integer.parseInt(limits[0]); 
        int to = limits[1].length() == 0 ? Integer.MAX_VALUE : Integer.parseInt(limits[1]); 
        int modulus = Integer.parseInt(rangeAndModulus[1]); 
        if (to < from) 
         throw new IllegalArgumentException("Invalid pattern: " + part); 
        ranges[i] = new NumberRange(from, to, from % modulus, modulus); 
       } else if (part.matches("\\d*-\\d*[eo]")) { 
        String[] limits = part.substring(0, part.length() - 1).split("-", -1); 
        int from = limits[0].length() == 0 ? 0 : Integer.parseInt(limits[0]); 
        int to = limits[1].length() == 0 ? Integer.MAX_VALUE : Integer.parseInt(limits[1]); 
        if (to < from) 
         throw new IllegalArgumentException("Invalid pattern: " + part); 
        ranges[i] = new NumberRange(from, to, part.charAt(part.length() - 1) == 'o' ? 1 : 0, 2); 
       } else { 
        throw new IllegalArgumentException("Invalid pattern: " + part); 
       } 
       max = Math.max(max, ranges[i].getMax()); 
       min = Math.min(min, ranges[i].getMin()); 
      } catch (NumberFormatException ex) { 
       throw new IllegalArgumentException("Invalid pattern: " + part); 
      } 
     } 
     this.max = max; 
     this.min = min; 
    } 

    /** 
    * Check whether this number expression matches the given number. 
    * 
    * @param number 
    *   the number to check against 
    * @return whether the expression matches the number 
    */ 
    public boolean matches(int number) { 
     if (number < min || number > max) 
      return false; 
     for (int i = 0; i < ranges.length; i++) { 
      if (ranges[i].matches(number)) 
       return true; 
     } 
     return false; 
    } 

    /** 
    * Return the minimum number that can be matched. 
    */ 
    public int getMinimum() { return min; } 

    /** 
    * Return the maximum number that can be matched. 
    */ 
    public int getMaximum() { return max; } 

    private static class NumberRange { 
     private final int min, max, remainder, modulus; 

     NumberRange(int min, int max, int remainder, int modulus) { 
      this.min = min; 
      this.max = max; 
      this.remainder = remainder; 
      this.modulus = modulus; 
     } 

     boolean matches(int number) { 
      return number >= min && number <= max && number % modulus == remainder; 
     } 

     int getMin() { return min; } 
     int getMax() { return max; } 
    } 
} 
+0

Si quiero que el separador sea ";" además de ",", ¿cuáles serían los cambios necesarios? – CyberMew

+1

@CyberMew reemplace 'split (", ", - 1);' por 'split (" [,;] ", - 1);' – mihi

1
+0

pero todavía tengo que dividir cosas en comas y guiones y analizarlas yo mismo? – mihi

+0

Parece que ninguno de estos 2 admite esa pieza, no. – DVK

+0

@mihi - El análisis sería fácil. Iría con org.apache.commons.lang.math.NumberRange +1 –

1

Suena como que sería más fácil simplemente codificarlo.

Aquí está el código python que admite la parte del rango de sus deseos.

>>> def f(n, pattern): 
...  ranges = [r.split('-') for r in pattern.split(',')] 
...  for a,b in ranges: 
...    if (not a or int(a) <= n) and (not b or int(b) >= n): 
...      return True 
...  return False 
... 
>>> f(4, '-1,2-9,33-') 
True 
>>> f(11, '-1,2-9,33-') 
False 
>>> f(100, '-1,2-9,33-') 
True 
>>> 

Funciona en tiempo lineal con la longitud de la cadena. Si compila el patrón en un IntervalTree, puede hacerlo logarítmico. El uso de memoria es siempre lineal.

+1

suena, pero aún debe probar su código. Tu código falla para patrones como 1-10,20,42,100- – mihi

+0

Y, todavía espero obtener algunas características adicionales ingeniosas que no tengo que pensar (pero a los usuarios les gustarán), como ocurre con las bibliotecas de expresiones regulares :) – mihi

Cuestiones relacionadas