Five weekends: Difference between revisions

Added Easylang
(+Stata)
(Added Easylang)
 
(40 intermediate revisions by 22 users not shown)
Line 30:
For maximum compatibility, this program uses only the basic instruction set (S/360)
and two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Five weekends 31/05/2016
FIVEWEEK CSECT
USING FIVEWEEK,R13 base register
Line 129:
XDEC DS CL12 temp for XDECO
YREGS
END FIVEWEEK</langsyntaxhighlight>
{{out}}
<pre>
Line 151:
201 occurrences
29 years with no five weekend month
</pre>
 
=={{header|Action!}}==
Day of the week is determined using [https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods Sakamoto] method.
<syntaxhighlight lang="action!">;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
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]
BYTE res
 
IF m<3 THEN
y==-1
FI
res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7
RETURN (res)
 
PROC Main()
BYTE ARRAY m31=[1 3 5 7 8 10 12]
INT ARRAY years(250)
BYTE ARRAY months(250)
INT y
BYTE i,m,mCount,yCount,found,c
 
mCount=0 yCount=0 c=0
FOR y=1900 TO 2100
DO
found=0
FOR i=0 TO 6
DO
m=m31(i)
IF DayOfWeek(y,m,1)=5 THEN
years(mCount)=y
months(mCount)=m
found=1
mCount==+1
FI
OD
IF found=0 THEN
yCount==+1
FI
OD
Print("5-weekend months in 1900-2100: ") PrintBE(mCount)
Print("non 5-weekend years in 1900-2100: ") PrintBE(yCount)
PutE()
 
