用于识别数字模式的Java程序

时间:2012-07-10 21:44:21

标签: java algorithm

我希望创建一个能够识别某些数字模式的程序。我不确定这是否需要算法或只是仔细考虑编程。我不是在寻找能够提供源代码的人,只是一些发人深省的想法让我朝着正确的方向前进。

数字将固定长度为6位数字,从000000到999999.我猜每个数字都将存储为数组的一部分。然后我想根据模式测试数字。

例如,假设我使用的3个模式是

A A A A A A - would match such examples as 111111 , 222222, 333333 etc where 
A B A B A B - would match such examples as 121212 , 454545, 919191 etc
A (A+1) (A+2) B (B+1) (B+2) - would match such examples as 123345, 789123, 456234

我想我所坚持的部分是如何将整数数组的每个部分分配给诸如A或B之类的值

我的初衷是将每个部分分配为单个字母。因此,如果数组由1 3 5 4 6 8组成,那么我将创建一个类似

的地图
A=1
B=3
C=5
D=4
E=6
F=8

然后一些如何采取第一种模式,

AAAAAA

并使用if(AAAAAA = ABCDEF)等测试然后我们匹配AAAAAAA

如果没有,那么通过我的所有模式尝试(ABABAB = ABCDEF)等

在这种情况下,没有理由将分配给C的值与数字234874中的值分配给F值相同。

我不确定这对任何人是否有意义,但我想我可以根据反馈来改进我的问题。

总之,我正在寻找有关如何让一个程序接受一个6位数的想法,然后将它返回给我们的模式。

在给出的评论之后,让我在下面的良好轨道上是我创建的最终解决方案。

