-
-
Save brucewoodward/e2309b224ba902c66fc79ca0c9ad5799 to your computer and use it in GitHub Desktop.
Playing with C and Ruby
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 <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
char *monthnames[] = { | |
(char*)0, "January", "February", "March", "April", "May", "June", | |
"July", "August", "September", "October", "November", "December" | |
}; | |
int days_in_month[] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; | |
struct date { | |
int day, month, year; | |
}; | |
int is_leap_year(struct date *today) | |
{ | |
return ((today->year & 3) == 0 && ((today->year % 25) != 0 || (today->year & 15) == 0)); | |
} | |
void next_day(struct date *today) | |
{ | |
bool moving_to_next_month = (today->day == days_in_month[today->month]); | |
bool moving_to_next_year = (moving_to_next_month && (today->month == 12)); | |
if (moving_to_next_year) { | |
today->year++; | |
today->month = 1; | |
today->day = 1; | |
days_in_month[2] = is_leap_year(today) ? 29 : 28; | |
} | |
else if (moving_to_next_month) { | |
today->month++; | |
today->day = 1; | |
} | |
else { /* next day */ | |
today->day++; | |
} | |
} | |
int main() | |
{ | |
struct date today = { 1, 7, 2017 }; /* start of the financial year */ | |
for (int i = 1; i <= 365; i++) { | |
printf("%d,%d,%s,%d\n", i, today.year, monthnames[today.month], today.day); | |
next_day(&today); | |
} | |
exit(0); | |
} |
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
#!/usr/bin/env ruby | |
require 'csv' | |
require 'date' | |
require 'time' | |
seconds_in_day = 86400 | |
today = start_time = Time.parse("1 July 2017") | |
(1..365).each do |day_of_fin_year| | |
puts CSV.generate_line([ day_of_fin_year, today.year, Date::MONTHNAMES[today.month], today.day ]) | |
today = Time.at(start_time + (day_of_fin_year * seconds_in_day)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I needed code to generate CSV for each day in the financial year to imported into a spreadsheet. Wrote the Ruby version first and decided to see what the code would look like if written in C. Decided to compare the time that each version took to run, even though the Ruby version runs in less than a second.