FOR i=0 TO 4
DO
PrintI(years(i)) Put('/) PrintBE(months(i))
OD
PrintE("...")
FOR i=mCount-5 TO mCount-1
DO
PrintI(years(i)) Put('/) PrintBE(months(i))
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Five_weekends.png Screenshot from Atari 8-bit computer]
<pre>
5-weekend months in 1900-2100: 201
non 5-weekend years in 1900-2100: 29
 
1901/3
1902/8
1903/5
1904/1
1904/7
...
2097/3
2098/8
2099/5
2100/1
2100/10
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar.Formatting; use Ada.Calendar;
Line 178 ⟶ 249:
Put_Line ("Number of months:" & Integer'Image (Months));
end Five_Weekends;
</syntaxhighlight>
</lang>
{{out|Sample output}}
<pre style="height:30ex;overflow:scroll">
Line 383 ⟶ 454:
2100 10
Number of months: 201
</pre>
 
=={{header|ALGOL 68}}==
{{trans|Fortran|Note: This specimen retains the original [[#Fortran|Fortran]] coding style. [http://rosettacode.org/mw/index.php?title=Five_weekends&action=historysubmit&diff=107850&oldid=107848 diff]}}
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<syntaxhighlight lang="algol68">five_weekends: BEGIN
INT m, year, nfives := 0, not5 := 0;
BOOL no5weekend;
MODE MONTH = STRUCT(
INT n,
[3]CHAR name
) # MODE MONTH #;
[]MONTH month = (
MONTH(13, "Jan"),
MONTH(3, "Mar"),
MONTH(5, "May"),
MONTH(7, "Jul"),
MONTH(8, "Aug"),
MONTH(10, "Oct"),
MONTH(12, "Dec")
);
FOR year FROM 1900 TO 2100 DO
IF year = 1905 THEN printf($"..."l$) FI;
no5weekend := TRUE;
FOR m TO UPB month DO
IF n OF month(m) = 13 THEN
IF day_of_week(1, n OF month(m), year-1) = 6 THEN
IF year<1905 OR year > 2096 THEN printf(($g, 5zl$, name OF month(m), year)) FI;
nfives +:= 1;
no5weekend := FALSE
FI
ELSE
IF day_of_week(1, n OF month(m), year) = 6 THEN
IF year<1905 OR year > 2096 THEN printf(($g, 5zl$, name OF month(m), year)) FI;
nfives +:= 1;
no5weekend := FALSE
FI
FI
OD;
IF no5weekend THEN not5 +:= 1 FI
OD;
printf(($g, g(0)l$, "Number of months with five weekends between 1900 and 2100 = ", nfives));
printf(($g, g(0)l$, "Number of years between 1900 and 2100 with no five weekend months = ", not5));
# contains #
PROC day_of_week = (INT d, m, y)INT: BEGIN
INT j, k;
j := y OVER 100;
k := y MOD 100;
(d + (m+1)*26 OVER 10 + k + k OVER 4 + j OVER 4 + 5*j) MOD 7
END # function day_of_week #;
SKIP
END # program five_weekends #</syntaxhighlight>
{{out}}
<pre>
Mar 1901
Aug 1902
May 1903
Jan 1904
Jul 1904
...
Mar 2097
Aug 2098
May 2099
Jan 2100
Oct 2100
Number of months with five weekends between 1900 and 2100 = 201
Number of years between 1900 and 2100 with no five weekend months = 29
</pre>
 
=={{header|Amazing Hopper}}==
<p>VERSION 1</p>
<syntaxhighlight lang="txt">
#include <jambo.h>
 
#context Obtiene suma de días de weekend
Args ( Domingo, Viernes, Sábado )
Not zero( Val( [3:end,Domingo] Of 'calendario' )), Get summatory
Not zero( Val( [3:end,Viernes] Of 'calendario' )), Get summatory, Add it
Not zero( Val( [3:end,Sábado ] Of 'calendario' )), Get summatory, Add it
Return\\
 
#define __PRNNL__ {"\n"}print
#synon __PRNNL__ *Print it
#defn Paralosdías(*) #GENCODE $$$*$$$ #ATCMLIST; #ENDGEN;
#enum 1,DOMINGO,6,VIERNES,7,SABADO
 
Main
Set stack 15
 
Init zero (calendario, candidato, total, columna)
/* Configura meses */
Meses={}, mes largo = {}
Let list ( Meses := "Enero ","Febrero ","Marzo ","Abril ","Mayo ",\
"Junio ","Julio ","Agosto ","Septiembre","Octubre ",\
"Noviembre ","Diciembre " )
Let list ( mes largo := 1, 3, 5, 7, 8, 10, 12 )
/* Busca los meses con weekend larguísimo */
Loop for (año = 1900, #( año <= 2100), ++año)
Loop for( i=1, #(i<=7), ++i)
Let ( calendario := Calendar( [i] Of 'mes largo' ---Backup to 'candidato'---,año,1) )
 
Para los días 'DOMINGO, VIERNES, SABADO' Obtiene suma de días de weekend
When ( Is equal to '15' ){
++total, Print (año," : ", [candidato] Of 'Meses'," | ")
When ( columna++ Is equal to '3' ) { Prnl, columna=0 }
}
Back
Back
Set ( Utf8("\nTotal de años con weekend de 5 días = "), total ), and Print it
End
 
Subrutines
</syntaxhighlight>
{{out}}
<pre>
1901 : Marzo | 1902 : Agosto | 1903 : Mayo | 1904 : Enero |
1904 : Julio | 1905 : Diciembre | 1907 : Marzo | 1908 : Mayo |
1909 : Enero | 1909 : Octubre | 1910 : Julio | 1911 : Diciembre |
1912 : Marzo | 1913 : Agosto | 1914 : Mayo | 1915 : Enero |
1915 : Octubre | 1916 : Diciembre | 1918 : Marzo | 1919 : Agosto |
1920 : Octubre | 1921 : Julio | 1922 : Diciembre | 1924 : Agosto |
1925 : Mayo | 1926 : Enero | 1926 : Octubre | 1927 : Julio |
1929 : Marzo | 1930 : Agosto | 1931 : Mayo | 1932 : Enero |
1932 : Julio | 1933 : Diciembre | 1935 : Marzo | 1936 : Mayo |
1937 : Enero | 1937 : Octubre | 1938 : Julio | 1939 : Diciembre |
1940 : Marzo | 1941 : Agosto | 1942 : Mayo | 1943 : Enero |
1943 : Octubre | 1944 : Diciembre | 1946 : Marzo | 1947 : Agosto |
1948 : Octubre | 1949 : Julio | 1950 : Diciembre | 1952 : Agosto |
1953 : Mayo | 1954 : Enero | 1954 : Octubre | 1955 : Julio |
1957 : Marzo | 1958 : Agosto | 1959 : Mayo | 1960 : Enero |
1960 : Julio | 1961 : Diciembre | 1963 : Marzo | 1964 : Mayo |
1965 : Enero | 1965 : Octubre | 1966 : Julio | 1967 : Diciembre |
1968 : Marzo | 1969 : Agosto | 1970 : Mayo | 1971 : Enero |
1971 : Octubre | 1972 : Diciembre | 1974 : Marzo | 1975 : Agosto |
1976 : Octubre | 1977 : Julio | 1978 : Diciembre | 1980 : Agosto |
1981 : Mayo | 1982 : Enero | 1982 : Octubre | 1983 : Julio |
1985 : Marzo | 1986 : Agosto | 1987 : Mayo | 1988 : Enero |
1988 : Julio | 1989 : Diciembre | 1991 : Marzo | 1992 : Mayo |
1993 : Enero | 1993 : Octubre | 1994 : Julio | 1995 : Diciembre |
1996 : Marzo | 1997 : Agosto | 1998 : Mayo | 1999 : Enero |
1999 : Octubre | 2000 : Diciembre | 2002 : Marzo | 2003 : Agosto |
2004 : Octubre | 2005 : Julio | 2006 : Diciembre | 2008 : Agosto |
2009 : Mayo | 2010 : Enero | 2010 : Octubre | 2011 : Julio |
2013 : Marzo | 2014 : Agosto | 2015 : Mayo | 2016 : Enero |
2016 : Julio | 2017 : Diciembre | 2019 : Marzo | 2020 : Mayo |
2021 : Enero | 2021 : Octubre | 2022 : Julio | 2023 : Diciembre |
2024 : Marzo | 2025 : Agosto | 2026 : Mayo | 2027 : Enero |
2027 : Octubre | 2028 : Diciembre | 2030 : Marzo | 2031 : Agosto |
2032 : Octubre | 2033 : Julio | 2034 : Diciembre | 2036 : Agosto |
2037 : Mayo | 2038 : Enero | 2038 : Octubre | 2039 : Julio |
2041 : Marzo | 2042 : Agosto | 2043 : Mayo | 2044 : Enero |
2044 : Julio | 2045 : Diciembre | 2047 : Marzo | 2048 : Mayo |
2049 : Enero | 2049 : Octubre | 2050 : Julio | 2051 : Diciembre |
2052 : Marzo | 2053 : Agosto | 2054 : Mayo | 2055 : Enero |
2055 : Octubre | 2056 : Diciembre | 2058 : Marzo | 2059 : Agosto |
2060 : Octubre | 2061 : Julio | 2062 : Diciembre | 2064 : Agosto |
2065 : Mayo | 2066 : Enero | 2066 : Octubre | 2067 : Julio |
2069 : Marzo | 2070 : Agosto | 2071 : Mayo | 2072 : Enero |
2072 : Julio | 2073 : Diciembre | 2075 : Marzo | 2076 : Mayo |
2077 : Enero | 2077 : Octubre | 2078 : Julio | 2079 : Diciembre |
2080 : Marzo | 2081 : Agosto | 2082 : Mayo | 2083 : Enero |
2083 : Octubre | 2084 : Diciembre | 2086 : Marzo | 2087 : Agosto |
2088 : Octubre | 2089 : Julio | 2090 : Diciembre | 2092 : Agosto |
2093 : Mayo | 2094 : Enero | 2094 : Octubre | 2095 : Julio |
2097 : Marzo | 2098 : Agosto | 2099 : Mayo | 2100 : Enero |
2100 : Octubre |
Total de años con weekend de 5 días = 201
</pre>
<p>VERSION 2</p>
<p>Esta versión genera el mismo resultado, sin hacer uso de la macro "calendar", con la diferencia que ahora le añadí el conteo de los días que no tienen el famoso "five weekend":</p>
<syntaxhighlight lang="txt">
#include <jambo.h>
 
#define __PRNNL__ {"\n"}print
#synon __PRNNL__ *Print it
#synon Set *Set
 
Main
Set stack 15
 
Init zero (candidato, total, sin weekend largo, sw, columna, fecha)
/* Configura meses */
mes largo = {}
Let list ( mes largo := 1, 3, 5, 7, 8, 10, 12 )
/* Busca los meses con weekend larguísimo */
Loop for (año = 1900, #( año <= 2100), ++año)
Loop for( i=1, #(i<=7), ++i)
 
Let ( candidato := [i] Of 'mes largo' )
Let ( fecha := Multicat ("1/",Str(candidato),"/",Str(año)) )
 
When ( Strday 'fecha' Is equal to '"Viernes"', \
And ( Days of month 'fecha' Compared to '31', Are equals? )) {
++total, sw=1
Print (año," : ", Just left (13, Month name 'candidato')," | ")
When ( columna++ Is equal to '3' ) { Prnl, columna=0 }
}
Back
When ( Not( sw ) ) { ++ sin weekend largo }, sw=0
Back
now Set ( Utf8("\nTotal de años con weekend de 5 días = "), total )
and Set ( Utf8("\nAños sin weekend de 5 días: "), sin weekend largo) then Print it
End
</syntaxhighlight>
{{out}}
<pre>
1901 : Marzo | 1902 : Agosto | 1903 : Mayo | 1904 : Enero |
1904 : Julio | 1905 : Diciembre | 1907 : Marzo | 1908 : Mayo |
...
2093 : Mayo | 2094 : Enero | 2094 : Octubre | 2095 : Julio |
2097 : Marzo | 2098 : Agosto | 2099 : Mayo | 2100 : Enero |
2100 : Octubre |
Total de años con weekend de 5 días = 201
Años sin weekend de 5 días: 29
 
</pre>
 
Line 389 ⟶ 690:
===Imperative===
 
<langsyntaxhighlight AppleScriptlang="applescript">set fiveWeekendMonths to {}
set noFiveWeekendYears to {}
 
Line 436 ⟶ 737:
set y to y + 12
end
resultText</langsyntaxhighlight>
 
{{out}} (can always add "display dialog resultText" for GUI output):
Line 449 ⟶ 750:
 
===Functional===
<langsyntaxhighlight AppleScriptlang="applescript">-- TEST -----------------------------------------------------------------------
on run
Line 621 ⟶ 922:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{|number|:201},
{firstFive:{"1901 March", "1902 August", "1903 May", "1904 January", "1904 July"}},
{lastFive:{"2097 March", "2098 August", "2099 May", "2100 January", "2100 October"}},
Line 629 ⟶ 930:
{leanYears:{1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962, 1973, 1979,
1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035, 2040, 2046, 2057, 2063, 2068, 2074,
2085, 2091, 2096}}}</langsyntaxhighlight>
 
===Using integer math===
An alternative to the date object manipulation methods above.
<syntaxhighlight lang="applescript">on monthsWithFiveWeekends(startYear, endYear)
set Dec1 to (current date)
tell Dec1 to set {its day, its month, its year} to {1, December, startYear - 1}
set daysFromBaseFriday to (Dec1's weekday as integer) - Friday
set longMonths to {"January", "March", "May", "July", "August", "October", "December"}
set daysBetween to {31, 59, 61, 61, 31, 61, 61} -- Days since starts of preceding long months.
set hits to {}
set hitlessYears to {}
repeat with y from startYear to endYear
set noHIts to true
-- Find long months that begin on Fridays.
repeat with i from 1 to 7
set daysFromBaseFriday to daysFromBaseFriday + (daysBetween's item i)
if ((i = 2) and (y mod 4 = 0) and ((y mod 100 > 0) or (y mod 400 = 0))) then ¬
set daysFromBaseFriday to daysFromBaseFriday + 1 -- Leap year.
if (daysFromBaseFriday mod 7 = 0) then
set end of hits to (longMonths's item i) & (space & y)
set noHIts to false
end if
end repeat
if (noHIts) then set end of hitlessYears to y
end repeat
return {hits:hits, hitlessYears:hitlessYears}
end monthsWithFiveWeekends
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on task()
set {startYear, endYear} to {1900, 2100}
set theResults to monthsWithFiveWeekends(startYear, endYear)
set output to {((count theResults's hits) as text) & " of the months from " & startYear & ¬
" to " & endYear & " have five weekends,", ¬
"the first and last five of these months being:"}
set end of output to join(theResults's hits's items 1 thru 5, ", ") & " …"
set end of output to "… " & join(theResults's hits's items -5 thru -1, ", ")
set hitlessCount to (count theResults's hitlessYears)
set end of output to linefeed & hitlessCount & " of the years have no such months:"
set cut to (hitlessCount + 1) div 2
set end of output to join(theResults's hitlessYears's items 1 thru cut, ", ")
set end of output to join(theResults's hitlessYears's items (cut + 1) thru -1, ", ")
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"201 of the months from 1900 to 2100 have five weekends,
the first and last five of these months being:
March 1901, August 1902, May 1903, January 1904, July 1904 …
… March 2097, August 2098, May 2099, January 2100, October 2100
 
29 of the years have no such months:
1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962, 1973, 1979, 1984, 1990, 2001
2007, 2012, 2018, 2029, 2035, 2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096"</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">longMonths: [1 3 5 7 8 10 12]
dates: []
 
yearsWithout: 0
 
loop 1900..2100 'year [
found?: false
loop longMonths 'month [
dt: to :date .format:"d-M-YYYY" ~"1-|month|-|year|"
if friday? dt [
'dates ++ @[@[dt\Month year]]
found?: true
]
]
if not? found? ->
inc 'yearsWithout
]
 
print.lines map first.n:5 dates 'd -> ~"|to :string d\0|, |to :string d\1|"
print "..."
print.lines map last.n:5 dates 'd -> ~"|to :string d\0|, |to :string d\1|"
 
print ""
print ["Found" size dates "months in total."]
print ["There are" yearsWithout "years without any month that has 5 full weekends."]</syntaxhighlight>
 
{{out}}
 
<pre>March, 1901
August, 1902
May, 1903
January, 1904
July, 1904
...
March, 2097
August, 2098
May, 2099
January, 2100
October, 2100
 
Found 201 months in total.
There are 29 years without any month that has 5 full weekends.</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Year := 1900
End_Year := 2100
31_Day_Months = 01,03,05,07,08,10,12
Line 668 ⟶ 1,077:
Years with no 5 day weekends between 1900 and 2100 : %No_5_Weekend_Count%
%All_Years_Without_5_Weekend%
)</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Line 675 ⟶ 1,084:
2 - Years Without 5 Weekend Months
3 - Year and Month with 5 Weekends
<syntaxhighlight lang="autoit">
<lang AutoIt>
#include <Date.au3>
#include <Array.au3>
Line 717 ⟶ 1,126:
EndIf
EndFunc ;==>Five_weekends
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
{{trans|Fortran|Note: This specimen retains the original [[#Fortran|Fortran]] coding style. [http://rosettacode.org/mw/index.php?title=Five_weekends&action=historysubmit&diff=107850&oldid=107848 diff]}}
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<lang algol68>five_weekends: BEGIN
INT m, year, nfives := 0, not5 := 0;
BOOL no5weekend;
MODE MONTH = STRUCT(
INT n,
[3]CHAR name
) # MODE MONTH #;
[]MONTH month = (
MONTH(13, "Jan"),
MONTH(3, "Mar"),
MONTH(5, "May"),
MONTH(7, "Jul"),
MONTH(8, "Aug"),
MONTH(10, "Oct"),
MONTH(12, "Dec")
);
FOR year FROM 1900 TO 2100 DO
IF year = 1905 THEN printf($"..."l$) FI;
no5weekend := TRUE;
FOR m TO UPB month DO
IF n OF month(m) = 13 THEN
IF day_of_week(1, n OF month(m), year-1) = 6 THEN
IF year<1905 OR year > 2096 THEN printf(($g, 5zl$, name OF month(m), year)) FI;
nfives +:= 1;
no5weekend := FALSE
FI
ELSE
IF day_of_week(1, n OF month(m), year) = 6 THEN
IF year<1905 OR year > 2096 THEN printf(($g, 5zl$, name OF month(m), year)) FI;
nfives +:= 1;
no5weekend := FALSE
FI
FI
OD;
IF no5weekend THEN not5 +:= 1 FI
OD;
printf(($g, g(0)l$, "Number of months with five weekends between 1900 and 2100 = ", nfives));
printf(($g, g(0)l$, "Number of years between 1900 and 2100 with no five weekend months = ", not5));
# contains #
PROC day_of_week = (INT d, m, y)INT: BEGIN
INT j, k;
j := y OVER 100;
k := y MOD 100;
(d + (m+1)*26 OVER 10 + k + k OVER 4 + j OVER 4 + 5*j) MOD 7
END # function day_of_week #;
SKIP
END # program five_weekends #</lang>
{{out}}
<pre>
Mar 1901
Aug 1902
May 1903
Jan 1904
Jul 1904
...
Mar 2097
Aug 2098
May 2099
Jan 2100
Oct 2100
Number of months with five weekends between 1900 and 2100 = 201
Number of years between 1900 and 2100 with no five weekend months = 29
</pre>
 
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">
# usage: awk -f 5weekends.awk cal.txt
 
Line 853 ⟶ 1,187:
print(bY)
}
</syntaxhighlight>
</lang>
 
See also: [http://rosettacode.org/wiki/Five_weekends#UNIX_Shell unix-shell] and [http://rosettacode.org/wiki/Calendar#AWK Calendar].
Line 882 ⟶ 1,216:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"DATELIB"
DIM Month$(12)
Month$() = "","January","February","March","April","May","June", \
Line 899 ⟶ 1,233:
IF num% = oldnum% PRINT "(none)" ELSE PRINT
NEXT year%
PRINT "Total = " ; num%</langsyntaxhighlight>
{{out}}
<pre>
Line 922 ⟶ 1,256:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <time.h>
 
Line 951 ⟶ 1,285:
printf("%d total\n", n);
return 0;
}</langsyntaxhighlight>
{{out}} (note that the C library may not be able to handle all dates; the output may vary across systems):
<pre>
Line 983 ⟶ 1,317:
 
Not your typical method. Requires <code>ncal</code>.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 1,022 ⟶ 1,356:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,032 ⟶ 1,366:
Total: 201
</pre>
 
=={{header|C sharp|C#}}==
===With iteration===
<syntaxhighlight lang="csharp">using System;
 
namespace _5_Weekends
{
class Program
{
const int FIRST_YEAR = 1900;
const int LAST_YEAR = 2100;
static int[] _31_MONTHS = { 1, 3, 5, 7, 8, 10, 12 };
 
static void Main(string[] args)
{
int totalNum = 0;
int totalNo5Weekends = 0;
 
for (int year = FIRST_YEAR; year <= LAST_YEAR; year++)
{
bool has5Weekends = false;
 
foreach (int month in _31_MONTHS)
{
DateTime firstDay = new DateTime(year, month, 1);
if (firstDay.DayOfWeek == DayOfWeek.Friday)
{
totalNum++;
has5Weekends = true;
Console.WriteLine(firstDay.ToString("yyyy - MMMM"));
}
}
 
if (!has5Weekends) totalNo5Weekends++;
}
Console.WriteLine("Total 5-weekend months between {0} and {1}: {2}", FIRST_YEAR, LAST_YEAR, totalNum);
Console.WriteLine("Total number of years with no 5-weekend months {0}", totalNo5Weekends);
}
}
}</syntaxhighlight>
{{out}}
<pre>
1901 - March
1902 - August
1903 - May
1904 - January
1904 - July
1905 - December
...
2095 - July
2097 - March
2098 - August
2099 - May
2100 - January
2100 - October
Total 5-weekend months between 1900 and 2100: 201
Total number of years with no 5-weekend months 29
</pre>
 
===With LINQ===
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
 
public class Program
{
public static void Main()
{
const int startYear = 1900, endYear = 2100;
var query = (
from year in startYear.To(endYear)
from month in 1.To(12)
where DateTime.DaysInMonth(year, month) == 31
select new DateTime(year, month, 1) into date
where date.DayOfWeek == DayOfWeek.Friday
select date)
.ToList();
Console.WriteLine("Count: " + query.Count);
Console.WriteLine();
Console.WriteLine("First and last 5:");
for (int i = 0; i < 5; i++)
Console.WriteLine(query[i].ToString("MMMM yyyy"));
Console.WriteLine("...");
for (int i = query.Count - 5; i < query.Count; i++)
Console.WriteLine(query[i].ToString("MMMM yyyy"));
Console.WriteLine();
Console.WriteLine("Years without 5 weekends:");
Console.WriteLine(string.Join(" ", startYear.To(endYear).Except(query.Select(dt => dt.Year))));
}
}
 
public static class IntExtensions
{
public static IEnumerable<int> To(this int start, int end) => Enumerable.Range(start, end - start + 1);
}</syntaxhighlight>
{{out}}
<pre>
Count: 201
 
First and last 5:
March 1901
August 1902
May 1903
January 1904
July 1904
...
March 2097
August 2098
May 2099
January 2100
October 2100
 
Years without 5 weekends:
1900 1906 1917 1923 1928 1934 1945 1951 1956 1962 1973 1979 1984 1990 2001 2007 2012 2018 2029 2035 2040 2046 2057 2063 2068 2074 2085 2091 2096</pre>
 
=={{header|C++}}==
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <vector>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <algorithm>
Line 1,077 ⟶ 1,527:
std::cout << std::endl ;
return 0 ;
}</langsyntaxhighlight>
{{out|Sample output}}
<pre style="height:30ex;overflow:scroll">
Line 1,316 ⟶ 1,766:
</pre>
 
=={{header|C=Using sharp|C#}}++20===
<syntaxhighlight lang="c++">
===With iteration===
<lang csharp>using System;
 
#include <chrono>
namespace _5_Weekends
#include <iostream>
{
#include <vector>
class Program
{
const int FIRST_YEAR = 1900;
const int LAST_YEAR = 2100;
static int[] _31_MONTHS = { 1, 3, 5, 7, 8, 10, 12 };
 
int main() {
static void Main(string[] args)
const std::vector<std::chrono::month> long_months = { std::chrono::January, std::chrono::March,
{
std::chrono::May, std::chrono::July, std::chrono::August, std::chrono::October, std::chrono::December };
int totalNum = 0;
int totalNo5Weekends = 0;
 
int month_count = 0;
for (int year = FIRST_YEAR; year <= LAST_YEAR; year++)
int blank_years = 0;
{
for ( int y = 1900; y <= 2100; ++y ) {
bool has5Weekends = false;
bool blank_year = true;
 
for ( std::chrono::month m : long_months ) {
foreach (int month in _31_MONTHS)
std::chrono::year_month_day first_of_month{std::chrono::year{y}, m, std::chrono::day{1}};
{
if ( std::chrono::weekday{first_of_month} == std::chrono::Friday ) {
DateTime firstDay = new DateTime(year, month, 1);
std::cout << first_of_month.year() << " " << first_of_month.month() << std::endl;
if (firstDay.DayOfWeek == DayOfWeek.Friday)
month_count++;
{
blank_year = false;
totalNum++;
}
has5Weekends = true;
}
Console.WriteLine(firstDay.ToString("yyyy - MMMM"));
if ( blank_year ) {
}
blank_years++;
}
}
 
}
if (!has5Weekends) totalNo5Weekends++;
std::cout << "Found " << month_count << " months with five Fridays, Saturdays and Sundays." << std::endl;
}
std::cout << "There were " << blank_years << " years with no such months." << std::endl;
Console.WriteLine("Total 5-weekend months between {0} and {1}: {2}", FIRST_YEAR, LAST_YEAR, totalNum);
}
Console.WriteLine("Total number of years with no 5-weekend months {0}", totalNo5Weekends);
</syntaxhighlight>
}
{{ out }}
}</lang>
{{out}}
<pre>
1901 - MarchMar
1902 - AugustAug
1903 - May
1904 - JanuaryJan
1904 - JulyJul
// elided... //
1905 - December
2097 Mar
...
2098 Aug
2095 - July
2099 May
2097 - March
2100 Jan
2098 - August
2100 Oct
2099 - May
Found 201 months with five Fridays, Saturdays and Sundays.
2100 - January
There were 29 years with no such months.
2100 - October
Total 5-weekend months between 1900 and 2100: 201
Total number of years with no 5-weekend months 29
</pre>
 
===With LINQ===
<lang csharp>using System;
using System.Linq;
using System.Collections.Generic;
 
public class Program
{
public static void Main()
{
const int startYear = 1900, endYear = 2100;
var query = (
from year in startYear.To(endYear)
from month in 1.To(12)
where DateTime.DaysInMonth(year, month) == 31
select new DateTime(year, month, 1) into date
where date.DayOfWeek == DayOfWeek.Friday
select date)
.ToList();
Console.WriteLine("Count: " + query.Count);
Console.WriteLine();
Console.WriteLine("First and last 5:");
for (int i = 0; i < 5; i++)
Console.WriteLine(query[i].ToString("MMMM yyyy"));
Console.WriteLine("...");
for (int i = query.Count - 5; i < query.Count; i++)
Console.WriteLine(query[i].ToString("MMMM yyyy"));
Console.WriteLine();
Console.WriteLine("Years without 5 weekends:");
Console.WriteLine(string.Join(" ", startYear.To(endYear).Except(query.Select(dt => dt.Year))));
}
}
 
public static class IntExtensions
{
public static IEnumerable<int> To(this int start, int end) => Enumerable.Range(start, end - start + 1);
}</lang>
{{out}}
<pre>
Count: 201
 
First and last 5:
March 1901
August 1902
May 1903
January 1904
July 1904
...
March 2097
August 2098
May 2099
January 2100
October 2100
 
Years without 5 weekends:
1900 1906 1917 1923 1928 1934 1945 1951 1956 1962 1973 1979 1984 1990 2001 2007 2012 2018 2029 2035 2040 2046 2057 2063 2068 2074 2085 2091 2096</pre>
 
=={{header|Ceylon}}==
<b>module.ceylon</b>
<langsyntaxhighlight lang="ceylon">
module rosetta.fiveweekends "1.0.0" {
import ceylon.time "1.2.2";
}
</syntaxhighlight>
</lang>
<b>run.ceylon</b>
<langsyntaxhighlight lang="ceylon">
import ceylon.time {
date,
Line 1,497 ⟶ 1,879:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,533 ⟶ 1,915:
 
</pre>
 
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(import java.util.GregorianCalendar
java.text.DateFormatSymbols)
 
Line 1,546 ⟶ 1,927:
(println month "-" year))
count
(println "Total Months: " ,))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. five-we.
data division.
Line 1,603 ⟶ 1,984:
.
end program five-we.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,622 ⟶ 2,003:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
startsOnFriday = (month, year) ->
# 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
Line 1,664 ⟶ 2,045:
fiveWeekends()
 
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
1901 2
1902 7
Line 1,697 ⟶ 2,078:
 
Years with no five-weekend months: 29
</syntaxhighlight>
</lang>
 
 
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">;; Given a date, get the day of the week. Adapted from
;; http://lispcookbook.github.io/cl-cookbook/dates_and_times.html
 
Line 1,748 ⟶ 2,127:
(format t "Last 5 months: ~A~%" (subseq good-months 0 5))
(format t "Years without a five-weekend month: ~A~%" bad-years))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,757 ⟶ 2,136:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.datetime, std.algorithm, std.range;
 
Date[] m5w(in Date start, in Date end) pure /*nothrow*/ {
Line 1,787 ⟶ 2,166:
writefln("\nThere are %d years in the range that do not have " ~
"months with five weekends.", n);
}</langsyntaxhighlight>
{{out}}
<pre>There are 201 months of which the first and last five are:
Line 1,803 ⟶ 2,182:
There are 29 years in the range that do not have months with five weekends.</pre>
===Simpler Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.datetime, std.traits;
 
Line 1,837 ⟶ 2,216:
writeln("\nTotal number of years with no 5-weekend months: ",
totalNo5Weekends);
}</langsyntaxhighlight>
{{out}}
<pre>Total 5-weekend months between 1900 and 2100: 201
Line 1,853 ⟶ 2,232:
 
Total number of years with no 5-weekend months: 29</pre>
 
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">
main() {
var total = 0;
var empty = <int>[];
for (var year = 1900; year < 2101; year++) {
var months =
[1, 3, 5, 7, 8, 10, 12].where((m) => DateTime(year, m, 1).weekday == 5);
print('$year\t$months');
total += months.length;
if (months.isEmpty) empty.add(year);
}
print('Total: $total');
print('Year with none: $empty');
}
</syntaxhighlight>
{{out|Sample output}}
<pre style="height:30ex;overflow:scroll">
1900 ()
1901 (3)
1902 (8)
1903 (5)
1904 (1, 7)
...
2098 (8)
2099 (5)
2100 (1, 10)
Total: 201
Year with none: [1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962, 1973, 1979, 1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035, 2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096]
</pre>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program FiveWeekends;
 
{$APPTYPE CONSOLE}
Line 1,888 ⟶ 2,299:
Writeln(Format('Months with 5 weekends: %d', [lFiveWeekendCount]));
Writeln(Format('Years with no 5 weekend months: %d', [lYearsWithout]));
end.</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func leap year .
return if year mod 4 = 0 and (year mod 100 <> 0 or year mod 400 = 0)
.
func weekday year month day .
normdoom[] = [ 3 7 7 4 2 6 4 1 5 3 7 5 ]
c = year div 100
r = year mod 100
s = r div 12
t = r mod 12
c_anchor = (5 * (c mod 4) + 2) mod 7
doom = (s + t + (t div 4) + c_anchor) mod 7
anchor = normdoom[month]
if leap year = 1 and month <= 2
anchor = (anchor + 1) mod1 7
.
return (doom + day - anchor + 7) mod 7 + 1
.
mdays[] = [ 31 28 31 30 31 30 31 31 30 31 30 31 ]
mon$[] = [ "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" ]
#
for year = 1900 to 2100
for m to 12
if mdays[m] = 31 and weekday year m 1 = 6
print year & "-" & mon$[m]
sum += 1
.
.
.
print "Total : " & sum
</syntaxhighlight>
{{out}}
<pre>
1901-Mar
1902-Aug
1903-May
1904-Jan
1904-Jul
.
.
2097-Mar
2098-Aug
2099-May
2100-Jan
2100-Oct
Total : 201
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Date do
@months { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" }
Line 1,908 ⟶ 2,368:
IO.puts "Found #{count} month with 5 weekends."
IO.puts "\nFound #{length(none)} years with no month having 5 weekends:"
IO.puts "#{inspect Enum.map(none, fn {y,_}-> y end)}"</langsyntaxhighlight>
 
{{out}}
Line 1,932 ⟶ 2,392:
Two examples, both based on first building a nested list-of-lists like [Year1, Year2, ..., YearN], where each year is a sublist of year and month tuples, like [{YearN, 1}, {YearN, 2}, ..., {YearN, 12}].<br>
First, a pretty compact example intended for use with <b>escript</b>:
<langsyntaxhighlight lang="erlang">
#!/usr/bin/env escript
%%
Line 1,962 ⟶ 2,422:
has_five({_Year, _Month}, _DaysNot31) ->
false.
</syntaxhighlight>
</lang>
Second, a more verbose Erlang module:
<langsyntaxhighlight lang="erlang">
-module(five_weekends).
 
Line 2,016 ⟶ 2,476:
find_years_without_5w_months(List) ->
[Y || {[{Y,_M}|_], 0} <- List].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,064 ⟶ 2,524:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FIVE_WEEKENDS
 
Line 2,101 ⟶ 2,561:
PRINT("Total =";CNT%)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,123 ⟶ 2,583:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
<lang Euphoria>
--Five Weekend task from Rosetta Code wiki
--User:Lnettnay
Line 2,166 ⟶ 2,626:
puts(1, "Number of years that have no months with five full weekends = ")
? none
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,185 ⟶ 2,645:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
[<EntryPoint>]
Line 2,218 ⟶ 2,678:
(List.take 5 allMonthsWith5we)
(List.take 5 (List.skip ((List.length allMonthsWith5we) - 5) allMonthsWith5we))
0</langsyntaxhighlight>
{{out}}
<pre>201 months in the range of years from 1900 to 2100 have 5 weekends.
29 years in the range of years from 1900 to 2100 have no month with 5 weekends.
Months with 5 weekends: [(1901, [3]); (1902, [8]); (1903, [5]); (1904, [1; 7]); (1905, [12])] ... [(2095, [7]); (2097, [3]); (2098, [8]); (2099, [5]); (2100, [1; 10])]</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: calendar calendar.format formatting io kernel math
sequences ;
 
: timestamps>my ( months -- )
[ { MONTH bl YYYY nl } formatted 2drop ] each ;
 
: month-range ( start-year #months -- seq )
[ <year> ] [ <iota> ] bi* [ months time+ ] with map ;
: find-five-weekend-months ( months -- months' )
[ [ friday? ] [ days-in-month ] bi 31 = and ] filter ;
1900 12 201 * month-range find-five-weekend-months
[ length "%d five-weekend months found.\n" printf ]
[ 5 head timestamps>my "..." print ]
[ 5 tail* timestamps>my ] tri</syntaxhighlight>
{{out}}
<pre>
201 five-weekend months found.
Mar 1901
Aug 1902
May 1903
Jan 1904
Jul 1904
...
Mar 2097
Aug 2098
May 2099
Jan 2100
Oct 2100
</pre>
 
=={{header|Fortran}}==
Line 2,228 ⟶ 2,721:
 
Using Zeller's congruence
<langsyntaxhighlight lang="fortran">program Five_weekends
implicit none
 
Line 2,284 ⟶ 2,777:
end function Day_of_week
end program Five_weekends</langsyntaxhighlight>
{{out}}
<pre>Mar 1901
Line 2,299 ⟶ 2,792:
Number of months with five weekends between 1900 and 2100 = 201
Number of years between 1900 and 2100 with no five weekend months = 29</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBASIClang="freebasic">' version 23-06-2015
' compile with: fbc -s console
 
Line 2,360 ⟶ 2,854:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>1901 | March
Line 2,384 ⟶ 2,878:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=fbeb1b7a06fff3da3f8b262ee5d71390 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim aMonth As Short[] = [1, 3, 5, 7, 8, 10, 12] 'All 31 day months
Dim aMMStore As New String[] 'To store results
Line 2,421 ⟶ 2,915:
" years that do not have at least one five-weekend month" 'Print the amount of years with no 5 weekend months
Print aMMStore.Join(",") 'Print the years with no 5 weekend months
End</langsyntaxhighlight>
Output:
<pre>
Line 2,443 ⟶ 2,937:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># return a list of two lists :
# first is the list of months with five weekends between years y1 and y2 (included)
# second is the list of years without such months, in the same interval
Line 2,475 ⟶ 2,969:
# [ "Mar-1901", "Aug-1902", "May-1903", "Jan-1904", "Jul-1904" ]
r[1]{[n-4 .. n]};
# [ "Mar-2097", "Aug-2098", "May-2099", "Jan-2100", "Oct-2100" ]</langsyntaxhighlight>
 
=={{header|Go}}==
Using second algorithm suggestion:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,527 ⟶ 3,022:
}
fmt.Println(len(haveNone), "total")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,571 ⟶ 3,066:
29 total
</pre>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">enum Day {
Sun, Mon, Tue, Wed, Thu, Fri, Sat
static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) }
Line 2,589 ⟶ 3,085:
}
}.flatten()
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def ym = { it.format('yyyy-MM') }
def years = 1900..2100
def fiveWeekendMonths = fiveWeekends(years)
println "Number of five weekend months: ${fiveWeekendMonths.size()}"
fiveWeekendMonths.each { println (ym(it)) }</langsyntaxhighlight>
 
{{out}}
Line 2,805 ⟶ 3,301:
 
Test:
<langsyntaxhighlight lang="groovy">def yearsWith = fiveWeekendMonths.collect { it.format('yyyy') as int } as Set
def yearsWithout = (years as Set) - yearsWith
println "\nNumber of years without a five weekend month: ${yearsWithout.size()}"
yearsWithout.each { println it }</langsyntaxhighlight>
 
{{out}}
Line 2,841 ⟶ 3,337:
2091
2096</pre>
 
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="visualfoxpro">
PROCEDURE Main()
LOCAL y, m, d, nFound, cNames, nTot := 0, nNotFives := 0
Line 2,878 ⟶ 3,373:
? "Years with no five weekends months: " + hb_NtoS( nNotFives )
 
RETURN</langsyntaxhighlight>
 
{{out}}
Line 2,913 ⟶ 3,408:
 
Now it is easy to get all months with 31 days that start on Friday.
<langsyntaxhighlight Haskelllang="haskell">import Data.List (intercalate)
 
data DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday |
Line 3,016 ⟶ 3,511:
formatMonth :: (Year, [Month]) -> String
formatMonth (y, m) = show y ++ ": " ++ intercalate ", " [ show x | x <- m ]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,042 ⟶ 3,537:
 
====Using Data.Time====
<syntaxhighlight lang ="haskell">import Data.TimeList (Day, fromGregorian, gregorianMonthLengthintercalate)
import Data.Time.Calendar.WeekDate (toWeekDate)
import Data.List.Split (chunksOf)
import Data.ListTime (intercalateDay, fromGregorian, gregorianMonthLength)
import Data.Time.Calendar.WeekDate (toWeekDate)
 
---------------- MONTHS WITH FIVE WEEKENDS ---------------
 
-- MONTHS WITH FIVE WEEKENDS --------------------------------------------------
fiveFridayMonths :: Integer -> [(Integer, Int)]
fiveFridayMonths y =
[1 .. 12] >>=
>>= \m ->
[ (y, m)
| isFriday (fromGregorian y m 1) ,
, gregorianMonthLength y m 31 == 31gregorianMonthLength ]y m
]
 
isFriday :: Day -> Bool
isFriday d = 5 == day
where
let (_, _, day) = toWeekDate d
in (_, _, day) == 5toWeekDate d
 
-- TEST ---------------------------------------------- TEST -------------------------
main :: IO ()
main = do
Line 3,070 ⟶ 3,565:
lean =
concat $
zipWith
(\months year -> [year | null months])
[ yearxs
| null months ])years
xs
years
n = (length . concat) xs
(putStrLn . intercalate "\n\n")
[ "How many five-weekend months 1900-2100 ?",
, '\t' : show n,
, "First five ?",
, '\t' : show (concat (take 5 xs)),
, "Last five ?",
, '\t' : show (concat (drop (n - 5) xs)),
, "How many lean years ? (No five-weekend months)",
, '\t' : show (length lean),
, "Which years are lean ?",
unlines $
, unlines (('\t' :) <$> fmap (unwords . fmap show) (chunksOf 5 lean))
('\t' :) . unwords . fmap show
]</lang>
<$> chunksOf 5 lean
]</syntaxhighlight>
{{Out}}
<pre>How many five-weekend months 1900-2100 ?
Line 3,114 ⟶ 3,609:
2040 2046 2057 2063 2068
2074 2085 2091 2096</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">link datetime,printf
 
procedure main(A) # five weekends
printf( "There are %d months from %d to %d with five full weekends.\n",
*(L := fiveweekends(s := 1900, f := 2100)), s,f)
printf("The first and last five such months are:\n")
every printf("%s\n",L[1 to 5]|"..."|L[-4 to 0])
printf( "There are %d years without such months as follows:\n",
*(M := Bonus(s,f,L)))
every printf("%s\n",!M)
end
 
procedure fiveweekends(start,finish)
L := [] # months years with five weekends FRI-SUN
every year := start to finish & month := 1 to 12 do
if month = (2|4|6|9|11) then next
else if julian(month,1,year) % 7 = 4 then
put(L,sprintf("%d-%d-1",year,month))
return L
end
 
procedure Bonus(start,finish,fwe)
every insert(Y := set(), start to finish)
every insert(F := set(), integer(!fwe ? tab(find("-"))))
return sort(Y--F)
end</syntaxhighlight>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides formatting]
[http://www.cs.arizona.edu/icon/library/src/procs/datetime.icn datetime.icn provides julian]
 
{{out}}
<pre>There are 201 months from 1900 to 2100 with five full weekends.
The first and last five such months are:
1901-3-1
1902-8-1
1903-5-1
1904-1-1
1904-7-1
...
2098-8-1
2099-5-1
2100-1-1
2100-10-1
There are 29 years without such months as follows:
1900
1906
1917
1923
1928
1934
1945
1951
1956
1962
1973
1979
1984
1990
2001
2007
2012
2018
2029
2035
2040
2046
2057
2063
2068
2074
2085
2091
2096</pre>
 
=={{header|Inform 7}}==
Inform 7 has no built-in date functions, so this solution implements date types and a day-of-week function.
 
<langsyntaxhighlight lang="inform7">Calendar is a room.
 
When play begins:
Line 3,219 ⟶ 3,790:
repeat with M running through months:
if M of Y is a happy month, decide no;
decide yes.</langsyntaxhighlight>
 
{{out}}
Line 3,234 ⟶ 3,805:
October 2100.
Found 201 months with five weekends and 29 years with no such months.</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>link datetime,printf
 
procedure main(A) # five weekends
printf( "There are %d months from %d to %d with five full weekends.\n",
*(L := fiveweekends(s := 1900, f := 2100)), s,f)
printf("The first and last five such months are:\n")
every printf("%s\n",L[1 to 5]|"..."|L[-4 to 0])
printf( "There are %d years without such months as follows:\n",
*(M := Bonus(s,f,L)))
every printf("%s\n",!M)
end
 
procedure fiveweekends(start,finish)
L := [] # months years with five weekends FRI-SUN
every year := start to finish & month := 1 to 12 do
if month = (2|4|6|9|11) then next
else if julian(month,1,year) % 7 = 4 then
put(L,sprintf("%d-%d-1",year,month))
return L
end
 
procedure Bonus(start,finish,fwe)
every insert(Y := set(), start to finish)
every insert(F := set(), integer(!fwe ? tab(find("-"))))
return sort(Y--F)
end</lang>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides formatting]
[http://www.cs.arizona.edu/icon/library/src/procs/datetime.icn datetime.icn provides julian]
 
{{out}}
<pre>There are 201 months from 1900 to 2100 with five full weekends.
The first and last five such months are:
1901-3-1
1902-8-1
1903-5-1
1904-1-1
1904-7-1
...
2098-8-1
2099-5-1
2100-1-1
2100-10-1
There are 29 years without such months as follows:
1900
1906
1917
1923
1928
1934
1945
1951
1956
1962
1973
1979
1984
1990
2001
2007
2012
2018
2029
2035
2040
2046
2057
2063
2068
2074
2085
2091
2096</pre>
 
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'types/datetime numeric'
find5wkdMonths=: verb define
years=. range 2{. y
Line 3,319 ⟶ 3,813:
m5w=. (#~ 0 = weekday) >,{years;months;31 NB. 5 full weekends iff 31st is Sunday(0)
>'MMM YYYY' fmtDate toDayNo m5w
)</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> # find5wkdMonths 1900 2100 NB. number of months found
201
(5&{. , '...' , _5&{.) find5wkdMonths 1900 2100 NB. First and last 5 months found
Line 3,336 ⟶ 3,830:
Oct 2100
# (range -. {:"1@(_ ". find5wkdMonths)) 1900 2100 NB. number of years without 5 weekend months
29</langsyntaxhighlight>
 
=={{header|Java}}==
In Java 1.5+ you can add <code>import static java.util.Calendar.*;</code> to the list of imports and remove all other occurrences of <code>Calendar.</code> from the rest of the code (e.g. <code>Calendar.FRIDAY</code> would simply become <code>FRIDAY</code>). It's more portable (and probably more clear) to leave the <code>Calendar.</code>'s in.
<langsyntaxhighlight lang="java">import java.util.Calendar;
import java.util.GregorianCalendar;
 
Line 3,371 ⟶ 3,865:
}
}
}</langsyntaxhighlight>
{{out}} (middle results cut out):
<pre style="height:30ex;overflow:scroll"> There are 201 months with five weekends from 1900 through 2100:
Line 3,428 ⟶ 3,922:
2091
2096</pre>
 
 
=={{header|JavaScript}}==
===ES5===
====Imperative====
<langsyntaxhighlight lang="javascript">function startsOnFriday(month, year)
{
// 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
Line 3,477 ⟶ 3,970:
document.write('Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '<br>');
}
fiveWeekends();</langsyntaxhighlight>
 
{{out|Sample output}}
Line 3,498 ⟶ 3,991:
 
Here is an alternative solution that uses the offset between the first day of every month, generating the same solution but without relying on the Date object.
<langsyntaxhighlight lang="javascript">var Months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'
Line 3,558 ⟶ 4,051:
 
console.log('Number of months that have five full weekends from 1900 to 2100: ' + total);
console.log('Number of years without any five full weekend months: ' + without);</langsyntaxhighlight>
{{out}}
<pre>1901-Mar
Line 3,575 ⟶ 4,068:
 
====Functional====
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 3,628 ⟶ 4,121:
null, 2
);
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 3,650 ⟶ 4,143:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
// longMonthsStartingFriday :: Int -> [Int]
const longMonthsStartingFriday = y =>
Line 3,709 ⟶ 4,202:
leanYearCount: lstLeanYears.length
});
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 3,734 ⟶ 4,227:
 
'''Foundations: Zeller's Congruence'''
<langsyntaxhighlight lang="jq"> Use Zeller's Congruence to determine the day of the week, given
# year, month and day as integers in the conventional way.
# Emit 0 for Saturday, 1 for Sunday, etc.
Line 3,748 ⟶ 4,241:
+ (.[1]/400|floor) - 2*(.[1]/100|floor)
| . % 7
;</langsyntaxhighlight>
'''Nuts and Bolts''':
<langsyntaxhighlight lang="jq">def weekday_of_last_day_of_month(year; month):
def day_before(day): (6+day) % 7;
 
Line 3,774 ⟶ 4,267:
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][.-1];
"\(.[1] | month) \(.[0])"
;</langsyntaxhighlight>
'''The Task''':
<langsyntaxhighlight lang="jq">five_weekends(1900;2101)
| "There are \(length) months with 5 weekends from 1900 to 2100 inclusive;",
"the first and last five are as follows:",
Line 3,782 ⟶ 4,275:
"...",
( .[length-5: ][] | pp),
"In this period, there are \( [range(1900;2101)] - map( .[0] ) | length ) years which have no five-weekend months."</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f Five_Weekends.jq
There are 201 months with 5 weekends from 1900 to 2100 inclusive;
the first and last five are as follows:
Line 3,798 ⟶ 4,291:
Jan 2100
Oct 2100
In this period, there are 29 years which have no five-weekend months.</langsyntaxhighlight>
 
=={{header|Julia}}==
<lang{{works with|Julia>|0.6}}
isdefined(:Date) || using Dates
 
<syntaxhighlight lang="julia">isweekend(dt::Date) = Dates.dayofweek(dt) ∈ (Dates.Friday, Dates.Saturday, Dates.Sunday)
const wday = Dates.Fri
const lo = 1900
const hi = 2100
const showres = 5
 
function hasfiveweekend(month::Integer, year::Integer)
mfive = recur(Date(lo, 1):Month(1):Date(hi, 12)) do m
dmin = Date(year, month, 1)
Dates.daysinmonth(m) == 31 && Dates.dayofweek(m) == wday
dmax = dmin + Dates.Day(Dates.daysinmonth(dmin) - 1)
return count(isweekend, dmin:dmax) ≥ 15
end
 
months = collect((y, m) for y in 1900:2100, m in 1:12 if hasfiveweekend(m, y))
println("Considering the years from ", lo, " to ", hi, ".\n")
println("There are ", length(mfive), " months having 5 3-day weekends.")
 
println("TheNumber firstof ",months showres,with "5 suchfull-weekends: $(length(months are:))")
println("First five such months:")
for m in mfive[1:showres]
for (y, m) in months[1:5] println(" - $y-$m", Dates.monthname(m), " ", Dates.year(m))end
println("Last five such months:")
end
for (y, m) in months[end-4:end] println(" - $y-$m") end
 
# extra credit
println("\nThe last ", showres, " such months are:")
yrs = getindex.(months, 1)
for m in mfive[end-showres+1:end]
nyrs = 2100 - 1899 - length(unique(yrs))
println(" ", Dates.monthname(m), " ", Dates.year(m))
end
 
println("Number of year with not one 5-full-weekend month: $nyrs")</syntaxhighlight>
print("\nThere are ", length(filter(y -> !(y in year(mfive)), lo:hi)))
println(" years that have no such months.")
</lang>
 
This code uses the <code>Dates</code> module, which is being incorporated into Julian's standard library with the current development version (<tt>0.4</tt>). I've used <code>isdefined</code> to make this code good for the current stable version (<tt>0.3</tt>) as well as for future releases. If <code>Dates</code> is not installed on your instance of Julian try <code>Pkg.add("Dates")</code> from the <tt>REPL</tt>.
 
{{out}}
<pre>Number of months with 5 full-weekends: 201
<pre>
First five such months:
Considering the years from 1900 to 2100.
- 1904-1
 
- 1909-1
There are 201 months having 5 3-day weekends.
- 1915-1
The first 5 such months are:
- 1926-1
March 1901
- 1932-1
August 1902
Last five such months:
May 1903
- 2062-12
January 1904
- 2073-12
July 1904
- 2079-12
 
- 2084-12
The last 5 such months are:
- 2090-12
March 2097
Number of year with not one 5-full-weekend month: 29</pre>
August 2098
May 2099
January 2100
October 2100
 
There are 29 years that have no such months.
</pre>
 
=={{header|k}}==
<syntaxhighlight lang="k">
<lang k>
cal_j:(_jd[19000101]+!(-/_jd 21010101 19000101)) / enumerate the calendar
is_we:(cal_j!7) _lin 4 5 6 / identify friday saturdays and sundays
Line 3,869 ⟶ 4,349:
yn5:y@&~y _lin y5 / find any years not in the 5 weekend month list
`0:,"There are ",($#yn5)," years without any five-weekend months"
`0:,1_,/",",/:$yn5</langsyntaxhighlight>
{{out}}
<pre>
Line 3,888 ⟶ 4,368:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.util.*
Line 3,914 ⟶ 4,394:
println("There are ${yearsWithNone.size} years with no months which have 5 weekends, namely:")
println(yearsWithNone)
}</langsyntaxhighlight>
 
{{out}}
Line 3,927 ⟶ 4,407:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
months = array(1, 3, 5, 7, 8, 10, 12),
fivemonths = array,
Line 3,978 ⟶ 4,458:
}
 
#output</langsyntaxhighlight>
{{out|Result}}
<pre>Total number of months 201
Line 3,987 ⟶ 4,467:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
local months={"JAN","MAR","MAY","JUL","AUG","OCT","DEC"}
local daysPerMonth={31+28,31+30,31+30,31,31+30,31+30,0}
Line 4,018 ⟶ 4,498:
print("Months with 5 weekends: ",cnt_months)
print("Years without 5 weekends in the same month:",cnt_no5we)
</syntaxhighlight>
</lang>
{{out}}
<pre>1900 0:
Line 4,046 ⟶ 4,526:
Months with 5 weekends: 201
Years without 5 weekends in the same month: 29</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">five_weekends:= proc()
local i, month, count;
#Only months with 31 days can possibly satisfy the condition
local long_months := [1,3,5,7,8,10,12];
local months := ["January","February","March","April","May","June","July","August","September","October","November","December"];
count := 0;
for i from 1900 to 2100 by 1 do
for month in long_months do
if Calendar:-DayOfWeek(Date(i, month, 1)) = 6 then
printf("%d-%s\n", i, months[month]);
count++;
end if;
end do;
end do;
printf("%d months have five full weekends.\n", count);
end proc;
five_weekends();</syntaxhighlight>
{{Out|Output}}
<pre>1901-March
1902-August
1903-May
1904-January
1904-July
1905-December
1907-March
1908-May
1909-January
1909-October
1910-July
1911-December
1912-March
1913-August
1914-May
1915-January
1915-October
1916-December
1918-March
1919-August
1920-October
1921-July
1922-December
1924-August
1925-May
1926-January
1926-October
1927-July
1929-March
1930-August
1931-May
1932-January
1932-July
1933-December
1935-March
1936-May
1937-January
1937-October
1938-July
1939-December
1940-March
1941-August
1942-May
1943-January
1943-October
1944-December
1946-March
1947-August
1948-October
1949-July
1950-December
1952-August
1953-May
1954-January
1954-October
1955-July
1957-March
1958-August
1959-May
1960-January
1960-July
1961-December
1963-March
1964-May
1965-January
1965-October
1966-July
1967-December
1968-March
1969-August
1970-May
1971-January
1971-October
1972-December
1974-March
1975-August
1976-October
1977-July
1978-December
1980-August
1981-May
1982-January
1982-October
1983-July
1985-March
1986-August
1987-May
1988-January
1988-July
1989-December
1991-March
1992-May
1993-January
1993-October
1994-July
1995-December
1996-March
1997-August
1998-May
1999-January
1999-October
2000-December
2002-March
2003-August
2004-October
2005-July
2006-December
2008-August
2009-May
2010-January
2010-October
2011-July
2013-March
2014-August
2015-May
2016-January
2016-July
2017-December
2019-March
2020-May
2021-January
2021-October
2022-July
2023-December
2024-March
2025-August
2026-May
2027-January
2027-October
2028-December
2030-March
2031-August
2032-October
2033-July
2034-December
2036-August
2037-May
2038-January
2038-October
2039-July
2041-March
2042-August
2043-May
2044-January
2044-July
2045-December
2047-March
2048-May
2049-January
2049-October
2050-July
2051-December
2052-March
2053-August
2054-May
2055-January
2055-October
2056-December
2058-March
2059-August
2060-October
2061-July
2062-December
2064-August
2065-May
2066-January
2066-October
2067-July
2069-March
2070-August
2071-May
2072-January
2072-July
2073-December
2075-March
2076-May
2077-January
2077-October
2078-July
2079-December
2080-March
2081-August
2082-May
2083-January
2083-October
2084-December
2086-March
2087-August
2088-October
2089-July
2090-December
2092-August
2093-May
2094-January
2094-October
2095-July
2097-March
2098-August
2099-May
2100-January
2100-October
201 months have five full weekends.</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">years = {1900, 2100}; months = {1 ,3 ,5 ,7 ,8 ,10 ,12};
result = Select[Tuples[{Range@@years, months}], (DateString[# ~ Join ~ 1, "DayNameShort"] == "Fri")&];
 
Line 4,055 ⟶ 4,757:
Print["Last months: " , DateString[#,{"MonthName"," ","Year"}]& /@ result[[-5 ;; All]]];
Print[# // Length, " years without 5 weekend months:\n", #] &@
Complement[Range @@ years, Part[Transpose@result, 1]];</langsyntaxhighlight>
{{out}}
<pre>201 months with 5 weekends
Line 4,067 ⟶ 4,769:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab">longmonth = [1 3 5 7 8 10 12];
 
i = 1;
Line 4,091 ⟶ 4,793:
for j = length(x)-4:length(x)
fprintf('\t %s \n',x(j,:))
end</langsyntaxhighlight>
{{out}}
<pre>There are 201 months with 5 weekends between 1900 and 2100.
Line 4,110 ⟶ 4,812:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">left(a, n) := makelist(a[i], i, 1, n)$
right(a, n) := block([m: length(a)], makelist(a[i], i, m - n + 1, m))$
 
Line 4,126 ⟶ 4,828:
 
right(a, 5);
[[2097,3],[2098,8],[2099,5],[2100,1],[2100,10]]</langsyntaxhighlight>
 
=={{header|MUMPS}}==
{{libheader|VA Kernel|22.0}}
<syntaxhighlight lang="mumps">
<lang MUMPS>
FIVE
;List and count the months between 1/1900 and 12/2100 that have 5 full weekends
Line 4,167 ⟶ 4,869:
. S:'N L=L_$S($L(L):",",1:"")_(R+1700)
W !,"For a total of "_C_" months.",!!,"There are "_$L(L,",")_" years with no five full weekends in any month.",!,"They are: "_L
Q</langsyntaxhighlight>Usage:<pre>
USER>d ^FIVE
 
Line 4,193 ⟶ 4,895:
=={{header|NetRexx}}==
 
<langsyntaxhighlight lang="netrexx">
/* NetRexx ************************************************************
* 30.08.2012 Walter Pachl derived from Rexx version 3
Line 4,239 ⟶ 4,941:
yya=yy+4800+mma
result=d-32075+1461*yya%4+367*(mm-2-mma*12)%12-3*((yya+100)%100)%4
Return result /* return the result */</langsyntaxhighlight>
Output: see Rexx version 3
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">
#!/usr/local/bin/newlisp
 
Line 4,321 ⟶ 5,023:
(println "Years with no five weekends months: " NotFives)
(exit)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,341 ⟶ 5,043:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import times
 
const LongMonths = {mJan, mMar, mMay, mJul, mAug, mOct, mDec}
 
var timeinfo = getLocalTime getTime()
timeinfo.monthday = 1
 
var sumNone = 0
Line 4,352 ⟶ 5,051:
var none = true
for month in LongMonths:
if initDateTime(1, month, year, 0, 0, 0).weekday == dFri:
timeinfo.year = year
timeinfo.month = echo month, " ", year
if getLocalTime(timeInfoToTime timeinfo).weekday == dFri:
echo month," ",year
none = false
if none: inc sumNone
 
echo "Years without a 5 weekend month: ",sumNone</lang>
echo "\nYears without a 5 weekend month: ", sumNone</syntaxhighlight>
{{out}}
<pre>March 1901
Line 4,372 ⟶ 5,070:
January 2100
October 2100
 
Years without a 5 weekend month: 29</pre>
 
Line 4,377 ⟶ 5,076:
{{libheader|OCaml Calendar Library}}
 
<langsyntaxhighlight lang="ocaml">open CalendarLib
 
let list_first_five = function
Line 4,403 ⟶ 5,102:
List.iter print_month (list_first_five (List.rev !months));
List.iter print_month (List.rev (list_first_five !months));
;;</langsyntaxhighlight>
 
{{out}}
Line 4,419 ⟶ 5,118:
2100-01
2100-10</pre>
 
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: fiveWeekEnd(y1, y2)
| y m |
 
Line 4,434 ⟶ 5,132:
]
]
dup size println dup left(5) println right(5) println ;</langsyntaxhighlight>
 
{{out}}
Line 4,445 ⟶ 5,143:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">fiveWeekends()={
my(day=6); \\ 0 = Friday; this represents Thursday for March 1, 1900.
my(ny=[31,30,31,30,31,31,30,31,30,31,31,28],ly=ny,v,s);
Line 4,464 ⟶ 5,162:
);
s
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 4,470 ⟶ 5,168:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl -w
use DateTime ;
 
Line 4,503 ⟶ 5,201:
}
print "No long weekends in the following " . @workhardyears . " years:\n" ;
map { print "$_\n" } @workhardyears ;</langsyntaxhighlight>
{{out}}
<pre>There are 201 months with 5 full weekends!
Line 4,548 ⟶ 5,246:
2096
</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015-09-10}}
<lang perl6># A month has 5 weekends iff it has 31 days and starts on Friday.
 
my @years = 1900 .. 2100;
my @has31 = 1, 3, 5, 7, 8, 10, 12;
my @happy = ($_ when *.day-of-week == 5 for (@years X @has31).map(-> ($y, $m) { Date.new: $y, $m, 1 }));
 
say 'Happy month count: ', +@happy;
say 'First happy months: ' ~ @happy[^5];
say 'Last happy months: ' ~ @happy[*-5 .. *];
say 'Dreary years count: ', @years - @happy».year.squish;</lang>
 
{{out}}
<pre>Happy month count: 201
First happy months: 1901-03-01 1902-08-01 1903-05-01 1904-01-01 1904-07-01
Last happy months: 2097-03-01 2098-08-01 2099-05-01 2100-01-01 2100-10-01
Dreary years count: 29</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence m31 = {"January",0,"March",0,"May",0,"July","August",0,"October",0,"December"}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer y,m,
<span style="color: #004080;">sequence</span> <span style="color: #000000;">m31</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"January"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"March"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"May"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"July"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"August"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"October"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"December"</span><span style="color: #0000FF;">}</span>
nmonths = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span>
string months
<span style="color: #000000;">nmonths</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
sequence res = {},
<span style="color: #004080;">string</span> <span style="color: #000000;">months</span>
none = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
<span style="color: #000000;">none</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
for y=1900 to 2100 do
months = ""
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1900</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2100</span> <span style="color: #008080;">do</span>
for m=1 to 12 do
<span style="color: #000000;">months</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
if string(m31[m])
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">12</span> <span style="color: #008080;">do</span>
and day_of_week(y,m,1)=6 then
<span style="color: #008080;">if</span> <span style="color: #004080;">string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m31</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m</span><span style="color: #0000FF;">])</span>
if length(months)!=0 then months &= ", " end if
<span style="color: #008080;">and</span> <span style="color: #7060A8;">day_of_week</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)=</span><span style="color: #008000;">"Friday"</span> <span style="color: #008080;">then</span>
months &= m31[m]
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">months</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">months</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">", "</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
nmonths += 1
<span style="color: #000000;">months</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">m31</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #000000;">nmonths</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if length(months)=0 then
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
none = append(none,y)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">months</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">none</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">none</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
res = append(res,sprintf("%d : %s\n",{y,months}))
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d : %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">months</span><span style="color: #0000FF;">}))</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"Found %d months with five full weekends\n",nmonths)
res[6..-6] = {" ...\n"}
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Found %d months with five full weekends\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nmonths</span><span style="color: #0000FF;">)</span>
puts(1,join(res,""))
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">6</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">" ...\n"</span><span style="color: #0000FF;">}</span>
printf(1,"Found %d years with no month having 5 weekends:\n",{length(none)})
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">))</span>
none[6..-6] = {".."}
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Found %d years with no month having 5 weekends:\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">none</span><span style="color: #0000FF;">)})</span>
?none</lang>
<span style="color: #000000;">none</span><span style="color: #0000FF;">[</span><span style="color: #000000;">6</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">".."</span><span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">none</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 4,616 ⟶ 5,298:
{1900,1906,1917,1923,1928,"..",2068,2074,2085,2091,2096}
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go ?=>
println("Months with five weekends:"),
FiveWeekends = [ [Year,Month] : Year in 1900..2100, Month in [1,3,5,7,8,10,12], dow(Year,Month,1) == 5],
WLen = FiveWeekends.len,
println(take(FiveWeekends,5)),
println("..."),
println(drop(FiveWeekends,WLen-5)),
println(len=WLen),
nl,
 
println("Years w/o five weekends:"),
FiveWeekendYears = [Year : [Year,_] in FiveWeekends].remove_dups,
NoHitYears = [Year : Year in 1900..2100, not member(Year,FiveWeekendYears)],
NHLen = NoHitYears.len,
println(take(NoHitYears,5)),
println("..."),
println(drop(NoHitYears,NHLen-5)),
println(len=NHLen),
nl.
go => true.
 
% Day of week, Sakamoto's method
dow(Y, M, D) = R =>
T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],
if M < 3 then
Y := Y - 1
end,
R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.
 
