Java程序用于识别数字模式

7
我希望能够创建一个程序,用于识别数字中的特定模式。我不确定这是否需要算法或仅需要精心设计的编程。我不需要任何人提供源代码,只需要一些启发性的想法来指导我正确的方向。
数字将固定为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 分配的值和 F 分配的值一样,就像数字 234874 中的情况。

我不确定这是否能让任何人理解,但我想我可以根据反馈来改进我的问题。

总之,我正在寻求有关如何使程序接受一个六位数并返回匹配的模式的想法。

解决方案

在得到评论后,我找到了一个好办法,以下是我创建的最终解决方案。

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 didn't 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;
}

}

不确定这些内容是否能帮助到有类似问题的人,如果有任何评论或建议,欢迎听取。


好的,我不会硬编码一个完全匹配(即A = 1类型的情况)。您可能希望将遇到的每个不同字符视为不同的数字。空格分隔应该是不同的数字(而不是数字)。 - Clockwork-Muse
这是人工智能的东西。道格拉斯·霍夫斯塔德就是凭借这种模式发现而成为了他的职业生涯。 - Marko Topolnik
嘿,你想要几个预定义的模式并进行检查吗? 你的模式已经有语义存储方式了吗?还是没有固定格式? - DrLudwig3
我已经建立了一个小模型,是否值得在这里发布,以便其他可能想解决类似问题的人可以查看它。如果是,我应该在哪里发布它?在新主题中吗?还是编辑我的原始帖子在这个主题中? - Chris Doyle
5个回答

2
我建议构建状态机:
A. 使用模式进行初始化:
1. 规范化所有模式 2. 建立深度为6的树,表示从根开始的所有模式和每个深度上的所有可能选择。
B. 运行状态机。
A.1. 模式规范化。

A A A A A A => A0 A0 A0 A0 A0 A0

C A C A C A => A0 B0 A0 B0 A0 B0(始终以 A、B、C、D 等开头。)

B B+1 B+2 A A+1 A+2 => 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 查找匹配模式。
这样说通吗?

谢谢Yuri,这似乎让我朝着正确的方向开始了。我采取的方法是创建一个模式树结构,使得所有模式都包含在树中,并使用DFS技术在最高层消除分支,从而消除多个模式。 - Chris Doyle

0
针对您提到的具体模式,可以编写简单程序来检查输入字符串是否匹配。
如果模式比您提到的更复杂,您可以使用上下文无关文法和正则表达式来指定规则。还有像lex和yacc这样的工具,它们将根据指定的规则处理输入字符串,并返回它们是否匹配。

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)

0

使用以下非常快速的匹配函数很容易实现。

给定模式是PatternElement数组,其中PatternElement由字母和整数组成。

给定数字是Digits数组。

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

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。


0

您可以推断出约束条件,然后使用回溯算法来确定特定数字是否与模式匹配(有时称为约束满足问题)。

例如,我们分别表示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实现(请参见thisJava问题),然后只需将约束转换为Prolog规则即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接