Task

Write a program or a script that returns the date of the last Fridays of each month of a given year.

The year may be given through any simple input method in your language (command line, std in, etc).



Example of an expected output:

./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28



Related tasks
 Five weekends
 Day of the week
 Find the last Sunday of each month


/* NetRexx */
options replace format comments java crossref symbols nobinary
 
import java.text.
 
runSample(arg)
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method lastFridayByLib(year) public static
 
  cal = GregorianCalendar(year, 0, 1)
 
  loop mon over DateFormatSymbols().getShortMonths()
    if \mon.isEmpty() then do
      totalDaysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
      cal.set(Calendar.DAY_OF_MONTH, totalDaysOfMonth)
 
      daysToRollBack = (cal.get(Calendar.DAY_OF_WEEK) + 1) // 7
 
      day = totalDaysOfMonth - daysToRollBack
      cal.set(Calendar.DAY_OF_MONTH, day)
 
      say year.right(4, 0) mon day.right(2, 0)
 
      cal.set(year, cal.get(Calendar.MONTH) + 1, 1)
      end
    end mon
  return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method lastFridayCalc(year) public static binary signals BadArgumentException
 
  if year <= 1700 then do
    signal BadArgumentException(year 'is out of range')
    end
 
  wk  = int
  mth = int
  yr  = int year
  days = [int 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  -- days in month
  days[1] = days[1] - ((yr // 4) | \(yr // 100) & (yr // 400)) -- adjust for leap year
 
  wk = yr * 365 + (yr - 1) % 4 - (yr - 1) % 100 + (yr - 1) % 400 + 6 -- week number
 
  loop mth = 0 to 11
    wk = (wk + days[mth]) // 7
    wx = int
    if wk < 5 then wx = -2
              else wx = 5
    yy = Rexx(yr)
    mm = Rexx(mth + 1)
    dd = Rexx(days[mth] + wx - wk)
    say yy.right(4, 0)'-'mm.right(2, 0)'-'dd.right(2, 0)
    end mth
  return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  do
    parse arg year .
    if year = '' | year = '.' then year = 2012
    dlm = '-'
    dlm = dlm.left(60, dlm)
    say
    say 'Using Java calendar libraries'
    say dlm
    lastFridayByLib(year)
    say
    say 'Calculated'
    say dlm
    lastFridayCalc(year)
  catch ex = Exception
    ex.printStackTrace
  end
  return
 