开发者

Iteration to recursion

开发者 https://www.devze.com 2023-04-01 13:03 出处:网络
private int array[][] = new int[5][5]; priva开发者_JAVA技巧te void arrayIteration(){ for(int i = 0; i < array.length; i++){
private int array[][] = new int[5][5];

priva开发者_JAVA技巧te void arrayIteration(){
    for(int i = 0; i < array.length; i++){
        for(int j = 0; j < array.length; j++){
            array[i][j] = 10;
        }
    }
}

Can I change the iteration method to recursive one that does the same task?

Edit (this is what I've tried but it's just playing with what I want to do):

private void arrayRecursion(){
    if(){
        array[i][i] = 10;  // Base
        return;
    }
    for(int i = 0; i < array.length; i++){
        arrayRecursion();
    }
}


Yes, you can. However, you shouldn't want to. I can write all my applications in assembly code but that doesn't make it a good idea :-)

There are a few algorithms that lend themselves naturally to recursion, those whose operations can be expressed in terms of the same operation on a smaller data set or lesser value (tree traversal, factorials, that sort of thing).

Initialising an array to all zeros is not one of those things.


Here's one way you could do it. Basically you start in the 0,0 corner and set it to the value. Then you do 0,1 and 1,0. 0,1 will set, and do 1,1 and 1,2. 1,0 will set and do 2,0 and 1,1. Note that 1,1 just got hit twice - that's fine because it's overwriting what it did before. When it hits a 'wall' it stops (this means if the [3] array was null, [4] wouldn't get hit) but that isn't a problem for arrays allocated with new int[x][y] notation.

class Sandbox {
    public static void main(String[] args) {
        int[][] test = new int[5][5];
        recursiveAssign(test,10);
        int numThatAreTen = 0;
        for(int i = 0; i < 5; i++) {
            for(int j = 0; j < 5; j++) {
                if(test[i][j] == 10) numThatAreTen++;
            }
        }
        System.out.println(numThatAreTen);
    } // main

    static void recursiveAssign(int[][] arr, int value) {
        recursiveAssign0(arr,value,0,0);
    } // recursiveAssign

    static private void recursiveAssign0(int[][] arr, int value, int x, int y) {
        if(arr != null && x < arr.length && arr[x] != null && y < arr[x].length) {
            arr[x][y] = value;
            // now go down, and across
            recursiveAssign0(arr,value,x+1,y);
            recursiveAssign0(arr,value,x,y+1);
        } 
    } // recursiveAssign0

} // Sandbox

which prints the expected 25

C:\Documents and Settings\glowcoder\My Documents>javac Sandbox.java

C:\Documents and Settings\glowcoder\My Documents>java Sandbox
25

C:\Documents and Settings\glowcoder\My Documents>
0

精彩评论

暂无评论...
验证码 换一张
取 消