Last Friday of each month: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Picat}}: Split into subsections.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 33:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
LASTFRI CSECT
USING LASTFRI,R13 base register
Line 111:
DW DS D packed (PL8) 15num
YREGS
END LASTFRI</
{{out}}
<pre>
Line 129:
=={{header|Action!}}==
<
BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752
BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
Line 193:
PrintB2(last) PutE()
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Last_Friday_of_each_month.png Screenshot from Atari 8-bit computer]
Line 216:
Uses GNAT. Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Find_last_sunday_of_each_month#Ada]].
<
Ada.Calendar.Formatting, Ada.Calendar.Arithmetic;
Line 245:
Put_Line(Selected);
end loop;
end Last_Weekday_In_Month;</
{{out}}
<pre>>./last_weekday_in_month friday 2012
Line 264:
Basically the same as the "Find the Last Sunday Of Each Month" task solution.
{{Trans|ALGOL W}}
<
# returns true if year is a leap year, false otherwise #
# assumes year is in the Gregorian Calendar #
Line 314:
)
OD
END</
{{out}}
<pre>
Line 333:
=={{header|ALGOL W}}==
Basically the same as the "Find the Last Sunday Of Each Month" task solution, uses the Day_of_week and isLeapYear procedures from the the day-of-the-week and leap-year tasks (included here for convenience).
<
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
Line 390:
for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) )
end
end.</
{{out}}
<pre>
Line 410:
{{Trans|JavaScript}}
<
-- lastFridaysOfYear :: Int -> [Date]
Line 605:
map(column, item 1 of xss)
end transpose</
{{Out}}
<pre>2014-01-31 2015-01-30 2016-01-29 2017-01-27 2018-01-26
Line 626:
AppleScript's weekday constants can be coerced either to English text or to the integers 1 (for Sunday) to 7 (Saturday).
<
-- Initialise an AppleScript date to the first day of some month in the specified year.
tell (current date) to set {firstDayOfNextMonth, its day, its year} to {it, 1, y}
Line 648:
end lastFridayOfEachMonthInYear
lastFridayOfEachMonthInYear(2020)</
{{Out}}
Line 667:
The above is of course hard-coded for Fridays. It can be made more flexible by taking an AppleScript weekday constant as a parameter:
<
-- Initialise an AppleScript date to the first day of some month in the specified year.
tell (current date) to set {firstDayOfNextMonth, its day, its year} to {it, 1, y}
Line 691:
end lastWeekdayWOfEachMonthInYear
lastWeekdayWOfEachMonthInYear(Friday, 2020)</
{{Out}}
<pre>"./last_Fridays 2020
Line 709:
=={{header|Arturo}}==
<
ensure -> in? m 1..12
Line 721:
loop 1..12 'month [
print to :string.format:"yyyy-MM-dd" lastFridayForMonth month
]</
{{out}}
Line 739:
=={{header|AutoHotkey}}==
<
{
InputBox, 1, Last Fridays of year, Enter a year:, , , , , , , , %A_YYYY%
Line 767:
stmp += 1, days
}
MsgBox % res</
{{out}} for 2012:
<pre>2012-01-27
Line 784:
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
#include <Date.au3>
Line 807:
ConsoleWrite($sResult)
EndFunc ;==>_GetFridays
</syntaxhighlight>
{{out}}
<pre>
Line 827:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f LAST_FRIDAY_OF_EACH_MONTH.AWK year
# converted from Fortran
Line 845:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 866:
The algorithm has been slightly simplified to avoid the additional day adjustment inside the loop, and the year is obtained from stdin rather than via the command line.
<
v2++1**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5<
>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v
^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6
>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8
^<# #"#"##"#"##!` +76:+1g00,+55,+*<</
{{out}}
Line 892:
Doesn't work with Julian calendar (then again, you probably don't need to plan your weekends for middle ages).
<
#include <stdlib.h>
Line 911:
return 0;
}</
=={{header|C sharp}}==
<
using System.Collections.Generic;
using System.Globalization;
Line 951:
}
}
}</
{{out}}
<pre>01/27/2012
Line 969:
{{libheader|Boost}}
called with <code>./last_fridays 2012</code>
<
#include <iostream>
#include <cstdlib>
Line 985:
}
return 0 ;
}</
{{out}}
<pre>2012-Jan-27
Line 1,004:
{{libheader|clj-time}}
<
'[clj-time.format :only [unparse formatters]])
Line 1,014:
(defn last-fridays-formatted [year]
(sort (map #(unparse (formatters :year-month-day) %) (last-fridays year))))</
{{out}}
Line 1,032:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
program-id. last-fri.
data division.
Line 1,081:
.
end program last-fri.
</syntaxhighlight>
{{out}}
Line 1,100:
=={{header|CoffeeScript}}==
<
last_friday_of_month = (year, month) ->
# month is 1-based, JS API is 0-based, then we use
Line 1,119:
year = parseInt process.argv[2]
print_last_fridays_of_month year
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
> coffee last_friday.coffee 2012
Fri Jan 27 2012
Line 1,135:
Fri Nov 30 2012
Fri Dec 28 2012
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 1,141:
The command-line argument processing is the only CLISP-specific code.
<
(let*
((timestamp (encode-universal-time 0 0 12 day month year))
Line 1,154:
(let* ((year (read-from-string (car *args*))))
(format t "~{~{~a-~2,'0d-~2,'0d~}~%~}" (last-fridays year)))</
Sample run for the year 2015:
Line 1,172:
=={{header|D}}==
<
void lastFridays(in uint year) {
Line 1,186:
void main() {
lastFridays(2012);
}</
<pre>2012-Jan-27
2012-Feb-24
Line 1,202:
=={{header|Delphi}}==
Uses the standard Delphi library.
<
{$APPTYPE CONSOLE}
Line 1,228:
WriteLn(DateToStr(D1));
end;
end.</
{{out}}
<pre>Enter year: 2019
Line 1,245:
=={{header|Elixir}}==
<
def lastFriday(year) do
Enum.map(1..12, fn month ->
Line 1,259:
Enum.each(RC.lastFriday(y), fn {year, month, day} ->
:io.format "~4b-~2..0w-~2..0w~n", [year, month, day]
end)</
{{out}}
Line 1,278:
=={{header|Elm}}==
<
import Html.App exposing (beginnerProgram)
import Html.Attributes exposing (placeholder, value, style)
Line 1,344:
, view = view
, update = update
}</
Link to live demo: http://dc25.github.io/lastFridayOfMonthElm/
Line 1,364:
=={{header|Emacs Lisp}}==
<
(defun last-friday (year)
Line 1,377:
(number-sequence 1 12)))
(last-friday 2012)</
{{output}}
<pre>2012-01-27
Line 1,393:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( last_date_each_month ).
Line 1,412:
Months_days = [{X, Y} || X <- Months, Y <- lists:seq(calendar:last_day_of_the_month(Year, X), calendar:last_day_of_the_month(Year, X) - 7, -1), calendar:valid_date(Year, X, Y), calendar:day_of_the_week(Year, X, Y) =:= Week_day],
[{Year, X, proplists:get_value(X, Months_days)} || X <- Months].
</syntaxhighlight>
{{out}}
<pre>
Line 1,433:
{{works with|Factor|0.98}}
The <code>last-friday-of-month</code> word in the <code>calendar</code> vocabulary does most of the work. This program expects the year as a command line argument.
<
IN: rosetta-code.last-fridays
(command-line) second string>number <year> 12 <iota>
[ months time+ last-friday-of-month ] with map
[ timestamp>ymd print ] each</
{{out}}
<pre>
Line 1,459:
Algorithm: compute day of week for last day of month, then subtract just enough to get to the preceding friday. Do this for each month. To simplify computations further, we only need to compute day of week of january 1st (the others are found by adding month lengths). Since day of week need only be known modulo 7, we do not compute modulo at all except once when subtracting.
<
implicit none
integer :: days(1:12) = (/31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31/)
Line 1,472:
end do
end program
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,559:
Loop
End</
{{out}}
<pre>For what year do you want to find the last Friday of the month
Line 1,579:
=={{header|Frink}}==
<
for m = 1 to 12
{
Line 1,585:
n = d - (((parseInt[d -> ### u ###] + 1) mod 7) + 1) days
println[n -> ### yyyy-MM-dd ###]
}</
{{out}}
Line 1,611:
=={{header|Gambas}}==
<
Dim siYear As Short = InputBox("Please input a year", "Last Friday of each month")
Dim siMonth, siDay As Short
Line 1,630:
Me.Close
End</
Output:
<pre>
Line 1,648:
=={{header|Go}}==
<
import (
Line 1,669:
fmt.Println(d.Format("2006-01-02"))
}
}</
{{out}}
<pre>
Line 1,691:
Test:
<
def lastFridays = lastWeekDays.curry(Day.Fri)
lastFridays(args[0] as int).each { println (ymd(it)) }</
Execution (Cygwin on Windows 7):
Line 1,713:
=={{header|Haskell}}==
<
(Day, addDays, showGregorian, fromGregorian, gregorianMonthLength)
import Data.Time.Calendar.WeekDate (toWeekDate)
Line 1,738:
mapM_
putStrLn
(intercalate " " <$> transpose (weekDayDates 5 <$> [2012 .. 2017]))</
{{Out}}
<pre>2012-01-27 2013-01-25 2014-01-31 2015-01-30 2016-01-29 2017-01-27
Line 1,755:
=={{header|Icon}} and {{header|Unicon}}==
This will write the last fridays for every year given as an argument. There is no error checking on the year.
<
every write(lastfridays(!A))
end
Line 1,774:
end
link datetime, printf</
{{libheader|Icon Programming Library}}
Line 1,797:
=={{header|J}}==
<
last_fridays=: 12 {. [: ({:/.~ }:"1)@(#~ 5 = weekday)@todate (i.366) + todayno@,&1 1</
In other words, start from January 1 of the given year, and count forward for 366 days, keeping the Fridays. Then pick the last remaining day within each represented month (which will be a Friday because we only kept the Fridays). Then pick the first 12 (since on a non-leap year which ends on a Thursday we would get an extra Friday).
Line 1,804:
Example use:
<
2012 1 27
2012 2 24
Line 1,816:
2012 10 26
2012 11 30
2012 12 28</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
import java.util.*;
Line 1,845:
}
}
}</
{{out}} (for <code>java LastFridays 2012</code>):
<pre>2012 Jan 27
Line 1,864:
====Iteration====
{{works with|Nodejs}}
<
last_friday_of_month = function(year, month) {
Line 1,891:
year = parseInt(process.argv[2]);
return print_last_fridays_of_month(year);
})();</
{{Out}}
<pre>>node lastfriday.js 2015
Line 1,908:
====Functional composition====
<
'use strict';
Line 1,978:
})
.join('\n');
})();</
{{Out}}
Line 1,995:
===ES6===
<
"use strict";
Line 2,074:
// MAIN ---
return main();
})();</
{{Out}}
<pre>2015-01-30 2016-01-29 2017-01-27 2018-01-26 2019-01-25
Line 2,092:
{{ works with|jq|1.4}}
'''Foundations'''
<
def until(cond; next):
Line 2,118:
| if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
else . % 7
end ;</
'''findLastFridays'''
<
def findLastFriday(year; month):
def isLeapYear:
Line 2,141:
(range(0;12) | "\(months[.]) \(findLastFriday($year; .+1))") ;
$year|tonumber|findLastFridays</
{{out}}
<
YEAR: 2012
January 27
Line 2,156:
October 26
November 30
December 28</
=={{header|Julia}}==
<
const wday = Dates.Fri
Line 2,184:
end
end
</
<pre>
This script will print the last Fridays of each month of the year given.
Line 2,211:
=={{header|K}}==
<syntaxhighlight lang="k">
/ List the dates of last Fridays of each month of
/ a given year
Line 2,225:
main: {[y]; lfd1[y];`0: ,"Dates of last Fridays of ",($y);12 10#arr}
</syntaxhighlight>
The output of a session is given below:
Line 2,251:
=={{header|Kotlin}}==
<
import java.util.*
Line 2,273:
}
}
}</
{{out}}
Line 2,294:
=={{header|Lasso}}==
<
#y % 400 == 0 ? return true
#y % 100 == 0 ? return false
Line 2,317:
with f in fridays(2012) do => {^
#f->format('%Q') + '\r'
^}</
{{out}}
Line 2,334:
=={{header|LiveCode}}==
<
-- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week.
convert the long date to dateitems
Line 2,356:
sort fridays ascending numeric
return fridays
end lastFriday</
Example<
2 24
3 30
Line 2,368:
10 26
11 30
12 28</
=={{header|Logo}}==
<
to leap? :year
output (and
Line 2,415:
print reduce [(word ?1 "- ?2)] (list :year :month :day)
]
bye</
{{out}}
Line 2,433:
=={{header|Lua}}==
<
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
Line 2,452:
end
lastWeekdays("Friday", tonumber(arg[1]))</
Command line session:
<pre>>lua lastFridays.lua 2012
Line 2,471:
=={{header|Maple}}==
<
local i, dt, change, last_days;
last_days := [31,28,31,30,31,30,31,31,30,31,30,31];
Line 2,488:
end proc;
fridays(2012);</
{{Out|Output}}
<pre>2012-1-27
Line 2,504:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
NestWhile[(DaysPlus[#, - 1]) &, #, (DateString[#, "DayName"] != "Friday") &] & /@
Most@Reverse@NestList [DaysPlus[# /. {x_, y_, X_} -> {x, y, 1}, - 1] &, {Y + 1, 1, 1}, 12]
Column@FridaysOfYear[2012]</
{{out}}
<pre>{2012,1,27}
Line 2,524:
=={{header|MATLAB}} / {{header|Octave}}==
<
t1 = datenum([y,1,1,0,0,0]);
t2 = datenum([y,12,31,0,0,0]);
Line 2,533:
datestr(last_fridays_of_year(2012),'yyyy-mm-dd')
</syntaxhighlight>
{{out}}
Line 2,551:
=={{header|Maxima}}==
<
if m < 3 then (m: m + 12, y: y - 1),
k: 1 + remainder(day + quotient((m + 1)*26, 10) + y + quotient(y, 4)
Line 2,570:
lastfridays(2012);
["2012-1-27", "2012-2-24", "2012-3-30", "2012-4-27", "2012-5-25", "2012-6-29",
"2012-7-27","2012-8-31", "2012-9-28", "2012-10-26", "2012-11-30", "2012-12-28"]</
=={{header|Nanoquery}}==
<
// a function to check if a year is a leap year
Line 2,623:
print form(friday.getMonth()) + "-"
println form(friday.getDay())
end</
=={{header|NetRexx}}==
Line 2,629:
{{trans|C}}
Implements the algorithms from both the [[#Java|Java]] and [[#C|C]] implementations.
<
options replace format comments java crossref symbols nobinary
Line 2,705:
end
return
</syntaxhighlight>
{{out}}
<pre>
Line 2,740:
=={{header|Nim}}==
<
const
Line 2,753:
var date = initDateTime(lastDay, month, year, 0, 0, 0)
date = date - days(DayDiffs[date.weekday])
echo date.format("yyyy-MM-dd")</
{{out}}
Line 2,775:
Using the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html Unix] from the standard OCaml library:
<
open Unix
Line 2,810:
done;
done;
Array.iter print_date fridays</
{{out}}
Line 2,830:
{{libheader|OCaml Calendar Library}}
<
let usage() =
Line 2,854:
aux num_days
done;
List.iter print_date (List.rev !fridays)</
Run this script with the command:
Line 2,862:
=={{header|Oforth}}==
<
: lastFridays(y)
Line 2,870:
while(dup dayOfWeek Date.FRIDAY <>) [ addDays(-1) ]
println
] ;</
{{out}}
Line 2,890:
=={{header|PARI/GP}}==
<
njd(D) =
{
Line 2,916:
}
for (m=1, 12, a=njd([2012,m+1,0]); print(njdate(a-(a+1)%7)))</
Output:<pre>
Line 2,935:
{{works with|Free Pascal}}
Using Free Pascal's DateUtils library would dramatically simplify the coding (see the Delphi example) but for older Pascal implementations the needed routines are the programmer's responsibility.
<syntaxhighlight lang="pascal">
program LastFriday;
Line 3,021:
end;
end.
</syntaxhighlight>
{{out}}
<pre>
Line 3,041:
=={{header|Perl}}==
<
use strict ;
use DateTime ;
Line 3,052:
}
say $dt->ymd ;
}</
{{out}}
<pre>2012-01-27
Line 3,069:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">last_day_of_month</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dow</span><span style="color: #0000FF;">)</span>
Line 3,082:
--last_day_of_month(prompt_number("Year:",{1752,9999}),FRIDAY)</span>
<span style="color: #000000;">last_day_of_month</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2012</span><span style="color: #0000FF;">,</span><span style="color: #000000;">FRIDAY</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 3,102:
PHP is generally used for web apps, so I am not implementing the command-line component of this task.
<
function last_friday_of_month($year, $month) {
$day = 0;
Line 3,123:
$year = 2012;
print_last_fridays_of_month($year);
?></
{{out}}
Line 3,142:
=={{header|Picat}}==
<
main(ARGV) =>
if ARGV.length > 0 then
Line 3,200:
(Year mod 4 == 0, Year mod 100 != 0)
;
Year mod 400 == 0. </
===Running the program===
Line 3,233:
=={{header|PicoLisp}}==
<
(for M 12
(prinl
Line 3,239:
(find '((D) (= "Friday" (day D)))
(mapcar '((D) (date Y M D)) `(range 31 22)) )
"-" ) ) ) )</
Test:
<
2012-01-27
2012-02-24
Line 3,253:
2012-10-26
2012-11-30
2012-12-28</
=={{header|Pike}}==
<
{
return day->week_day() == 5 &&
Line 3,267:
write("%{%s\n%}", days->format_ymd());
return 0;
}</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
Fridays: procedure (year) options (main); /* 8 January 2013 */
declare year character (4) varying;
Line 3,293:
end;
end Fridays;
</syntaxhighlight>
The command: FRIDAYS /2008 produces:
<pre>
Line 3,328:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function last-dayofweek {
param(
Line 3,342:
}
last-dayofweek 2012 "Friday"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 3,362:
This script finds the first and/or last or all dates of any of the days of week; accepts <code>[Int32]</code> and <code>[DateTime]</code> values for Month and Year parameters; outputs <code>[DateTime]</code> objects by default but has an option to output time strings in various formats. This script also allows for pipeline input based mainly upon the Month parameter.
This script has a syntax as complex as any PowerShell Cmdlet because it attempts to do everything.
<syntaxhighlight lang="powershell">
function Get-Date0fDayOfWeek
{
Line 3,460:
}
}
</syntaxhighlight>
The default is to return <code>[DateTime]</code> objects:
<syntaxhighlight lang="powershell">
1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday
</syntaxhighlight>
{{Out}}
<pre>
Line 3,481:
</pre>
Return the <code>[DateTime]</code> objects as strings (using the default string format):
<syntaxhighlight lang="powershell">
1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday -AsString
</syntaxhighlight>
{{Out}}
<pre>
Line 3,500:
</pre>
Return the <code>[DateTime]</code> objects as strings (specifying the string format):
<syntaxhighlight lang="powershell">
1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday -AsString -Format yyyy-MM-dd
</syntaxhighlight>
{{Out}}
<pre>
Line 3,520:
=={{header|PureBasic}}==
<
Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1
NewList d.i()
Line 3,553:
EndIf
Print("...End")
Input()</
{{out}}
<pre>Input Year [ 1971 < y < 2038 ]: 2017
Line 3,572:
=={{header|Python}}==
<
def last_fridays(year):
Line 3,578:
last_friday = max(week[calendar.FRIDAY]
for week in calendar.monthcalendar(year, month))
print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))</
{{out}}
Line 3,595:
2012-12-28</pre>
Another solution
<
c=calendar.Calendar()
fridays={}
Line 3,609:
for item in sorted((month+"-"+day for month,day in fridays.items()),
key=lambda x:int(x.split("-")[1])):
print item</
Using reduce
<
c=calendar.Calendar()
fridays={}
Line 3,626:
for item in sorted((month+"-"+day for month,day in fridays.items()),
key=lambda x:int(x.split("-")[1])):
print item</
using itertools
<
from itertools import chain
f=chain.from_iterable
Line 3,646:
for item in sorted((month+"-"+day for month,day in fridays.items()),
key=lambda x:int(x.split("-")[1])):
print item</
=={{header|Quackery}}==
<
dup 4 / over +
over 100 / -
Line 3,697:
[ 5 lastwkdays ] is lastfridays ( year --> )
2012 lastfridays</
{{out}}
Line 3,715:
=={{header|R}}==
<
d = as.Date(paste0(year, "-01-01"))
fridays = d + seq(by = 7,
Line 3,721:
364 + (months(d + 30 + 29) == "February"))
message(paste(collapse = "\n", fridays[tapply(
seq_along(fridays), as.POSIXlt(fridays)$mon, max)]))</
=={{header|Racket}}==
<
#lang racket
(require srfi/19 math)
Line 3,766:
(for ([d (last-fridays 2012)])
(displayln (~a (date->string d "~a ~d ~b ~Y"))))
</syntaxhighlight>
{{out}}
<pre>
Line 3,785:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my @fri;
for Date.new("$year-01-01") .. Date.new("$year-12-31") {
Line 3,791:
}
.say for @fri[1..12];
}</
Example:
Line 3,810:
A solution without a result array to store things in:
<syntaxhighlight lang="raku"
say ~.value.reverse.first: *.day-of-week == 5
for classify *.month, Date.new("$year-01-01") .. Date.new("$year-12-31");
}</
Here, <code>classify</code> sorts the dates into one bin per month (but preserves the order in each bin). We then take the list inside each bin (<code>.value</code>) and find the last (<code>.reverse.first</code>) date which is a Friday.
Line 3,819:
Another variation where the data flow can be read left to right using feed operators:
<syntaxhighlight lang="raku"
.say for Date.new("$year-01-01") .. Date.new("$year-12-31") ==> classify *.month ==>
map *.value.reverse.first: *.day-of-week == 5
}</
=={{header|REBOL}}==
The longer version:
<
days-in-feb: function [year] [either leap-year? year [29] [28]]
Line 3,848:
year: to-integer input
repeat month 12 [print last-friday-of-month month year]
</syntaxhighlight>
{{out}}
<pre>rebol last-fridays.reb <<< 2012
Line 3,865:
</pre>
A shorter version:
<
collect [
repeat month 12 [
Line 3,877:
foreach friday last-fridays-of-year to-integer input [print friday]
</syntaxhighlight>
NB. See "Find the last Sunday of each month" Rosetta for alternative (even more succinct) solution
Line 3,910:
║ last day─of─week is then obtained straightforwardly, or via subtraction. ║
╚════════════════════════════════════════════════════════════════════════════════════════════════╝
<
parse arg yyyy /*obtain optional argument from the CL.*/
do j=1 for 12 /*traipse through all the year's months*/
Line 3,959:
.er: arg ,_; say; say '***error*** (in LASTDOW)'; say /*tell error, and */
say word('day-of-week month year excess', arg(2)) arg(1) a._ /*plug in a choice.*/
say; exit 13 /*··· then exit. */</
{{out|output|text= when using the following input of: <tt> 2012 </tt> or <tt> 12 </tt>}}
<pre>
Line 3,977:
=={{header|Ring}}==
<
see "What year to calculate (yyyy) : "
give year
Line 3,999:
next
</syntaxhighlight>
Output:
<pre>
Line 4,019:
=={{header|Ruby}}==
<
def last_friday(year, month)
Line 4,028:
year = Integer(ARGV.shift)
(1..12).each {|month| puts last_friday(year, month)}</
Friday is <code>d.wday == 5</code>; the expression <code>(d.wday - 5) % 7</code> counts days after Friday.
Line 4,048:
Or get the last day of the month and go to the previous day until it's a Friday.
<
def last_friday(year, month)
Line 4,055:
d
end
</syntaxhighlight>
=={{header|Run BASIC}}==
<
dayOne$ = "01-01-";yr
n1 = date$(dayOne$)
Line 4,072:
wend
print date$(n1) ' print last Friday's date
next i</
<pre>Year:?2013
01/25/2013
Line 4,088:
=={{header|Rust}}==
<
use time::{Date, Duration};
Line 4,101:
println!("{}", date - days_back);
});
}</
{{out}}
Line 4,120:
=={{header|Scala}}==
<
import java.text.SimpleDateFormat
Line 4,143:
}
}
}</
{{out}}
<pre>2012-Jan-27
Line 4,163:
Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Find_last_sunday_of_each_month#Seed7]].
<
include "time.s7i";
include "duration.s7i";
Line 4,192:
end for;
end if;
end func;</
{{out}} when called with <tt>s7 rosetta/lastWeekdayInMonth 5 2013</tt>:
Line 4,211:
=={{header|SenseTalk}}==
<
ask "What year?"
put it into year
Line 4,229:
add a month to lastDayOfMonth -- advance to last day of next month
end repeat
</syntaxhighlight>
{{out}}
<pre>
Line 4,249:
=={{header|Sidef}}==
{{trans|Perl}}
<
var (year=2016) = ARGV.map{.to_i}...
Line 4,258:
}
say dt.ymd
}</
{{out}}
<pre>
Line 4,278:
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">
Pharo Smalltalk
Line 4,288:
thenSelect: [ :each |
(((Date daysInMonth: each monthIndex forYear: yr) - each dayOfMonth) <= 6) and: [ each year = yr ] ] ]
</syntaxhighlight>
{{out}}
<pre>
Line 4,296:
=={{header|SQL}}==
<syntaxhighlight lang="sql">
select to_char( next_day( last_day( add_months( to_date(
:yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday
from dual
connect by level <= 12;
</syntaxhighlight>
<pre>
LASTFRIDAY
Line 4,322:
=={{header|Stata}}==
<
args year
clear
Line 4,348:
| 30nov2012 |
| 28dec2012 |
+-----------+</
=={{header|Swift}}==
<syntaxhighlight lang="swift">
import Foundation
Line 4,400:
print(lastFridays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))
</syntaxhighlight>
<pre>
1/27/12
Line 4,417:
=={{header|Tcl}}==
<
set year [lindex $argv 0]
foreach dm {02/1 03/1 04/1 05/1 06/1 07/1 08/1 09/1 10/1 11/1 12/1 12/32} {
Line 4,424:
# Print the interesting part
puts [clock format $t -format "%Y-%m-%d" -gmt 1]
}</
Sample execution:
<pre>
Line 4,443:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
year=2012
Line 4,455:
ENDLOOP
ENDLOOP
</syntaxhighlight>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 4,474:
=={{header|UNIX Shell}}==
Using <code>ncal</code>. Will switch to Julian calender as ncal sees fit, and will not calculate past year 9999 (chances are you'll be too dead by then to worry about weekends anyway).
<
if [ -z $1 ]; then exit 1; fi
Line 4,482:
for m in 01 02 03 04 05 06 07 08 09 10 11 12; do
echo $1-$m-`ncal $m $1 | grep Fr | sed 's/.* \([0-9]\)/\1/'`
done</
For systems without ncal:
<
# usage: last_fridays [ year]
Line 4,502:
# Strip leading zeros to avoid octal interpretation
month=$(( 1 + ${month#0} ))
done</
Using <code>date --date</code> from GNU date??? This code is not portable.
<
# Free code, no limit work
Line 4,576:
# main
last_fridays ${1:-2012}</
Sample execution:
Line 4,596:
=={{header|Visual FoxPro}}==
<
*!* OOP implementaion
LOCAL lnYear As Integer, oCalc As fricalc
Line 4,631:
ENDDEFINE
</syntaxhighlight>
=={{header|Vlang}}==
<
import os
Line 4,663:
}
}
}</
{{out}}
<pre>Please select a year: 2012
Line 4,684:
=={{header|Wren}}==
{{libheader|Wren-date}}
<
import "/date" for Date
Line 4,706:
System.print(dt.addDays(-wd - 2))
}
}</
{{out}}
Line 4,742:
=={{header|XPL0}}==
<
func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat)
Line 4,764:
IntOut(0, LastDay); CrLf(0);
];
]</
{{out}}
Line 4,784:
=={{header|zkl}}==
Gregorian calendar
<
fcn lastDay(y,d){
[1..12].pump(List,'wrap(m){ // 12 months, closure for y & d
Line 4,793:
})
}
lastDay(2012,D.Friday).concat("\n").println();</
For each month in year y, count back from the last day in the month
until a Friday is found and print that date.
|