質問

つまり、次のようなことができます

for() {
    for {
       for {
       }
    }
}

N回を除きますか?言い換えると、ループを作成するメソッドが呼び出されると、パラメーターNが与えられ、メソッドはこれらのループのN個を別の入れ子に作成しますか?

もちろん、アイデアは<!> quot; easy <!> quot;または<!> quot;通常の<!> quot;それを行う方法。私はすでに非常に複雑なもののアイデアを持っています。

役に立ちましたか?

解決

再帰

を調べてください。

他のヒント

jjnguyは正しい。再帰により、可変深さのネストを動的に作成できます。ただし、少し作業をしないと、外側のレイヤーからデータにアクセスできません。 <!> quot; in-line-nested <!> quot;ケース:

for (int i = lo; i < hi; ++i) {
    for (int j = lo; j < hi; ++j) {
        for (int k = lo; k < hi; ++k) {
            // do something **using i, j, and k**
        }
    }
}

使用する最も内側のボディのスコープ内で変数ij、およびkを保持します。

これを行うための簡単なハックが1つあります:

public class NestedFor {

    public static interface IAction {
        public void act(int[] indices);
    }

    private final int lo;
    private final int hi;
    private final IAction action;

    public NestedFor(int lo, int hi, IAction action) {
        this.lo = lo;
        this.hi = hi;
        this.action = action;
    }

    public void nFor (int depth) {
        n_for (0, new int[0], depth);
    }

    private void n_for (int level, int[] indices, int maxLevel) {
        if (level == maxLevel) {
            action.act(indices);
        } else {
            int newLevel = level + 1;
            int[] newIndices = new int[newLevel];
            System.arraycopy(indices, 0, newIndices, 0, level);
            newIndices[level] = lo;
            while (newIndices[level] < hi) {
                n_for(newLevel, newIndices, maxLevel);
                ++newIndices[level];
            }
        }
    }
}

IActionインターフェースは、actメソッドへの引数としてインデックスの配列を取る制御されたアクションの役割を規定します。

この例では、NestedForの各インスタンスは、反復制限と最も内側のレベルで実行されるアクションを持つコンストラクターによって構成されます。 nForメソッドのパラメーターは、ネストの深さを指定します。

使用例は次のとおりです。

public static void main(String[] args) {
    for (int i = 0; i < 4; ++i) {
        final int depth = i;
        System.out.println("Depth " + depth);
        IAction testAction = new IAction() {
            public void act(int[] indices) {
                System.out.print("Hello from level " + depth + ":");
                for (int i : indices) { System.out.print(" " + i); }
                System.out.println();
            }
        };
        NestedFor nf = new NestedFor(0, 3, testAction);
        nf.nFor(depth);
    }
}

およびその実行からの(部分的な)出力:

Depth 0
Hello from level 0:
Depth 1
Hello from level 1: 0
Hello from level 1: 1
Hello from level 1: 2
Depth 2
Hello from level 2: 0 0
Hello from level 2: 0 1
Hello from level 2: 0 2
Hello from level 2: 1 0
Hello from level 2: 1 1
Hello from level 2: 1 2
Hello from level 2: 2 0
Hello from level 2: 2 1
Hello from level 2: 2 2
Depth 3
Hello from level 3: 0 0 0
Hello from level 3: 0 0 1
Hello from level 3: 0 0 2
Hello from level 3: 0 1 0
...
Hello from level 3: 2 1 2
Hello from level 3: 2 2 0
Hello from level 3: 2 2 1
Hello from level 3: 2 2 2

あなたが本当にやりたいことを説明したいかもしれません。

外側のforループがカウントを制御するだけである場合、ネストされた<=>ループは、単一の<=>ループで処理できるカウントによる反復のより複雑な方法です。

例:

for (x = 0; x < 10; ++x) {
  for (y = 0; y < 5; ++y) {
    for (z = 0; z < 20; ++z) {
      DoSomething();
    }
  }
}

と同等:

for (x = 0; x < 10*5*20; ++x) {
  DoSomething();
}

先日、これについて実際に考えていました。

おそらく完璧ではないが、私が尋ねられていると思うものにかなり近い例は、ディレクトリツリーを印刷することでしょう

public void printTree(directory) {
   for(files in directory) {
      print(file);
      if(file is directory) {
          printTree(file);
      }
   }
}

この方法では、forループのスタックが相互に入れ子になり、それらがどのように連携するかを正確に把握する手間がかかりません。

2015編集:前の呪文と同じ無駄に、これを処理するために次のパッケージを作成しました。 https://github.com/BeUndead/NFor

使用方法は次のとおりです

public static void main(String... args) {
    NFor<Integer> nfor = NFor.of(Integer.class)
            .from(0, 0, 0)
            .by(1, 1, 1)
            .to(2, 2, 3);

    for (Integer[] indices : nfor) {
        System.out.println(java.util.Arrays.toString(indices));
    }
}

結果

