多次元配列を使用してパスカル三角形のオブジェクトを作成するクラスを作成しようとしています。これで、配列の正しい初期化を除いて、すべてが整っています(少なくともそう思います)。私のプログラムは次のようになります。
class Pascal{
//Object variables
int size;
int[][] pascal;
Pascal(int size){ //Constructor
this.size = size; //Defines how many rows/columns the triangle has.
pascal = new int[size][];
//Allocation of the arrays
for(int i=0;i<pascal.length;i++)
pascal[i] = new int[i+1];
pascal[0][0] = 1; //the tip of the triangle is always one. Also you need a value to start with.
//Initialisation of the elements
for(int x=0;x<pascal.length;x++){
for(int y=0;y<pascal[x].length;y++){
if(x>0){
if(y==0 || y == (pascal[x].length)-1)
pascal[x][y] = 1; //Initialisation of the first and last element of the actual array x
else
pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//Initialisation of all elements in between
}
}
}
}
//The print method needed to display the pascal triangle
void print(){
for(int i=0;i<pascal.length;i++){
for(int k=pascal.length;k>i;k--)
System.out.print(" ");
for(int j=0;j<pascal[i].length;j++)
System.out.print(pascal[i][j]+" ");
System.out.println();
}
}
//main function
public static void main(String... args){
Pascal p = new Pascal(5); //example triangle consisting of 5 rows total
p.print();
}
}
この特定の例 (new Pascal(5);) の出力は次のようになります。
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
それでも、それは次のとおりです。
1
2 1
1 1 1
1 0 1 1
1 0 0 0 1
問題はコードの配列初期化部分のどこかにあるに違いないことはわかっています。おそらく単純な間違いですが、モニターを見つめても、もうどこにも行きません:/
答えを教えたくない場合に備えて: 私の理解では、for ループの値 x が 1 で値 y が 0 であるため、配列要素 pascal[1][0] は 2 ではなく 1 である必要があります。 if-condition if( y==0 || y==pascal[x].length-1) が適用され、pascal[1][0] = 1 が設定されます。
ご協力いただきありがとうございます!