package com.doyleisgod.number.pattern.finder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class FindPattern {
private final int[] numberArray; //Array that we will match patterns against.
private final Document patternTree = buildPatternTree(); //patternTree containing all the patterns
private final Map<String, Integer> patternisedNumberMap; //Map used to allocate ints in the array to a letter for pattern analysis
private int depth = 0; //current depth of the pattern tree

// take the int array passed to the constructor and store it in out numberArray variable then build the patternised map
public FindPattern (int[] numberArray){
    this.numberArray = numberArray;
    this.patternisedNumberMap = createPatternisedNumberMap();
}

//builds a map allocating numbers to letters. map is built from left to right of array and only if the number does not exist in the map does it get added
//with the next available letter. This enforces that the number assigned to A can never be the same as the number assigned to B etc
private Map<String, Integer> createPatternisedNumberMap() {
    Map<String, Integer> numberPatternMap = new HashMap<String, Integer>();

    ArrayList<String> patternisedListAllocations = new ArrayList<String>();
    patternisedListAllocations.add("A");
    patternisedListAllocations.add("B");
    patternisedListAllocations.add("C");
    patternisedListAllocations.add("D");
    Iterator<String> patternisedKeyIterator = patternisedListAllocations.iterator();

    for (int i = 0; i<numberArray.length; i++){
        if (!numberPatternMap.containsValue(numberArray[i])) {
            numberPatternMap.put(patternisedKeyIterator.next(), numberArray[i]);
        } 
    }
    return numberPatternMap;
}

//Loads an xml file containing all the patterns.
private Document buildPatternTree(){
    Document document = null;
    try {
    File patternsXML = new File("c:\\Users\\echrdoy\\Desktop\\ALGO.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    document = db.parse(patternsXML);

    } catch (Exception e){
        e.printStackTrace();
        System.out.println("Error building tree pattern");
    }
    return document;
}

//gets the rootnode of the xml pattern list then called the dfsnodesearch method to analyse the pattern against the int array. If a pattern is found a
//patternfound exception is thorwn. if the dfsNodeSearch method returns without the exception thrown then the int array didnt match any pattern
public void patternFinder() {
    Node rootnode= patternTree.getFirstChild();
    try {
        dfsNodeSearch(rootnode);
        System.out.println("Pattern not found");
    } catch (PatternFoundException p) {
        System.out.println(p.getPattern());
    }
}

//takes a node of the xml. the node is checked to see if it matches a pattern (this would only be true if we reached the lowest depth so must have 
//matched a pattern. if no pattern then analyse the node for an expression. if expression is found then test for a match. the int from the array to be tested
//will be based on the current depth of the pattern tree. as each depth represent an int such as depth 0 (i.e root) represent position 0 in the int array
//depth 1 represents position 1 in the int array etc. 
private void dfsNodeSearch (Node node) throws PatternFoundException {
    if (node instanceof Element){
        Element nodeElement = (Element) node;
        String nodeName = nodeElement.getNodeName();

        //As this method calls its self for each child node in the pattern tree we need a mechanism to break out when we finally reach the bottom
        // of the tree and identify a pattern. For this reason we throw pattern found exception allowing the process to stop and no further patterns.
        // to be checked.
        if (nodeName.equalsIgnoreCase("pattern")){
            throw new PatternFoundException(nodeElement.getTextContent());
        } else {
            String logic = nodeElement.getAttribute("LOGIC");
            String difference = nodeElement.getAttribute("DIFFERENCE");

            if (!logic.equalsIgnoreCase("")&&!difference.equalsIgnoreCase("")){
                if (matchPattern(nodeName, logic, difference)){
                    if (node.hasChildNodes()){
                        depth++;
                        NodeList childnodes = node.getChildNodes();
                        for (int i = 0; i<childnodes.getLength(); i++){
                            dfsNodeSearch(childnodes.item(i));
                        }
                        depth--;
                    }
                } 
            }
        }


    }
}

//for each node at a current depth a test will be performed against the pattern, logic and difference to identify if we have a match. 
private boolean matchPattern(String pattern, String logic, String difference) {
    boolean matched = false;
    int patternValue = patternisedNumberMap.get(pattern);

    if (logic.equalsIgnoreCase("+")){
        patternValue += Integer.parseInt(difference);
    } else if (logic.equalsIgnoreCase("-")){
        patternValue -= Integer.parseInt(difference);
    }

    if(patternValue == numberArray[depth]){
        matched=true;
    }

    return matched;
}


}

xml模式列表如下所示

<?xml version="1.0"?>
<A LOGIC="=" DIFFERENCE="0">
    <A LOGIC="=" DIFFERENCE="0">
        <A LOGIC="=" DIFFERENCE="0">
            <A LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(A)(A)(A)</pattern>
            </A>
            <B LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(A)(B)(A)</pattern>
            </B>
        </A>
        <B LOGIC="=" DIFFERENCE="0">
            <A LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(A)(B)(A)</pattern>
            </A>
            <B LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(A)(B)(B)</pattern>
            </B>
        </B>
    </A>
    <A LOGIC="+" DIFFERENCE="2">
        <A LOGIC="+" DIFFERENCE="4">
            <A LOGIC="+" DIFFERENCE="6">
                <pattern>(A)(A+2)(A+4)(A+6)</pattern>
            </A>
       </A>
    </A>
    <B LOGIC="=" DIFFERENCE="0">
        <A LOGIC="+" DIFFERENCE="1">
            <B LOGIC="+" DIFFERENCE="1">
                <pattern>(A)(B)(A+1)(B+1)</pattern>
            </B>
        </A>
        <A LOGIC="=" DIFFERENCE="0">
            <A LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(B)(A)(A)</pattern>
            </A>
            <B LOGIC="+" DIFFERENCE="1">
                <pattern>(A)(B)(A)(B+1)</pattern>
            </B>
            <B LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(B)(A)(B)</pattern>
            </B>
        </A>
        <B LOGIC="=" DIFFERENCE="0">
            <A LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(B)(B)(A)</pattern>
            </A>
            <B LOGIC="=" DIFFERENCE="0">
                <pattern>(A)(B)(B)(B)</pattern>
            </B>
        </B>
        <A LOGIC="-" DIFFERENCE="1">
            <B LOGIC="-" DIFFERENCE="1">
                <pattern>(A)(B)(A-1)(B-1)</pattern>
            </B>
        </A>
    </B>
    <A LOGIC="+" DIFFERENCE="1">
        <A LOGIC="+" DIFFERENCE="2">
            <A LOGIC="+" DIFFERENCE="3">
                <pattern>(A)(A+1)(A+2)(A+3)</pattern>
            </A>
        </A>
    </A>
    <A LOGIC="-" DIFFERENCE="1">
        <A LOGIC="-" DIFFERENCE="2">
            <A LOGIC="-" DIFFERENCE="3">
                <pattern>(A)(A-1)(A-2)(A-3)</pattern>
            </A>
        </A>
    </A>
</A>

我的模式发现异常类看起来像这样

package com.doyleisgod.number.pattern.finder;

public class PatternFoundException extends Exception {
private static final long serialVersionUID = 1L;
private final String pattern;

public PatternFoundException(String pattern) {
    this.pattern = pattern;
}

public String getPattern() {
    return pattern;
}

}

不确定是否有任何问题可以帮助任何有类似问题的人,或者如果有人对此工作有任何意见,那么听听他们会很高兴。

5 个答案:

答案 0 :(得分:2)

我建议建立状态机:

一个。用模式初始化:

  1. 规范化所有模式
  2. 构建一个深度为6的树,它代表从root开始的所有模式以及每个深度上的所有可能选择。
  3. B中。运行状态机


    A.1。模式规范化。

    A A A A A =&gt; A0 A0 A0 A0 A0 A0

    C A C A C A =&gt; A0 B0 A0 B0 A0 B0(始终以A开头,然后是B,C,D等)

    B B + 1 B + 2 A A + 1 A + 2 =&gt; A0 A1 A2 B0 B1 B2

    因此,您始终使用A0开始标准化模式。

    A.2。建树

    1.       A0
           /  | \
    2.   A0  B0  A1
          |   |   |
    3.   A0  A0  A2
          |   |   |
    4.   A0  B0  B0
          |   |   |
    5.   A0  A0  B1
          |   |   |
    6.   A0  B0  B2
          |   |   |
         p1  p2  p3
    

    B中。运行状态机

    使用Depth-first search algorithm使用递归来查找匹配的模式。

    有意义吗?

答案 1 :(得分:0)

您可以将数字分成一个字节数组(或者如果您愿意,可以使用整数),每个字符一个。可以根据阵列的适当元素之间的直接比较来定义每个模式。

ababab=a[0]==a[2] && a[2]==a[4] && a[1]==a[3] && a[3]==a[5] && a[0]!=a[1]
aaabbb=a[0]==a[1] && a[1]==a[2] && a[3]==a[4] && a[4]==a[5] && a[0]!=a[3]
fedcba=(a[0]-a[1])==1 && (a[1]-a[2])==1 && (a[2]-a[3])==1 && (a[3]-a[4])==1 && (a[4]-a[5]==1)

答案 2 :(得分:0)

使用以下非常快速的匹配功能很容易。

鉴于模式是PatternElement的数组,其中PatternElement由一个字母和一个整数组成。

鉴于数字是数字阵列。

现在使用Number和Digit的每个组合(嵌套for循环)调用match()函数。

匹配函数从左到右迭代模式和数字,并替换数字以匹配模式中的字母。如果更换了一个数字,也可以替换所有相同的数字。如果您到达的索引不是数字,因为它已被替换,请检查此元素是否与模式匹配。

Example 1 iterations. Pattern: A B A C    Number 3 2 3 5
                               ^                 ^ 
                   1.                            A 2 A 5    replace 3 by A. 
                                 ^                 ^
                   2.                            A B A 5    replace 2 by B
                                   ^                 ^    
                   3.                            A B A 5    Existing A matches pattern. Good
                                     ^                 ^
                   4.                            A B A C    replace 5 by C. SUCCESS

对于(n + 2),您可以通过在替换或匹配期间做一些额外的数学运算来做同样的事情。

注意:该号码不需要仅包含数字。如果你想更换任何字符,你甚至可以匹配类似的模式!所以A B C A B C也会以通用形式匹配D F G D F G.

答案 3 :(得分:0)

您可以推断出约束,然后使用回溯算法来确定特定数字是否与模式匹配(有时也称为constraint satisfaction problem)。

例如,让我们分别表示6个数字d1,d2,d3,d4,d5和d6中的每一个。然后,可以将模式A (A+1) (A+2) B (B+1) (B+2)重写为以下规则/约束集:

dx = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
d2 = d1 + 1
d2 = d1 + 2
d4 = d3 + 1
d5 = d3 + 2

在你的例子中,我只能看到两种推断规则 - 一个用于数字相等(d1 = d2,如果它们在模式中的位置具有相同的字符),另一个用于算术运算(我不知道A和B是否应该是不同的数字,如果是这样,你将需要额外的不平等规则)。所有种类都可以简单地转化为约束。

然后可以从这些约束中编译可能的解决方案树。它可以从以下内容开始:

[A = ?]
|-- 1
|-- 2
|-- 3
|   |-- [B = ?]
|       |-- 1
...     ...

然后在其他节点上包含约束。

自己可能很难正确实现回溯算法,因此为您的平台找到Prolog实现是有意义的(请参阅this Java问题),然后将约束转换为Prolog规则。

答案 4 :(得分:0)

对于您作为示例提到的特定模式,可以编写简单的程序来检查输入字符串是否匹配。

如果模式比您提到的模式更复杂,您可以使用Context-free grammar和正则表达式来指定规则。还有像lex和yacc这样的工具,它们将根据指定的规则处理输入字符串,如果匹配或不匹配则返回。