% Days in a month.
max_days_in_month(Year,Month) = Days =>
if member(Month, [1,3,5,7,8,10,12]) then
Days = 31
elseif member(Month,[4,6,9,11]) then
Days = 30
else
if leap_year(Year) then
Days = 29
else
Days = 28
end
end.
 
leap_year(Year) =>
(Year mod 4 == 0, Year mod 100 != 0)
;
Year mod 400 == 0. </syntaxhighlight>
 
{{out}}
<pre>Months with five weekends:
[[1901,3],[1902,8],[1903,5],[1904,1],[1904,7]]
...
[[2097,3],[2098,8],[2099,5],[2100,1],[2100,10]]
len = 201
 
Years w/o five weekends:
[1900,1906,1917,1923,1928]
...
[2068,2074,2085,2091,2096]
len = 29</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq Lst
(make
(for Y (range 1900 2100)
Line 4,634 ⟶ 5,378:
(setq Lst (diff (range 1900 2100) (uniq (mapcar cadr Lst))))
(prinl "There are " (length Lst) " years with no five-weekend months:")
(println Lst)</langsyntaxhighlight>
{{out}}
<pre>There are 201 months with five weekends:
Line 4,654 ⟶ 5,398:
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">int(0..1) weekends(object day)
{
return (<5,6,7>)[day->week_day()];
Line 4,671 ⟶ 5,415:
 
array rest = range->years() - have5->year();
write("%d years without any 5 weekend month:\n %{%d,%}\n", sizeof(rest), rest->year_no());</langsyntaxhighlight>
 
{{out}}
Line 4,693 ⟶ 5,437:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
weekends: procedure options (main); /* 28/11/2011 */
declare tally fixed initial (0);
Line 4,719 ⟶ 5,463:
 
end weekends;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,801 ⟶ 5,545:
=={{header|PowerShell}}==
 
<langsyntaxhighlight lang="powershell">$fiveWeekends = @()
$yearsWithout = @()
foreach ($y in 1900..2100) {
Line 4,820 ⟶ 5,564:
Write-Output ""
Write-Output "Extra Credit: these $($yearsWithout.count) years have no such month:"
Write-Output ($yearsWithout -join ",")</langsyntaxhighlight>
 
{{Output}}
Line 4,829 ⟶ 5,573:
1900,1906,1917,1923,1928,1934,1945,1951,1956,1962,1973,1979,1984,1990,2001,2007,2012,2018,2029,2035,2040,2046,2057,2063
,2068,2074,2085,2091,2096</pre>
 
=={{header|Prolog}}==
Works with SWI-Prolog;
<syntaxhighlight lang="prolog">main() :-
weekends(1900, 2100, FiveWeekendList, RemainderWeekendList),
 
length(FiveWeekendList, FiveLen),
maplist(write, ["Total five weekend months:", FiveLen, '\n']),
slice(FiveWeekendList, 5, FirstFiveList),
maplist(write, ["First five {year,month} pairs:", FirstFiveList, '\n']),
slice(FiveWeekendList, -5, LastFiveList),
maplist(write, ["Last five {year,month} pairs:", LastFiveList, '\n']),
 
maplist(take_year, FiveWeekendList, FiveYearList),
list_to_set(FiveYearList, FiveYearSet),
maplist(take_year, RemainderWeekendList, RemainderYearList),
list_to_set(RemainderYearList, RemainderYearSet),
 
subtract(RemainderYearSet, FiveYearSet, NonFiveWeekendSet),
length(NonFiveWeekendSet, NonFiveWeekendLen),
maplist(write, ["Total years with no five weekend months:", NonFiveWeekendLen, '\n']),
writeln(NonFiveWeekendSet).
 
weekends(StartYear, EndYear, FiveWeekendList, RemainderWeekendList) :-
numlist(StartYear, EndYear, YearList),
numlist(1, 12, MonthList),
pair(YearList, MonthList, YearMonthList),
partition(has_five_weekends, YearMonthList, FiveWeekendList, RemainderWeekendList).
 
has_five_weekends({Year, Month}) :-
long_month(Month),
starts_on_a_friday(Year, Month).
 
starts_on_a_friday(Year, Month) :-
Date = date(Year, Month, 1),
day_of_the_week(Date, DayOfTheWeek),
DayOfTheWeek == 5.
 
take_year({Year, _}, Year).
 
long_month(1).
long_month(3).
long_month(5).
long_month(7).
long_month(8).
long_month(10).
long_month(12).
 
% Helpers
 
% https://stackoverflow.com/a/7739806
pair(L1, L2, Pairs):-findall({A,B}, (member(A, L1), member(B, L2)), Pairs).
 
slice(_, 0, []).
 
slice(List, N, NList):-
N < 0,
N1 is abs(N),
last_n_elements(List, N1, NList).
 
slice(List, N, NList):-
N > 0,
first_n_elements(List, N, NList).
 
first_n_elements(List, N, FirstN):-
length(FirstN, N),
append(FirstN, _, List).
 
last_n_elements(List, N, LastN) :-
length(LastN, N),
append(_, LastN, List).
</syntaxhighlight>
{{out}}
<pre>?- main.
Total five weekend months:201
First five {year,month} pairs:[{1901,3},{1902,8},{1903,5},{1904,1},{1904,7}]
Last five {year,month} pairs:[{2097,3},{2098,8},{2099,5},{2100,1},{2100,10}]
Total years with no five weekend months:29
[1900,1906,1917,1923,1928,1934,1945,1951,1956,1962,1973,1979,1984,1990,2001,2007,2012,2018,2029,2035,2040,2046,2057,2063,2068,2074,2085,2091,2096]
true .</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure DateG(year.w, month.b, day)
;Returns the number of days before or after the earliest reference date
;in PureBasic's Date Library (1 Jan 1970) based on an assumed Gregorian calendar calculation
Line 4,896 ⟶ 5,724:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out|Sample output}}
<pre>1901 3
Line 4,916 ⟶ 5,744:
 
=={{header|Python}}==
<syntaxhighlight lang ="python">from datetime import timedelta(date, date
timedelta)
 
DAY = timedelta(days=1)
START, STOP = date(1900, 1, 1), date(2101, 1, 1)
WEEKEND = {6, 5, 4} # Sunday is day 6
FMT = '%Y %m(%B)'
 
def fiveweekendspermonth(start=START, stop=STOP):
'Compute months with five weekends between dates'
when = start
lastmonth = weekenddays = 0
fiveweekends = []
while when < stop:
year, mon, _mday, _h, _m, _s, wday, _yday, _isdst = when.timetuple()
if mon != lastmonth:
if weekenddays >= 15:
fiveweekends.append(when - DAY)
weekenddays = 0
lastmonth = mon
if wday in WEEKEND:
weekenddays += 1
when += DAY
return fiveweekends
 
def five_weekends_per_month(start: date = START,
dates = fiveweekendspermonth()
stop: date = STOP) -> list[date]:
"""Compute months with five weekends between dates"""
current_date = start
last_month = weekend_days = 0
five_weekends = []
while current_date < stop:
if current_date.month != last_month:
if weekend_days >= 15:
five_weekends.append(current_date - DAY)
weekend_days = 0
last_month = current_date.month
if current_date.weekday() in WEEKEND:
weekend_days += 1
current_date += DAY
return five_weekends
 
 
dates = five_weekends_per_month()
indent = ' '
print('f"There are %s{len(dates)} months of which the first and last five are:' % len(dates)")
print(indent + ('\n' + indent).join(d.strftime(FMT) for d in dates[:5]))
print(indent + '...')
print(indent + ('\n' + indent).join(d.strftime(FMT) for d in dates[-5:]))
 
years_without_five_weekends_months = (STOP.year - START.year
print('\nThere are %i years in the range that do not have months with five weekends'
% len(set(range(START.year, STOP.year)) - len({d.year for d in dates}))</lang>
print(f"\nThere are {years_without_five_weekends_months} years in the "
f"range that do not have months with five weekends")</syntaxhighlight>
 
'''Alternate Algorithm'''
 
The condition is equivalent to having a thirty-one day month in which the last day of the month is a Sunday.
<langsyntaxhighlight lang="python">LONGMONTHS = (1, 3, 5, 7, 8, 10, 12) # Jan Mar May Jul Aug Oct Dec
 
def fiveweekendspermonth2(start=START, stop=STOP):
 
return [date(yr, month, 31)
def five_weekends_per_month2(start: date = START,
for yr in range(START.year, STOP.year)
for month in LONGMONTHS stop: date = STOP) -> list[date]:
return [last_day
if date(yr, month, 31).timetuple()[6] == 6 # Sunday
]for year in range(start.year, stop.year)
for month in LONG_MONTHS
if (last_day := date(year, month, 31)).weekday() == 6] # Sunday
 
dates2 = fiveweekendspermonth2five_weekends_per_month2()
assert dates2 == dates</langsyntaxhighlight>
 
{{out|Sample output}}
Line 4,980 ⟶ 5,814:
 
There are 29 years in the range that do not have months with five weekends</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ over 3 < if [ 1 - ]
dup 4 / over +
over 100 / -
swap 400 / +
swap 1 -
[ table
0 3 2 5 0 3
5 1 4 6 2 4 ]
+ + 7 mod ] is dayofweek ( day month year --> weekday )
 
[ 1 -
[ table
$ "January" $ "February"
$ "March" $ "April"
$ "May" $ "June"
$ "July" $ "August"
$ "September" $ "October"
$ "November" $ "December" ]
do ] is monthname ( monthnumber --> $ )
[] [] temp put
201 times
[ true temp put
i^ 1900 +
' [ 1 3 5 7 8 10 12 ]
witheach
[ 2dup swap
1 unrot dayofweek
5 = iff
[ false temp replace
over join nested
swap dip join ]
else drop ]
temp take iff
[ temp take
swap join
temp put ]
else drop ]
temp take swap
say "There are "
dup size echo
say " months with five weekends."
cr cr
5 split swap
say "Five weekends: "
witheach
[ do swap
monthname echo$
sp echo
i if say ", " ]
cr say " ..."
cr space 15 of echo$
-5 split nip
witheach
[ do swap
monthname echo$
sp echo
i if say ", " ]
cr cr
say "Years without five weekends: "
witheach
[ echo
i if say ", "
i^ 8 mod 7 = if
[ cr space 29 of echo$ ] ]</syntaxhighlight>
 
{{out}}
 
<pre>There are 201 months with five weekends.
 
Five weekends: March 1901, August 1902, May 1903, January 1904, July 1904
...
March 2097, August 2098, May 2099, January 2100, October 2100
 
Years without five weekends: 1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951,
1956, 1962, 1973, 1979, 1984, 1990, 2001, 2007,
2012, 2018, 2029, 2035, 2040, 2046, 2057, 2063,
2068, 2074, 2085, 2091, 2096</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">ms = as.Date(sapply(c(1, 3, 5, 7, 8, 10, 12),
function(month) paste(1900:2100, month, 1, sep = "-")))
ms = format(sort(ms[weekdays(ms) == "Friday"]), "%b %Y")
message("There are ", length(ms), " months with five weekends.")
message("The first five: ", paste(ms[1:5], collapse = ", "))
message("The last five: ", paste(tail(ms, 5), collapse = ", "))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require srfi/19)
Line 5,010 ⟶ 5,925:
(define count (length weekends))
 
(displayln (~a "There are " count " weeksmonths with five weekends."))
(displayln "The first five are: ")
(for ([w (take weekends 5)])
Line 5,017 ⟶ 5,932:
(for ([w (drop weekends (- count 5))])
(displayln (date->string w "~b ~Y")))
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 201 weeksmonths with five weekends.
The first five are:
Mar 1901
Line 5,034 ⟶ 5,949:
Oct 2100
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015-09-10}}
<syntaxhighlight lang="raku" line># A month has 5 weekends iff it has 31 days and starts on Friday.
 
