7

数字の特定のパターンを識別するプログラムを作成しようとしています。これにアルゴリズムが必要なのか、プログラミングを慎重に考えただけなのかはわかりません。私はソースコードを提供してくれる人を探しているのではなく、正しい方向に私を始めるための刺激的なアイデアを探しています。

数値は、000000から999999までの6桁の固定長になります。各数値は、配列の一部として格納されると思います。次に、パターンに対して数値をテストしたいと思います。

たとえば、私が使用している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)などを試してください

このシナリオでは、番号234874のように、Cに割り当てられた値が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 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;
}

}

これのいずれかが同様の問題を抱えている人に役立つかどうか、またはこれがどのように機能しているかについて誰かがコメントを持っているかどうかはわかりません。

4

5 に答える 5

2

ステートマシンを構築することをお勧めします:

A.パターンによる初期化:

  1. すべてのパターンを正規化する
  2. ルートから始まるすべてのパターンとすべての深さで可能なすべての選択肢を表す深さ=6のツリーを構築します。

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で始まる正規化されたパターンがあります。

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.ステートマシンを実行する

再帰を使用した深さ優先探索アルゴリズムを使用して、一致するパターンを見つけます。

それは意味がありますか?

于 2012-07-10T22:24:18.800 に答える
0

例として挙げた特定のパターンについては、入力文字列が一致するかどうかを確認するための簡単なプログラムを作成できます。

パターンが言及したパターンよりも複雑になる場合は、文脈自由文法と正規表現を使用してルールを指定できます。また、lexやyaccのようなツールがあり、指定されたルールに従って入力文字列を処理し、一致するかどうかを返します。

于 2012-07-11T09:56:46.347 に答える
0

数値を、文字ごとに1つずつ、バイトの配列(または必要に応じてint)に分割できます。各パターンは、配列の適切な要素間の直接比較の観点から定義できます。

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)
于 2012-07-10T22:12:12.273 に答える
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)の場合、置換またはマッチング中に追加の計算を行うことで、同じことができます。

注:数字は数字だけで構成されている必要はありません。文字を置き換えたい場合は、同様のパターンに一致させることもできます。したがって、ABCABCは一般的な形式のDFGDFGとも一致します。

于 2012-07-10T22:37:13.073 に答える
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

あなたの例では、2種類の推論されたルールしか見ることができません-1つは数字の等式(パターン内の位置が同じ文字の場合はd1 = d2)、もう1つは算術演算(AとBが異なる数であるかどうかはわかりません) 、もしそうなら、不平等のための追加の種類のルールが必要になります)。すべての種類は、簡単に制約に変換できます。

次に、考えられる解決策のツリーをこれらの制約からコンパイルできます。次のようなもので始まる場合があります。

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

次に、他のノードに制約を含めます。

自分でバックトラッキングアルゴリズムを正しく実装するのは難しいかもしれないので、プラットフォームのProlog実装を見つけて(Javaについてはこの質問を参照)、制約をPrologルールに変換するのが理にかなっています。

于 2012-07-10T23:28:26.910 に答える