Hi I am trying to solve the puzzles on the spotify website - http://www.spotify.com/uk/jobs/tech/best-before/
I'm writing it in C++ and im getting some very annoying results. I have an int called pause
which is usless and does nothing, but when I delete it my program seems to return the wrong result.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int Year;
int Month;
int Day;
int pause; // <--- My useless INT which when Deleted my code returns wrong output
stringstream ss;
string input;
string in;
bool loop=true;
int date[3];
bool DateFound=false;
void Check_date();
void Check_date()
{
if(DateFound==false)
{
//Check if valid Year
if (date[1]<2999 && date[1]>0 && date[2]>0 && date[3]>0)
{ //check months & days are valid
if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]<=31){DateFound=true;}}
if(date[2]==4 || date[2]==6 || date[2]==9 || date[2]==11){if(date[3]<=30){DateFound=true;}}
//Check For Leap Year
if (date[2]==2)
{ if(date[3]<28)DateFound=true;
if(date[1]%4==0 && date[3]<=29)DateFound=true;
if(date[1]%100==0 && date[1]%400!=0 && date[3]>28)DateFound=false;
}
if(DateFound==true){Year=date[1]; Month=date[2]; Day=date[3];}
}
}
}
void SwitchDate(){int temp; temp=date[2]; date[2]=date[3]; date[3]=temp;
Check_date();};
void ShiftDate(int places)
{ if(places==1)
{
int temp; temp=date[3]; date[3]=date[2]; date[2]=temp; temp=date[1]; date[1]=date[2]; date[2]=temp; Check_date();
}
if(places==2)
{
int temp; temp=date[1]; date[1]=date[2]; date[2]=temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();
}
};
int main ()
{
while(loop==true)
{
cin >> input;
for (int x=0, y=1; y<4; y++, x++)
{
while (input[x] !='/' && x !=input.length()) ss<<input[x++];
ss>> date[y];
ss.clear();
}
//order small medium large
for (int x=3, temp; x!=0; x--)
{
if (date[x] < date[x-1])
{ temp=date[x-1];
date[x-1]=date[x];
date[x]=temp;
}
if (x==1 && (date[2] > date[3] ))
{
temp=date[3];
date[3]=date[2];
date[2]=temp;
}
}
Check_date();//return true
SwitchDate();
ShiftDate(1);
SwitchDate();
ShiftDate(2);
SwitchDate();
//PRINT
cout <<Year; cout<< endl;
cout <<Month; cout<< endl;
cout <<Day; cout<< endl;
// 13/12/5
cout <<"Again? 'Y' or 'N' \n";
cin >>in;
if(in=="y" || in=="Y"){loop=true;}
if(in=="n" || in=="N"){loop=false;}
}
return 0;
}
int date[3];
You have declared date
as an arary of three int
s. The three int
s are called: date[0]
, date[1]
, and date[2]
.
Yet, in this line
if (date[1]<2999 && date[1]>0 && date[2]>0 && date[3]>0)
you refer to something called date[3]
, which doesn't exist.
In C and C++, arrays are zero-based. That is, the first element is indexed by 0
. If the array is of size N, then the final element is indexed by N-1.