複習recursion

1. 如果這樣數列賦值在recursion之前,則:

private void lop(int x, int size, double[] jerry){
		if(x==size-1){
			jerry[x] = -1;
			return;
		}
		if(jerry[x+1]==0){
			jerry[x+1] = jerry[x]- 1;  //if so, then jerry={1,1,3.14}
			lop(x+1, size, jerry);
		}
		//jerry[x] = jerry[x+1]+ 1;
	}

2. 如果賦值在recursion最後,則:(本意)

private void lop(int x, int size, double[] jerry){
		if(x==size-1){
			jerry[x] = -1;
			return;
		}
		if(jerry[x+1]==0){
			//jerry[x+1] = jerry[x]- 1;  
			lop(x+1, size, jerry);
		}
		jerry[x] = jerry[x+1]+ 1;  //if so, then jerry={5.14,4.14,3.14}
	}

3. 感覺recursion很容易漏掉某些值。所以要多次對instance調用。

/* May 10,2014
 * to understand seamcarver by msi-pl
 * learn how recur in for loop
 */

public class recur{
	public recur(){
		
	}
	private void lop(int x, int y, int size, double[][] jing){
		double feed = 3.14;
		if(y==size-1){
			if(x==0)
				jing[x][y] = feed;
			if(x==1)
				jing[x][y] = feed*10;
			if(x==2)
				jing[x][y] = feed*100;	
			return;
		}
		for(int m = 0; m <size; m++){
			int px = (x+m)%3;
			//if(px >= size)
				//px = 0;
				//continue;
			if(jing[px][y+1]==0){
				lop(px, y+1, size, jing);
			}
		}
		jing[x][y] = jing[x][y+1]+ 1;
	}
	
	public void sh(int dx){
		recur jerry = new recur();
		double[][] tony = new double[dx][dx];
		jerry.lop(0, 0, dx, tony);
		jerry.lop(1, 0, dx, tony);  // need to do so for jerry[1][0];
		jerry.lop(2, 0, dx, tony);  //need to do so for jerry[2][0];
		
		for(int i = 0; i<dx; i++){
			for(int j=0; j<dx; j++){
				StdOut.println(tony[i][j]);
			}
		}
	}
	public static void main(String[] args){
		recur shishi = new recur();
		shishi.sh(3);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章