my @years = 1900 .. 2100;
my @has31 = 1, 3, 5, 7, 8, 10, 12;
my @happy = ($_ when *.day-of-week == 5 for (@years X @has31).map(-> ($y, $m) { Date.new: $y, $m, 1 }));
 
say 'Happy month count: ', +@happy;
say 'First happy months: ' ~ @happy[^5];
say 'Last happy months: ' ~ @happy[*-5 .. *];
say 'Dreary years count: ', @years - @happy».year.squish;</syntaxhighlight>
 
{{out}}
<pre>Happy month count: 201
First happy months: 1901-03-01 1902-08-01 1903-05-01 1904-01-01 1904-07-01
Last happy months: 2097-03-01 2098-08-01 2099-05-01 2100-01-01 2100-10-01
Dreary years count: 29</pre>
 
=={{header|REXX}}==
Line 5,042 ⟶ 5,977:
<br>Changing the task's requirements to find how many extended weekends (Fr-Sa-Su ''or'' Sa-Su-Mo) there are for
<br>each month would entail changing only a single &nbsp; '''if''' &nbsp; statement.
<langsyntaxhighlight lang="rexx">/*REXX program finds months that contain five weekends (given a date range). */
month. =31; month.2=0 /*month days; February is skipped. */
month.4=30; month.6=30; month.9=30; month.11=30 /*all the months with thirty-days. */
Line 5,072 ⟶ 6,007:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/</langsyntaxhighlight>
'''output''' &nbsp; when using the default inputs:
<pre style="height:98ex">
Line 5,314 ⟶ 6,249:
===version for older REXXes===
This version will work with any version of a REXX interpreter.
<langsyntaxhighlight lang="rexx">/*REXX program finds months that contain five weekends (given a date range). */
month. =31; month,2=0 /*month days; February is skipped. */
month.4=30; month.6=30; month.9=30; month.11=30 /*all the months with thirty-days. */
Line 5,350 ⟶ 6,285:
if w==0 then w=7; return w /*Sunday=1, Monday=2, ... Saturday=7 */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version.
<br><br>
 
