簡體   English   中英

用於識別數字模式的Java程序

[英]Java program to identify patterns in numbers

我希望創建一個程序來識別數字中的某些模式。 我不確定這是否需要算法或只是仔細考慮編程。 我不是在找人提供源代碼,只是一些發人深省的想法讓我朝着正確的方向前進。

數字將固定長度為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中所示。

我不確定這對任何人是否有意義,但我想我可以根據反饋改進我的問題。

總而言之,我正在尋找有關如何讓程序接受一個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 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. 規范化所有模式
  2. 構建一個深度為6的樹,它代表從root開始的所有模式以及每個深度上的所有可能選擇。

B.運行狀態機


A.1。 模式規范化。

AAAAAA => A0 A0 A0 A0 A0 A0

CACACA => 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開始標准化模式。

A2。 建一棵樹

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.運行狀態機

使用遞歸的深度優先搜索算法來查找匹配的模式。

是否有意義?

您可以將數字分成一個字節數組(或者如果您願意,可以使用整數),每個字符一個。 可以根據陣列的適當元素之間的直接比較來定義每個模式。

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)

通過以下非常快速的匹配功能,這很容易。

鑒於模式是PatternElement的數組,其中PatternElement由Letter和整數組成。

鑒於數字是數字陣列。

現在使用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),您可以通過在替換或匹配期間做一些額外的數學運算來做同樣的事情。

注意:該號碼不需要僅包含數字。 如果你想更換任何字符,你甚至可以匹配類似的模式! 所以ABCABC也會以通用形式匹配DFGDFG。

您可以推斷約束 ,然后使用回溯算法來確定特定數字是否與模式匹配(有時稱為約束滿足問題 )。

例如,讓我們分別表示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實現是有意義的(請參閱Java的這個問題),然后將約束轉換為Prolog規則。

對於您作為示例提到的特定模式,可以編寫簡單的程序來檢查輸入字符串是否匹配。

如果模式比您提到的模式更復雜,您可以使用無上下文語法和正則表達式來指定規則。 還有像lex和yacc這樣的工具,它們將根據指定的規則處理輸入字符串,如果匹配或不匹配則返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM