1

私は次のようなタプルクラスを持っています:

private class Tuple {
    private int fileno;
    private int position;

    public Tuple(int fileno, int position) {
        this.fileno = fileno;
        this.position = position;
    }
}

このリストを次のように参照するハッシュマップもあります

    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();

ここで、ファイル内の単語数を数える必要があるシナリオがあります。データは次のとおりです。

abc 10.txt
abc 10.txt
abc 10.txt
abc 12.txt
abc 12.txt
ghost 15.txt
and so on....

さて、上記の発生数を数える方法は?簡単ですが、私は長い間コーディングを行っており、Javaも初めてです。また、重複はハッシュマップに入れられないことも学びました。ありがとう。

リストにデータを追加するには:

List<Tuple> idx = index.get(word);
                            if (idx == null) {
                                idx = new LinkedList<Tuple>();
                                index.put(word, idx);
                            }
                            idx.add(new Tuple(fileno, pos));

上記のコードはデータをダンプするだけです。次に、文字列配列[]の単語と比較します。最後に必要なのは次のようなものです:abc 10.txt count-3 abc 12.txt count-2 ghost 15.txt count-1

マップが役立つかどうか/リストを再度使用する必要がある/これを行うための関数を作成する必要があるかどうかわかりませんか?ありがとう!

上記の問題を簡単な条件ステートメントで解決しました!ありがとう@codeguru

/*
                     consider all cases and update wc as along
                     Lesson learnt - Map does not handle duplicates
                                    - List does not work
                                    - spend half a day figuring out 
                     */
                    if(wordInstance == null && fileNameInstance == null) {
                          wordInstance = wordOccurence;
                          fileNameInstance = files.get(t.fileno);
                    }
                    if(wordInstance == wordOccurence && fileNameInstance ==files.get(t.fileno)) {
                          wc++;
                    }
                    if(wordInstance == wordOccurence && fileNameInstance !=files.get(t.fileno)) {
                        wc=0;
                        fileNameInstance = files.get(t.fileno);
                        wc++;
                    }
                    if(wordInstance != wordOccurence && fileNameInstance ==files.get(t.fileno)) {
                        wc=0;
                        wordInstance = wordOccurence;
                        wc++;
                    }
4

1 に答える 1

1

これを必要以上に複雑にしているのではないかと思います。コンピューターから一歩後退することをお勧めします。まず、簡単な入力例を取り上げて、出力がどうあるべきかを手作業で理解する必要があります。次に、この出力を実行するために実行した手順を説明するいくつかの文を(母国語で)記述します。そこから、Javaに簡単に翻訳できるようになるまで、説明を改良する必要があります。

于 2012-10-16T15:54:35.973 に答える