===version short and focussed at the task description===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Short(er) solution focussed at the task's description
* Only 7 months can have 5 full weekends
Line 5,409 ⟶ 6,344:
Return result /* return the result */
 
leapyear: Return ( (arg(1)//4=0) & (arg(1)//100<>0) ) | (arg(1)//400=0)</langsyntaxhighlight>
{{Out}}
<pre>
Line 5,431 ⟶ 6,366:
 
===shorter version===
<langsyntaxhighlight lang="rexx">/*REXX program finds months that contain five weekends (given a date range). */
month. =31; month.2=0 /*month days; February is skipped. */
month.4=30; month.6=30; month.9=30; month.11=30 /*all the months with thirty-days. */
Line 5,460 ⟶ 6,395:
say
say "There are " # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version.
 
===shorter and more focused===
This REXX version takes advantage that a month with five full weekends must start on a Friday and have 31 days.
<langsyntaxhighlight lang="rexx">/*REXX program finds months that contain five weekends (given a date range). */
month. =31 /*days in "all" the months. */
month.2=0; month.4=0; month.6=0; month.9=0; month.11=0 /*not 31 day months.*/
Line 5,491 ⟶ 6,426:
end /*y*/
say
say "There are " # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version.
<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
sum = 0
month = list(12)
Line 5,515 ⟶ 6,450:
next
see "Total : " + sum + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,537 ⟶ 6,472:
2100-October
Total : 201
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
OVER 3 < -
R→B DUP 4 / OVER 100 / - OVER 400 / + + B→R
{ 0 3 2 5 0 3 5 1 4 6 2 4 } ROT GET + + 7 MOD
≫ ''''DAYoW'''' STO
{} (0,0) 1900 2100 FOR y
1 CF 1 12 '''FOR''' m
'''IF''' { 1 3 5 7 8 10 12 } m POS '''THEN'''
'''IF''' 1 m y '''DAYoW''' 5 == '''THEN'''
'''IF''' DUP RE 5 < OVER RE 195 > OR '''THEN'''
y m R→C ROT SWAP + SWAP '''END'''
1 + 1 SF '''END'''
'''END'''
'''NEXT IF''' 1 FC? '''THEN''' (0,1) + '''END'''
'''NEXT'''
≫ ''''MW5WE'''' STO
|
'''DAYoW''' ''( j mm aaaa -- day )''
if ( m < 3 ) { y -= 1; }
return (y + y/4 - y/100 + y/400
+ t[m-1] + d) % 7 ;
'''MW5WE''' ''( -- {(first)..(last)} (months,years) )''
For each year in range
reset flag
scan long months
if month starts on Fridays
if in first 5 or last 5 ones
store as (yyyy,mm)
increase month counter, set flag
if flag not set, count the year
|}
{{out}}
<pre>
2: { (1901,3) (1902,8) (1903,5) (1904,1) (1904,7) (2097,3) (2098,8) (2099,5) (2100,1) (2100,10) }
1: (201,29)
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'date'
# The only case where the month has 5 weekends is when the last day
# of the month falls on a Sunday and the month has 31 days.
 
LONG_MONTHS = [1,3,5,7,8,10,12]
dates = []
YEARS = (1900.upto(.2100) do |year|.to_a
 
1.upto(12) do |month|
dates = YEARS.product(LONG_MONTHS).map{|y, m| Date.new(y,m,31)}.select(&:sunday?)
d = Date.new(year, month, -1) # -1 is last day of month
years_4w = YEARS - dates.map(&:year)
dates << d if d.sunday? && d.day == 31
end
end
 
puts "There are #{dates.size} months with 5 weekends from 1900 to 2100:"
puts dates.first(5).map { |d| d.strftime("%b %Y") }, "..."
puts dates.last(5).map {|d| d.strftime("%b %Y") }
puts "..."
puts "There are #{years_4w.size} years without months with 5 weekends:"
puts dates.last(5).map { |d| d.strftime("%b %Y") }
puts years_4w.join(", ")</syntaxhighlight>
years_with_5w = dates.map(&:year)
years = (1900..2100).to_a - years_with_5w
puts "There are #{years.size} years without months with 5 weekends:"
puts years.join(", ")</lang>
 
'''Output'''
Line 5,583 ⟶ 6,561:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">preYear = 1900
for yyyy = 1900 to 2100
for mm = 1 to 12 ' go thru all 12 months
Line 5,608 ⟶ 6,586:
end if
preCount = count
next yyyy</langsyntaxhighlight>
 
{{Out}}
Line 5,628 ⟶ 6,606:
200 2100-01
201 2100-01</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">extern crate chrono;
use chrono::prelude::*;
 
/// Months with 31 days
const LONGMONTHS: [u32; 7] = [1, 3, 5, 7, 8, 10, 12];
 
/// Get all the tuples (year, month) in wich there is five Fridays, five Saturdays and five Sundays
/// between the years start and end (inclusive).
fn five_weekends(start: i32, end: i32) -> Vec<(i32, u32)> {
let mut out = vec![];
 
for year in start..=end {
for month in LONGMONTHS.iter() {
// Five weekends if a 31-days month starts with a Friday.
if Local.ymd(year, *month, 1).weekday() == Weekday::Fri {
out.push((year, *month));
}
}
}
 
out
}
 
fn main() {
let out = five_weekends(1900, 2100);
 
let len = out.len();
println!(
"There are {} months of which the first and last five are:",
len
);
for (y, m) in &out[..5] {
println!("\t{} / {}", y, m);
}
println!("...");
for (y, m) in &out[(len - 5..)] {
println!("\t{} / {}", y, m);
}
}
 
#[test]
fn test() {
let out = five_weekends(1900, 2100);
assert_eq!(out.len(), 201);
}</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import java.util.Calendar._
import java.util.GregorianCalendar
 
Line 5,664 ⟶ 6,689:
(1900 to 2100) - months.map(_.year) shouldBe expectedNon5erYears
}
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "time.s7i";
 
Line 5,684 ⟶ 6,709:
end for;
writeln("Number of months:" <& months);
end func;</langsyntaxhighlight>
 
{{Out}}
Line 5,706 ⟶ 6,731:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">require('DateTime');
 
var happymonths = [];
Line 5,739 ⟶ 6,764:
say happymonths.last(5).join("\n");
say "No long weekends in the following #{workhardyears.len} years:";
say workhardyears.join(",");</langsyntaxhighlight>
{{out}}
<pre>
Line 5,757 ⟶ 6,782:
1900,1906,1917,1923,1928,1934,1945,1951,1956,1962,1973,1979,1984,1990,2001,2007,2012,2018,2029,2035,2040,2046,2057,2063,2068,2074,2085,2091,2096
</pre>
 
=={{header|Simula}}==
{{trans|FreeBasic}}
<langsyntaxhighlight lang="simula">! TRANSLATION OF FREEBASIC VERSION ;
BEGIN
 
Line 5,848 ⟶ 6,874:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,874 ⟶ 6,900:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">clear
set obs `=tm(2101m1)-tm(1900m1)'
gen month=tm(1900m1)+_n-1
Line 5,903 ⟶ 6,929:
| 2100m1 |
| 2100m10 |
+---------+</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
set months {}
Line 5,927 ⟶ 6,953:
puts [join [list {*}[lrange $months 0 4] ... {*}[lrange $months end-4 end]] \n]
puts "There are [llength $years] years without any five-weekend months"
puts [join $years ","]</langsyntaxhighlight>
{{Out}}
<pre>
Line 5,947 ⟶ 6,973:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
LOOP year=1900,2100
Line 5,955 ⟶ 6,981:
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
{{Out}}
<pre style='height:30ex;overflow:scroll'>
Line 6,163 ⟶ 7,189:
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="text">' ------=< MAIN >=------
' only months with 31 day can have five weekends
' these months are: January, March, May, July, August, October, December
Line 6,230 ⟶ 7,256:
100 Print "October"; : Return
110 Print "November"; : Return
120 Print "December"; : Return</langsyntaxhighlight>
{{out}}
<pre>1901 | March
Line 6,259 ⟶ 7,285:
* feed this file to an awk-script to look for the months with 5 weekends.
 
<langsyntaxhighlight lang="bash">echo "Creating cal-file..."
echo > cal.txt
for ((y=1900; y <= 2100; y++)); do
Line 6,271 ⟶ 7,297:
echo "Looking for month with 5 weekends:"
awk -f 5weekends.awk cal.txt
</syntaxhighlight>
</lang>
 
See also: [http://rosettacode.org/wiki/Five_weekends#AWK awk] and [[Calendar]]. <br>
Try it out online: [http://www.compileonline.com/execute_ksh_online.php compileonline.com]
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
 
Sub Main()
Dim y As Long, m As Long, t As String, cpt As Long, cptm As Long
For y = 1900 To 2100
t = vbNullString
For m = 1 To 12 Step 2
If m = 9 Then m = 8
If Weekday(DateSerial(y, m, 1)) = vbFriday Then
t = t & ", " & m
cptm = cptm + 1
End If
Next
If t <> "" Then
Debug.Print y & t
Else
cpt = cpt + 1
End If
Next
Debug.Print "There is " & cptm & " months with five full weekends from the year 1900 through 2100"
Debug.Print "There is " & cpt & " years which don't have months with five weekends"
End Sub</syntaxhighlight>
{{out}}
<pre>1901, 3
1902, 8
1903, 5
1904, 1, 7
1905, 12
1907, 3
1908, 5
1909, 1, 10
1910, 7
......
2090, 12
2092, 8
2093, 5
2094, 1, 10
2095, 7
2097, 3
2098, 8
2099, 5
2100, 1, 10
There is 201 months with five full weekends from the year 1900 through 2100
There is 29 years which don't have months with five weekends</pre>
 
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
<lang VBScript>
For y = 1900 To 2100
For m = 1 To 12
Line 6,290 ⟶ 7,363:
 
WScript.Echo vbCrLf & "Total = " & i & " months"
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{libheader|Wren-date}}
{{libheader|Wren-seq}}
<syntaxhighlight lang="wren">import "./date" for Date
import "./seq" for Lst
 
var dates = []
var years = []
for (y in 1900..2100) {
var hasFive = false
for (m in 1..12) {
var fri = 0
var sat = 0
var sun = 0
for (d in 1..Date.monthLength(y, m)) {
var d = Date.new(y, m, d)
var dow = d.dayOfWeek
if (dow == 5) {
fri = fri + 1
} else if (dow == 6) {
sat = sat + 1
} else if (dow == 7) {
sun = sun + 1
}
}
var fd = Date.new(y, m, 1)
if (fri == 5 && sat == 5 && sun == 5) {
dates.add(fd)
hasFive = true
}
}
if (!hasFive) years.add(y)
}
 
Date.default = "mmm|-|yyyy"
System.print("Between 1900 and 2100:-")
System.print(" There are %(dates.count) months that have five full weekends.")
System.print(" The first 5 are:")
for (i in 0..4) System.print(" %(dates[i])")
System.print(" and the last 5 are:")
for (i in -5..-1) System.print(" %(dates[i])")
System.print("\n There are %(years.count) years that do not have at least one five-weekend month, namely:")
var chunks = Lst.chunks(years, 10)
for (i in 0...chunks.count) System.print(" %(chunks[i])")</syntaxhighlight>
 
{{out}}
<pre>
Between 1900 and 2100:-
There are 201 months that have five full weekends.
The first 5 are:
Mar-1901
Aug-1902
May-1903
Jan-1904
Jul-1904
and the last 5 are:
Mar-2097
Aug-2098
May-2099
Jan-2100
Oct-2100
 
There are 29 years that do not have at least one five-weekend month, namely:
[1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962]
[1973, 1979, 1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035]
[2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096]
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
 
Line 6,330 ⟶ 7,471:
];
CrLf(0); IntOut(0, C); CrLf(0); \show number of years
]</langsyntaxhighlight>
 
{{Out}}
Line 6,353 ⟶ 7,494:
=={{header|zkl}}==
Months with five weekends:
<langsyntaxhighlight lang="zkl">var [const] D=Time.Date, r=L();
foreach y,m in ([1900..2100],[1..12]){
if (D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) r.append(String(y,"-",m))
}</langsyntaxhighlight>
Alternatively, in a functional style using list comprehensions:
<langsyntaxhighlight lang="zkl">r:=[[(y,m); [1900..2100];
[1..12],{D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)};
{String(y,"-",m)}]];</langsyntaxhighlight>
{{out}}
<pre>
Line 6,369 ⟶ 7,510:
 
Extra credit: Years with no five day weekends:
<langsyntaxhighlight lang="zkl">var [const] D=Time.Date, r=L();
foreach y in ([1900..2100]){ yes:=True;
foreach m in ([1..12]){
Line 6,375 ⟶ 7,516:
}
if (yes) r.append(y)
}</langsyntaxhighlight>
Alternatively:
<langsyntaxhighlight lang="zkl">var yes, r=[[(y,m);
[1900..2100];
[1..12],{if(m==1)yes=True; if(D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) yes=False; True},
{if (m==12) yes else False};
{y}]]</langsyntaxhighlight>
Bit of a sleaze using a global var (yes) to hold state.
First filter: On the first month, reset global, note if month has five weekends, always pass.
1,983

edits