[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[1, 0, 0]
[1, 0, 1]
[1, 0, 2]
[1, 1, 0]
[1, 1, 1]
[1, 1, 2]

lessThan以外の条件もサポートします。使用方法(import static NFor.*;を使用):

NFor<Integer> nfor = NFor.of(Integer.class)
        .from(-1, 3, 2)
        .by(1, -2, -1)
        .to(lessThanOrEqualTo(1), greaterThanOrEqualTo(-1), notEqualTo(0));

結果:

[-1, 3, 2]
[-1, 3, 1]
[-1, 1, 2]
[-1, 1, 1]
[-1, -1, 2]
[-1, -1, 1]
[0, 3, 2]
[0, 3, 1]
[0, 1, 2]
[0, 1, 1]
[0, -1, 2]
[0, -1, 1]
[1, 3, 2]
[1, 3, 1]
[1, 1, 2]
[1, 1, 1]
[1, -1, 2]
[1, -1, 1]

明らかに、異なる長さと異なるクラス(すべてのボックス化された数値プリミティブ)のループがサポートされています。デフォルト(指定しない場合)はfrom(0、...)。by(1、...);ただし、to(...)を指定する必要があります。

NForTestファイルは、いくつかの異なる使用方法を示す必要があります。

これの基本的な前提は、再帰を使用するのではなく、単に各インデックスを「インデックス」に進めることです。

問題にはさらに仕様が必要です。再帰が役立つかもしれませんが、ほとんどの場合、再帰は反復の代替であり、その逆も同様です。 2レベルのネストされたループで十分な場合があります。解決しようとしている問題をお知らせください。

ネストループの背後にある基本的な考え方は、乗算です。

Michael Burrの答えを拡張して、外側のforループがカウントを制御するだけの場合、nカウントに対するネストされたXループは、単にカウントの積を反復するより複雑な方法です単一のYループ。

次に、この考え方をリストに拡張しましょう。ネストされたループで3つのリストを反復処理する場合、これは単一のループでリストの積を反復処理するより複雑な方法です。しかし、3つのリストの積をどのように表現しますか?

最初に、型の積を表現する方法が必要です。 P2<X, Y>P3<A, B, C>の2つのタイプの積は、List<X>のような汎用タイプとして表現できます。これは、1つのタイプList<Y>ともう1つのタイプList<Z>の2つの値で構成される単なる値です。次のようになります。

public abstract class P2<A, B> {
  public abstract A _p1();
  public abstract B _p2();
}

3つのタイプの製品の場合、明らかな3番目の方法でList<P3<X, Y, Z>>があります。したがって、3つのリストの製品は、製品タイプにリストファンクターを配布することによって実現されます。したがって、ListdoSomething、および<=>の積は単純に<=>です。その後、1つのループでこのリストを反復処理できます。

Functional Java ライブラリには、ファーストクラスの関数と製品タイプを使用したリストの乗算をサポートする<=>タイプがあります(P2、P3など。これらもライブラリに含まれています)。

例:

for (String x : xs) {
   for (String y : ys) {
     for (String z : zs) {
       doSomething(x, y, z);
     }
   }
}

と同等:

for (P3<String, String, String> p : xs.map(P.p3()).apply(ys).apply(zs)) {
   doSomething(p._1(), p._2(), p._3());
}

Functional Javaをさらに進めると、次のように<=>をファーストクラスにすることができます。 <=>が文字列を返すとしましょう:

public static final F<P3<String, String, String>, String> doSomething =
  new F<P3<String, String, String>, String>() {
    public String f(final P3<String, String, String> p) {
      return doSomething(p._1(), p._2(), p._3());
    }
  };

その後、forループを完全に削除し、<=>:

のすべてのアプリケーションの結果を収集できます。
List<String> s = xs.map(P.p3()).apply(ys).apply(zs).map(doSomething);

次のような一般的なネストループ構造を持っている場合:

for(i0=0;i0<10;i0++)
    for(i1=0;i1<10;i1++)
        for(i2=0;i2<10;i2++)
            ....
                for(id=0;id<10;id++)
                    printf("%d%d%d...%d\n",i0,i1,i2,...id);

i0,i1,i2,...,idはループ変数、dはネストされたループの深さです。

同等の再帰ソリューション:

void nestedToRecursion(counters,level){
    if(level == d)
        computeOperation(counters,level);
    else
    {
        for (counters[level]=0;counters[level]<10;counters[level]++)
            nestedToRecursion(counters,level+1);
    }
}
void computeOperation(counters,level){
    for (i=0;i<level;i++)
        printf("%d",counters[i]);
    printf("\n");
}

countersは、サイズi0,i1,i2,...idの配列で、対応する変数int counters[d]それぞれinitial[d], ending[d]を表します。

nestedToRecursion(counters,0);

同様に、再帰の初期化や終了などの変数を配列を使用して変換できます。つまり、<=>を使用できます。

Java 7で思いついた最も一般的なアプローチは

// i[0] = 0..1  i[1]=0..3, i[2]=0..4
MultiForLoop.loop( new int[]{2,4,5}, new MultiForLoop.Callback() { 
    void act(int[] i) { 
        System.err.printf("%d %d %d\n", i[0], i[1], i[2] );
    }
}

またはJava 8の場合:

// i[0] = 0..1  i[1]=0..3, i[2]=0..4
MultiForLoop.loop( new int[]{2,4,5}, 
   i -> { System.err.printf("%d %d %d\n", i[0], i[1], i[2]; } 
);

これをサポートする実装は次のとおりです。

/**
 * Uses recursion to perform for-like loop.
 *  
 * Usage is 
 *  
 *    MultiForLoop.loop( new int[]{2,4,5}, new MultiForLoop.Callback() { 
 *        void act(int[] indices) { 
 *            System.err.printf("%d %d %d\n", indices[0], indices[1], indices[2] );
 *        }
 *    }
 *  
 * It only does 0 - (n-1) in each direction, no step or start 
 * options, though they could be added relatively trivially.
 */
public class MultiForLoop {

    public static interface Callback {
        void act(int[] indices);
    }

    static void loop(int[] ns, Callback cb) {
        int[] cur = new int[ns.length];
        loop(ns, cb, 0, cur);
    }

    private static void loop(int[] ns, Callback cb, int depth, int[] cur) {
        if(depth==ns.length) {
            cb.act(cur);
            return;
        }

        for(int j = 0; j<ns[depth] ; ++j ) {
            cur[depth]=j;
            loop(ns,cb, depth+1, cur);
        }
    }
}
String fors(int n){
StringBuilder bldr = new StringBuilder();
for(int i = 0; i < n; i++){
    for(int j = 0; j < i; j++){
        bldr.append('\t');
    }
    bldr.append("for() {\n");
}
for(int i = n-1; i >= 0; i--){
    for(int j = 0; j < i; j++){
        bldr.append('\t');
    }
    bldr.append("}\n");
}
return bldr.toString();
}

素敵なネストされたforループスケルトンを作成します;-) 完全に深刻なわけではなく、再帰的なソリューションの方がエレガントだと思います。

public void recursiveFor(Deque<Integer> indices, int[] ranges, int n) {

    if (n != 0) {

       for (int i = 0; i < ranges[n-1]; i++) {

          indices.push(i);
          recursiveFor(indices, ranges, n-1);
          indices.pop();
       }
    }

    else {

       // inner most loop body, access to the index values thru indices
       System.out.println(indices);
    }
}

サンプル呼び出し:

int[] ranges = {2, 2, 2};

recursiveFor(new ArrayDeque<Integer>(), ranges, ranges.length);

質問に初めて答えたが、この情報を共有する必要があると感じた の `

for (x = 0; x < base; ++x) {
  for (y = 0; y < loop; ++y) {
      DoSomething();
  }
}

同等であること

for (x = 0; x < base*loop; ++x){
    DoSomething();
}

したがって、n個のネストが必要な場合は、baseloopの除算を使用して書き込むことができるため、次のように簡単に見えるようになります。

char[] numbs = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
     public void printer(int base, int loop){
       for (int i = 0; i < pow(base, loop); i++){
         int remain = i;
         for (int j = loop-1; j >= 0; j--){
           int digit = remain/int(pow(base, j));
           print(numbs[digit]);
           remain -= digit*pow(base, j);
         }
         println();
       }
     }

したがって、printer(10, 2);と入力すると、印刷されます。

00
01
02
03
04
...
97
98
99

これは本当にうまくいきました-myAlternativePathsに保存されたいくつかの選択肢から選択する必要がありました。基本的な考え方は、次の選択を構築しようとしていて、<!> quot; overflow <! > quot; 1つのディメンション/コンポーネントで、そのディメンションを再初期化し、次のディメンションに追加します。

public boolean isValidAlternativeSelection (int[] alternativesSelected) {
    boolean allOK = true;
    int nPaths= myAlternativePaths.size();
    for (int i=0; i<nPaths; i++) {
        allOK=allOK & (alternativesSelected[i]<myAlternativePaths.get(i).myAlternativeRoutes.size());
    }
    return allOK;
}


public boolean getNextValidAlternativeSelection (int[] alternativesSelected) {
    boolean allOK = true;
    int nPaths= myAlternativePaths.size();
    alternativesSelected[0]=alternativesSelected[0]+1;
    for (int i=0; i<nPaths; i++) {
        if (alternativesSelected[i]>=myAlternativePaths.get(i).myAlternativeRoutes.size()) {
            alternativesSelected[i]=0;
            if(i<nPaths-1) {
                alternativesSelected[i+1]=alternativesSelected[i+1]+1;
            } else {
                allOK = false;
            }
        }
 //       allOK=allOK & (alternativesSelected[i]<myAlternativePaths.get(i).myAlternativeRoutes.size());
    }
    return allOK;
}

簡潔にするために、ここにコードを配置しています:

void variDepth(int depth, int n, int i) {
    cout<<"\n d = "<<depth<<" i = "<<i;
    if(!--depth) return;
    for(int i = 0;i<n;++i){
        variDepth(depth,n,i);
    }
}
void testVariDeapth()
{   variDeapth(3, 2,0);
}

出力

 d = 3 i = 0
 d = 2 i = 0
 d = 1 i = 0
 d = 1 i = 1
 d = 2 i = 1
 d = 1 i = 0
 d = 1 i = 1
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top