Resolviendo el problema 19, Dios santo olvidaba la sensacion de cuando resuelvo un problema de Project Euler, termino, mi solucion es lenta y grande y veo las demas y oh sorpresa!, las soluciones que los otros plantean son tan sencillas que te quieres volver loco…
Asi fue el caso con este problema… aunque mi solucion en Java no fue tan diferente a las demas planteadas en algunos lenguajes parecidos como CSharp (no lo hice en Python esta vez por que no he usado datetime ahi).
API API API API API API!…
Empece este problema utilizando Python, los datos que venian como anios biciestos, dias de los meses… pero despues, me dije a mi mismo… Porque diablos estoy empezando desde 0 si en el JDK puedo utilizar java.util.Date o GregorianCalendar?! (datetime en python pero no he usado mucho asi que decidi hacerlo en Java primero)
En fin… termine con esta solucion:
package org.otfusion.euler.problema19;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Calendar;
public class Main {
private static Calendar mCalendar;
/**
* @param args
*/
public static void main(String[] args) {
/*
* You are given the following information, but you may prefer to do some research for yourself.
*
* 1 Jan 1900 was a Monday.
* Thirty days has September,
* April, June and November.
* All the rest have thirty-one,
* Saving February alone,
* Which has twenty-eight, rain or shine.
* And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
*
* How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
*/
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
int year = 1901;
mCalendar = new GregorianCalendar(year, Calendar.JANUARY, 1);
int months[] = {Calendar.JANUARY,Calendar.FEBRUARY,Calendar.MARCH,Calendar.APRIL,Calendar.MAY,Calendar.JUNE,
Calendar.JULY,Calendar.AUGUST,Calendar.SEPTEMBER, Calendar.OCTOBER,Calendar.NOVEMBER,Calendar.DECEMBER};
int total = 0;
while (year < 2001) {
for (int i = 0; i < months.length; i++) {
mCalendar.set(year, months[i], 1);
String str = sdf.format(mCalendar.getTime());
if (str.equalsIgnoreCase("sun")) {
total++;
}
}
year++;
}
System.out.println(total);
}
}
Por si quieren saber la solucion es 171, sean o no tramposos lo ivan a correr, asi que mejor la escribo de una vez. Igual no se trata de completar los problemas, si no llegar a la solucion por ti mismo.
Luego hare la solucion en Python.