Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>/* * Computes and returns the next year in which New Year's Day will * fall on the same day of the week as in a given year. */ public int newYears(int year) { // First, find out what day of the week it falls on in year X Calendar calendar = new GregorianCalendar(); // create a calendar object calendar.set(year, 0, 1); // calendar.set([year], January, 1st) int day = calendar.get(Calendar.DAY_OF_WEEK); // store this value for later // The code between the curly braces below will be executed 30 times, // the first time i = 1, the second i = 2, third i = 3, etc... for(int i = 1; true; i++) { calendar.set(year + i, 0, 1); // set the calendar to the next year if(calendar.get(Calendar.DAY_OF_WEEK) == day) // compare to the value we stored earlier, and if it's the same day... { return year + i; // we have the correct year! } } } </code></pre> <p><strong>EDIT</strong></p> <p>Okay I'm going overboard here but I must follow the calling of my inner geek.</p> <p>I took a for loop and looped through and ran a bunch of sequential years through the function, subtracted to find the difference, and got this table:</p> <pre><code> in | out | difference 2004 2009 5 2005 2011 6 2006 2012 6 2007 2018 11 2008 2013 5 2009 2015 6 2010 2016 6 2011 2022 11 2012 2017 5 2013 2019 6 2014 2020 6 2015 2026 11 </code></pre> <p>There's a very clear pattern that repeats every four years (because of leap year I suppose). Using this, we can write a sneaky/condensed version of this function:</p> <pre><code>public int sneakyNewYears(int year) { int diff = year % 4; int add = -1; if(diff == 0) add = 5; if(diff == 1) add = 6; if(diff == 2) add = 6; if(diff == 3) add = 11; return year + add; } </code></pre> <p>This works fine for 98.6% percent of years, but testing this 'sneaky' function against the working function shows that there are a few years that this doesn't work for, for some odd reason... These years: 1575, 1577, 1578, 1579, 1580, 1581, 1582, 1691, 1695, 1696, 1697, 1698, 1699, 1700, 1791, 1795, 1796, 1797, 1798, 1799, 1800, 1891, 1895, 1896, 1897, 1898, 1899 and 1900.</p> <p>Anyway.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload