Created
April 20, 2012 02:43
-
-
Save lessandro/2425452 to your computer and use it in GitHub Desktop.
puzzle #1. <algorithm> is just awesome.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <cstdio> | |
#include <cstring> | |
#define BUFSIZE (sizeof("aa/bb/cccc")) | |
using namespace std; | |
bool leap(int year) | |
{ | |
// Recall that a year is a leap year (has 366 days) if the year is divisible by 4, | |
// unless it is divisible also by 100 | |
// but not by 400 | |
if (year % 4 != 0) | |
return false; | |
if (year % 100 != 0) | |
return true; | |
return (year % 400 == 0); | |
} | |
bool valid(int year, int month, int day) | |
{ | |
// fix year | |
if (year < 1000) | |
year += 2000; | |
// basic checks | |
if (month < 1 || month > 12) | |
return false; | |
if (day < 1 || day > 31) | |
return false; | |
// month length | |
if (month == 2 && day > 29) | |
return false; | |
if (day == 31 && (month & 1) == (month > 7)) | |
return false; | |
// leap year | |
if (month == 2 && day == 29 && !leap(year)) | |
return false; | |
printf("%d-%02d-%02d\n", year, month, day); | |
return true; | |
} | |
int main() | |
{ | |
char buf[BUFSIZE]; | |
int vec[3]; | |
// read the thing | |
fgets(buf, BUFSIZE, stdin); | |
// remove first \n char | |
strtok(buf, "\n"); | |
// scan ints into our array | |
sscanf(buf, "%d/%d/%d", vec, vec+1, vec+2); | |
// sort it before using next_permutation | |
sort(vec, vec+3); | |
do { | |
if (valid(vec[0], vec[1], vec[2])) | |
return 0; | |
} | |
while (next_permutation(vec, vec+3)); | |
printf("%s is illegal\n", buf); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment