私はプログラミングと Java の初心者で、Project Euler の Web サイトで作業して独学しようとしています。私はこの問題を解決しようとしています: http://projecteuler.net/problem=19、つまり:
20 世紀 (1901 年 1 月 1 日から 2000 年 12 月 31 日まで) の月の最初の日曜日は何回ありましたか?
私がそれを解決するために考えた方法は、カレンダーを表す 2D 配列を作成し、7 までカウントして配列をループし、7 までカウントするたびに、配列内のそのポイントに 1 を追加することでした。最後に、配列の最初の行を合計します。これは、その月の最初の日曜日の数になります。
しかし、ループに問題があり、月末になると 7 までのカウントがリセットされ、それを止める方法がわかりません。
これが私のコードです:
public class Problem019 {
public static void main (String[] args){
//System.out.println(LeapYearTest(1996));
int ThirtyOne = 31;
int Thirty = 30;
int FebNorm = 28;
int FebLeap = 29;
int a, b, c, Day, e = 0, f = 0;
int Calander[] []= new int [12] [] ;
Calander[0] = new int [ThirtyOne];
Calander[1] = new int [FebNorm];
Calander[2] = new int [ThirtyOne];
Calander[3] = new int [Thirty];
Calander[4] = new int [ThirtyOne];
Calander[5] = new int [Thirty];
Calander[6] = new int [ThirtyOne];
Calander[7] = new int [ThirtyOne];
Calander[8] = new int [Thirty];
Calander[9] = new int [ThirtyOne];
Calander[10] = new int [Thirty];
Calander[11] = new int [ThirtyOne];
for (a=1901;a<2001;a++){
//System.out.println(a);
if (LeapYearTest(a))
{
Calander[1] = new int [FebLeap];
}
else
{
Calander[1] = new int [FebNorm];
}
for (e=0;e<Calander.length;e++)
{
System.out.println("e: " + e);
f=0;
while (f<Calander[e].length)
{
//System.out.println(Calander[e].length);
Day=1;
while (Day<8 && f<Calander[e].length)
{
System.out.println("f: " + f + "\tDay: " + Day + "\tCalander[e][f]: " + Calander[e][f]);
Day++;
f++;
if (f<Calander[e].length && f!=0 && Day==7)
{
Calander[e][f]+= 1;
}
}
}
}
//System.out.println(a);
}
for (b=0;b<Calander.length;b++)
{
System.out.print(Calander[0][b]);
}
}
public static boolean LeapYearTest(int x)
{
if (x%4==0 || x%400==0){
return true;
}
if (x%100==0){
return false;
}
else return false;
}
}
これは出力されるもので、e は月、f は月の日数、Day は 7 まで数えます:
f: 25 Day: 5 Calander[e][f]: 0
f: 26 Day: 6 Calander[e][f]: 0
f: 27 Day: 7 Calander[e][f]: 100
f: 28 Day: 1 Calander[e][f]: 0
f: 29 Day: 2 Calander[e][f]: 0
**f: 30 Day: 3 Calander[e][f]: 0**
e: 10
**f: 0 Day: 1 Calander[e][f]: 0**
f: 1 Day: 2 Calander[e][f]: 0
f: 2 Day: 3 Calander[e][f]: 0
Day が月末にリセットされないようにループを設定するにはどうすればよいですか? または、ネストされたループがそれほど多くないこの問題を解決する別の方法はありますか?
ありがとうございました!