Thursday, March 17, 2011

C++ simulation for a puzzle

Sometimes we can find the answers by simulations easier than by logic. (In this case logic is also pretty easy )
The problem : On what day Sat/Sun(For that matters any combination ) will 1st of january fall mostly( Again for that matter any date )

// Purpose : The code try to simulate all the years till 2401 and find which day is on 31st december each year
//Logic:
// Because of the leap year rule we have exacly (400*365+100-3) day and its divisible by 7 completely hence we just
// need to check till 400 years
// Author: Tanmay Dutta
#include
#define start 2002
#define end 2401
using namespace std;
int main()
{
int year,day,count[7];
bool isleap,iscentury;
isleap= false;
iscentury = false;
day=0;
// initializing count to zero
for(int i =0;i<7; i++)
count[i]=0;
enum weekdays{ mon,tue,wed,thr,fri,sat,sun}; // starts with monday = 0
// We know that on 2010 31st dec was on friday
count[day]=1;
for(year = start; year<=end; year++)
{
// check for leap year
if(year%4 ==0)
isleap=true;
// leap year rule does not apply to years with last two digits as 100
if(year%100==0)
isleap = false;
// this rule has an exception at 400 again
if(year%400==0)
isleap=true;
if(isleap)
day=day+2;
else
day=day+1;
if(day==7)
day = 0;
if(day==8)
day=1;
isleap = false;
count[day]+=1;
}
cout<<"Mon"<<'\t'<<"Tue"<<'\t'<<"Wed"<<'\t'<<"Thr"<<'\t'<<"Fri"<<'\t'<<"Sat"<<'\t'<<"Sun"<<'\n';
for(int i =0;i<7; i++)
cout< cout<<'\n';
system("PAUSE");

}

No comments:

Post a Comment