Skip to content

Instantly share code, notes, and snippets.

@tsheaff
Last active February 20, 2018 00:13
Show Gist options
  • Save tsheaff/f88c82428f10eb9d0e9f2771cce9c622 to your computer and use it in GitHub Desktop.
Save tsheaff/f88c82428f10eb9d0e9f2771cce9c622 to your computer and use it in GitHub Desktop.
const _ = require('lodash');
const moment = require('moment');
const birthdays = [
'February 22', // Washington
'October 30', // Adams
'April 13', // Jefferson
'March 16', // Madison
'April 28th', // Monroe
'July 11', // Quincy Adams
'March 15', // Jackson
'December 5', // Van Buren
'February 9', // Harrison
'March 29', // Tyler
'November 2', // Polk
'November 24', // Taylor
'January 7', // Fillmore
'November 23', // Pierce
'April 23', // Buchanan
'February 12', // Lincoln
'December 29', // Johnson
'April 27', // Grant
'October 4', // Hayes
'November 19', // Garfield
'October 5', // Arthur
'March 18', // Cleveland
'August 20', // Harrison
'January 29', // McKinley
'October 27', // Roosevelt
'September 15', // Taft
'December 28', // Wilson
'November 2', // Harding
'July 4', // Coolidge
'August 10', // Hoover
'January 30', // Roosevelt
'May 8', // Truman
'October 14', // Eisenhower
'May 29', // Kennedy
'August 27', // Johnson
'January 9', // Nixon
'July 14', // Ford
'October 1', // Carter
'February 6', // Reagan
'June 12', // Bush
'August 19', // Clinton
'July 6', // Bush
'August 4', // Obama
'June 14', // Trump
];
const momentBirthdays = _.map(birthdays, (birthday) => {
return moment(birthday, 'MMMM D').startOf('day');
});
const linearAverage = () => {
const daysOfYear = _.map(momentBirthdays, (momentBirthday) => {
return momentBirthday.dayOfYear();
});
const averageDayOfYear = _.sum(daysOfYear) / _.size(daysOfYear);
return moment().startOf('day').dayOfYear(averageDayOfYear).format('MMMM Do');
};
const polarAverage = () => {
const vectors = _.map(momentBirthdays, (momentBirthday) => {
const angle = 2 * Math.PI * (momentBirthday.dayOfYear() / 365);
return [Math.cos(angle), Math.sin(angle)];
});
const sumOfCos = _.sumBy(vectors, (v) => { return v[0]; });
const sumOfSin = _.sumBy(vectors, (v) => { return v[1]; });
const averageAngle = Math.atan(sumOfSin / sumOfCos);
const averageDayOfYear = 365 * 24 * averageAngle / (2 * Math.PI);
return moment().startOf('year').add(averageDayOfYear, 'hours').format('MMMM Do');
};
console.log('linear average is ', linearAverage());
console.log(' polar average is ', polarAverage());
@tsheaff
Copy link
Author

tsheaff commented Feb 20, 2018

Results for me:

$ node presidential-birthdays.js
linear average is  July 4th
 polar average is  December 5th

@tsheaff
Copy link
Author

tsheaff commented Feb 20, 2018

@natesilver538 Did you use vector averaging method? How'd you arrive at November? 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment