Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
5
Task/Five-weekends/00-META.yaml
Normal file
5
Task/Five-weekends/00-META.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
category:
|
||||
- Puzzles
|
||||
from: http://rosettacode.org/wiki/Five_weekends
|
||||
note: Date and time
|
||||
25
Task/Five-weekends/00-TASK.txt
Normal file
25
Task/Five-weekends/00-TASK.txt
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
|
||||
|
||||
|
||||
;Task:
|
||||
# Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
|
||||
# Show the ''number'' of months with this property (there should be 201).
|
||||
# Show at least the first and last five dates, in order.
|
||||
|
||||
|
||||
'''Algorithm suggestions'''
|
||||
* Count the number of Fridays, Saturdays, and Sundays in every month.
|
||||
* Find all of the 31-day months that begin on Friday.
|
||||
|
||||
|
||||
'''Extra credit'''
|
||||
|
||||
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
|
||||
|
||||
|
||||
;Related tasks
|
||||
* [[Day of the week]]
|
||||
* [[Last Friday of each month]]
|
||||
* [[Find last sunday of each month]]
|
||||
<br><br>
|
||||
|
||||
100
Task/Five-weekends/360-Assembly/five-weekends.360
Normal file
100
Task/Five-weekends/360-Assembly/five-weekends.360
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
* Five weekends 31/05/2016
|
||||
FIVEWEEK CSECT
|
||||
USING FIVEWEEK,R13 base register
|
||||
B 72(R15) skip savearea
|
||||
DC 17F'0' savearea
|
||||
STM R14,R12,12(R13) prolog
|
||||
ST R13,4(R15) "
|
||||
ST R15,8(R13) "
|
||||
LR R13,R15 "
|
||||
LM R10,R11,=AL8(0) nko=0; nok=0
|
||||
LH R6,Y1 y=y1
|
||||
LOOPY CH R6,Y2 do y=y1 to y2
|
||||
BH ELOOPY
|
||||
MVI YF,X'00' yf=0
|
||||
LA R7,1 im=1
|
||||
LOOPIM C R7,=F'7' do im=1 to 7
|
||||
BH ELOOPIM
|
||||
LR R1,R7 im
|
||||
SLA R1,1 *2 (H)
|
||||
LH R2,ML-2(R1) ml(im)
|
||||
ST R2,M m=ml(im)
|
||||
MVC D,=F'1' d=1
|
||||
L R4,M m
|
||||
C R4,=F'2' if m<=2
|
||||
BH MSUP2
|
||||
L R8,M m
|
||||
LA R8,12(R8) mw=m+12
|
||||
LR R9,R6 y
|
||||
BCTR R9,0 yw=y-1
|
||||
B EMSUP2
|
||||
MSUP2 L R8,M mw=m
|
||||
LR R9,R6 yw=y
|
||||
EMSUP2 LR R4,R9 ym
|
||||
SRDA R4,32 .
|
||||
D R4,=F'100' yw/100
|
||||
ST R5,J j=yw/100
|
||||
ST R4,K k=yw//100
|
||||
LR R4,R8 mw
|
||||
LA R4,1(R4) mw+1
|
||||
MH R4,=H'26' (mw+1)*26
|
||||
SRDA R4,32 .
|
||||
D R4,=F'10' (mw+1)*26/10
|
||||
LR R2,R5 "
|
||||
A R2,D d
|
||||
A R2,K d+k
|
||||
L R3,K k
|
||||
SRA R3,2 k/4
|
||||
AR R2,R3 (mw+1)*26/10+k/4
|
||||
L R3,J j
|
||||
SRA R3,2 j/4
|
||||
AR R2,R3 (mw+1)*26/10+k/4+j/4
|
||||
LA R5,5 5
|
||||
M R4,J 5*j
|
||||
AR R2,R5 (mw+1)*26/10+k/4+j/4
|
||||
SRDA R2,32 .
|
||||
D R2,=F'7' (d+(mw+1)*26/10+k+k/4+j/4+5*j)/7
|
||||
C R2,=F'6' if dow=friday
|
||||
BNE NOFRIDAY
|
||||
XDECO R6,XDEC y
|
||||
MVC PG+0(4),XDEC+8 output y
|
||||
LR R1,R7 im
|
||||
MH R1,=H'3' *3
|
||||
LA R14,MN-3(R1) @mn(im)
|
||||
MVC PG+5(3),0(R14) output mn(im)
|
||||
XPRNT PG,8 print buffer
|
||||
LA R11,1(R11) nok=nok+1
|
||||
MVI YF,X'01' yf=1
|
||||
NOFRIDAY LA R7,1(R7) im=im+1
|
||||
B LOOPIM
|
||||
ELOOPIM L R4,YF yf
|
||||
CLI YF,X'00' if yf=0
|
||||
BNE EYFNE0
|
||||
LA R10,1(R10) nko=nko+1
|
||||
EYFNE0 LA R6,1(R6) y=y+1
|
||||
B LOOPY
|
||||
ELOOPY XDECO R11,XDEC nok
|
||||
MVC PG+0(4),XDEC+8 output nok
|
||||
MVC PG+4(12),=C' occurrences'
|
||||
XPRNT PG,80 print buffer
|
||||
XDECO R10,XDEC nko
|
||||
MVC PG+0(4),XDEC+8 output nko
|
||||
MVC PG+4(33),=C' years with no five weekend month'
|
||||
XPRNT PG,80 print buffer
|
||||
L R13,4(0,R13) epilog
|
||||
LM R14,R12,12(R13) "
|
||||
XR R15,R15 "
|
||||
BR R14 exit
|
||||
Y1 DC H'1900' year start
|
||||
Y2 DC H'2100' year stop
|
||||
ML DC H'1',H'3',H'5',H'7',H'8',H'10',H'12'
|
||||
MN DC C'jan',C'mar',C'may',C'jul',C'aug',C'oct',C'dec'
|
||||
YF DS X year flag
|
||||
M DS F month
|
||||
D DS F day
|
||||
J DS F j=yw/100
|
||||
K DS F j=mod(yw,100)
|
||||
PG DC CL80'....-' buffer
|
||||
XDEC DS CL12 temp for XDECO
|
||||
YREGS
|
||||
END FIVEWEEK
|
||||
53
Task/Five-weekends/ALGOL-68/five-weekends.alg
Normal file
53
Task/Five-weekends/ALGOL-68/five-weekends.alg
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
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 #
|
||||
56
Task/Five-weekends/AWK/five-weekends.awk
Normal file
56
Task/Five-weekends/AWK/five-weekends.awk
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# usage: awk -f 5weekends.awk cal.txt
|
||||
|
||||
# Filter a file of month-calendars, such as
|
||||
# ...
|
||||
## January 1901
|
||||
## Mo Tu We Th Fr Sa Su
|
||||
## 1 2 3 4 5 6
|
||||
## 7 8 9 10 11 12 13
|
||||
## 14 15 16 17 18 19 20
|
||||
## 21 22 23 24 25 26 27
|
||||
## 28 29 30 31
|
||||
# ...
|
||||
## March 1901
|
||||
## Mo Tu We Th Fr Sa Su
|
||||
## 1 2 3
|
||||
## 4 5 6 7 8 9 10
|
||||
## 11 12 13 14 15 16 17
|
||||
## 18 19 20 21 22 23 24
|
||||
## 25 26 27 28 29 30 31
|
||||
# ...
|
||||
# This file is generated by a script for the unix-shell,
|
||||
# see http://rosettacode.org/wiki/Five_weekends#UNIX_Shell
|
||||
|
||||
BEGIN { print("# Month with 5 weekends:")
|
||||
badYears = numW5 = 0;
|
||||
lastW5 = -1
|
||||
}
|
||||
|
||||
0+$2>33 { if( $2>currYear ) { # calendar-header: month, year
|
||||
if( lastW5==numW5 ) {
|
||||
badYears++; sep="\n"
|
||||
if( badYears % 10 ) { sep=" " }
|
||||
bY=bY currYear sep; # collect years in string
|
||||
##print badYears,":", currYear
|
||||
}
|
||||
lastW5=numW5
|
||||
}
|
||||
WE=0; currYear=$2; currMY = $1 " " $2;
|
||||
##print currMY;
|
||||
next
|
||||
}
|
||||
|
||||
/^Mo/ { next } # skip lines with weekday-names
|
||||
|
||||
{ $0 = substr($0,13) } # cut inputline, leave Fr,Sa,Su only
|
||||
|
||||
NF>2 { WE++; # 3 fields left => complete weekend found
|
||||
if( WE>4 ) {
|
||||
numW5++; printf("%4d : %s\n", numW5, currMY)
|
||||
}
|
||||
}
|
||||
|
||||
END { print("# Found", numW5, "month with 5 weekends.")
|
||||
print("# Found", badYears, "years with no month having 5 weekends:")
|
||||
print(bY)
|
||||
}
|
||||
50
Task/Five-weekends/Action-/five-weekends.action
Normal file
50
Task/Five-weekends/Action-/five-weekends.action
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
;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
|
||||
23
Task/Five-weekends/Ada/five-weekends.ada
Normal file
23
Task/Five-weekends/Ada/five-weekends.ada
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
with Ada.Calendar.Formatting; use Ada.Calendar;
|
||||
|
||||
use Ada.Calendar.Formatting;
|
||||
|
||||
procedure Five_Weekends is
|
||||
Months : Natural := 0;
|
||||
begin
|
||||
for Year in Year_Number range 1901..2100 loop
|
||||
for Month in Month_Number range 1..12 loop
|
||||
begin
|
||||
if Day_Of_Week (Formatting.Time_Of (Year, Month, 31)) = Sunday then
|
||||
Put_Line (Year_Number'Image (Year) & Month_Number'Image (Month));
|
||||
Months := Months + 1;
|
||||
end if;
|
||||
exception
|
||||
when Time_Error =>
|
||||
null;
|
||||
end;
|
||||
end loop;
|
||||
end loop;
|
||||
Put_Line ("Number of months:" & Integer'Image (Months));
|
||||
end Five_Weekends;
|
||||
44
Task/Five-weekends/Amazing-Hopper/five-weekends-1.hopper
Normal file
44
Task/Five-weekends/Amazing-Hopper/five-weekends-1.hopper
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
#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
|
||||
35
Task/Five-weekends/Amazing-Hopper/five-weekends-2.hopper
Normal file
35
Task/Five-weekends/Amazing-Hopper/five-weekends-2.hopper
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
#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
|
||||
48
Task/Five-weekends/AppleScript/five-weekends-1.applescript
Normal file
48
Task/Five-weekends/AppleScript/five-weekends-1.applescript
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
set fiveWeekendMonths to {}
|
||||
set noFiveWeekendYears to {}
|
||||
|
||||
set someDate to current date
|
||||
set day of someDate to 1
|
||||
|
||||
repeat with someYear from 1900 to 2100
|
||||
set year of someDate to someYear
|
||||
set foundOne to false
|
||||
repeat with someMonth in {January, March, May, July, ¬
|
||||
August, October, December}
|
||||
set month of someDate to someMonth
|
||||
if weekday of someDate is Friday then
|
||||
set foundOne to true
|
||||
set end of fiveWeekendMonths to ¬
|
||||
(someYear as text) & "-" & (someMonth as text)
|
||||
end
|
||||
end repeat
|
||||
if not foundOne then
|
||||
set end of noFiveWeekendYears to someYear
|
||||
end
|
||||
end repeat
|
||||
|
||||
set text item delimiters to ", "
|
||||
set monthList to ¬
|
||||
(items 1 thru 5 of fiveWeekendMonths as text) & ", ..." & linefeed & ¬
|
||||
" ..., " & (items -5 thru end of fiveWeekendMonths as text)
|
||||
|
||||
set monthCount to count fiveWeekendMonths
|
||||
set yearCount to count noFiveWeekendYears
|
||||
|
||||
set resultText to ¬
|
||||
"Months with five weekends (" & monthCount & "): " & linefeed & ¬
|
||||
" " & monthList & linefeed & linefeed & ¬
|
||||
"Years with no such months (" & yearCount & "): "
|
||||
|
||||
set y to 1
|
||||
repeat while y < yearCount
|
||||
set final to y+11
|
||||
if final > yearCount then
|
||||
set final to yearCount
|
||||
end
|
||||
set resultText to ¬
|
||||
resultText & linefeed & ¬
|
||||
" " & (items y through final of noFiveWeekendYears as text)
|
||||
set y to y + 12
|
||||
end
|
||||
resultText
|
||||
173
Task/Five-weekends/AppleScript/five-weekends-2.applescript
Normal file
173
Task/Five-weekends/AppleScript/five-weekends-2.applescript
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
-- TEST -----------------------------------------------------------------------
|
||||
on run
|
||||
|
||||
fiveWeekends(1900, 2100)
|
||||
|
||||
end run
|
||||
|
||||
-- FIVE WEEKENDS --------------------------------------------------------------
|
||||
|
||||
-- fiveWeekends :: Int -> Int -> Record
|
||||
on fiveWeekends(fromYear, toYear)
|
||||
set lstYears to enumFromTo(fromYear, toYear)
|
||||
|
||||
-- yearMonthString :: (Int, Int) -> String
|
||||
script yearMonthString
|
||||
on |λ|(lstYearMonth)
|
||||
((item 1 of lstYearMonth) as string) & " " & ¬
|
||||
item (item 2 of lstYearMonth) of ¬
|
||||
{"January", "", "March", "", "May", "", ¬
|
||||
"July", "August", "", "October", "", "December"}
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
-- addLongMonthsOfYear :: [(Int, Int)] -> [(Int, Int)]
|
||||
script addLongMonthsOfYear
|
||||
on |λ|(lstYearMonth, intYear)
|
||||
|
||||
-- yearMonth :: Int -> (Int, Int)
|
||||
script yearMonth
|
||||
on |λ|(intMonth)
|
||||
{intYear, intMonth}
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
lstYearMonth & ¬
|
||||
map(yearMonth, my longMonthsStartingFriday(intYear))
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
-- leanYear :: Int -> Bool
|
||||
script leanYear
|
||||
on |λ|(intYear)
|
||||
0 = length of longMonthsStartingFriday(intYear)
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
set lstFullMonths to map(yearMonthString, ¬
|
||||
foldl(addLongMonthsOfYear, {}, lstYears))
|
||||
|
||||
set lstLeanYears to filter(leanYear, lstYears)
|
||||
|
||||
{{|number|:length of lstFullMonths}, ¬
|
||||
{firstFive:(items 1 thru 5 of lstFullMonths)}, ¬
|
||||
{lastFive:(items -5 thru -1 of lstFullMonths)}, ¬
|
||||
{leanYearCount:length of lstLeanYears}, ¬
|
||||
{leanYears:lstLeanYears}}
|
||||
end fiveWeekends
|
||||
|
||||
-- longMonthsStartingFriday :: Int -> [Int]
|
||||
on longMonthsStartingFriday(intYear)
|
||||
|
||||
-- startIsFriday :: Int -> Bool
|
||||
script startIsFriday
|
||||
on |λ|(iMonth)
|
||||
weekday of calendarDate(intYear, iMonth, 1) is Friday
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
filter(startIsFriday, [1, 3, 5, 7, 8, 10, 12])
|
||||
end longMonthsStartingFriday
|
||||
|
||||
-- calendarDate :: Int -> Int -> Int -> Date
|
||||
on calendarDate(intYear, intMonth, intDay)
|
||||
tell (current date)
|
||||
set {its year, its month, its day, its time} to ¬
|
||||
{intYear, intMonth, intDay, 0}
|
||||
return it
|
||||
end tell
|
||||
end calendarDate
|
||||
|
||||
-- GENERIC FUNCTIONS ----------------------------------------------------------
|
||||
|
||||
-- enumFromTo :: Enum a => a -> a -> [a]
|
||||
on enumFromTo(m, n)
|
||||
set {intM, intN} to {fromEnum(m), fromEnum(n)}
|
||||
|
||||
if intM > intN then
|
||||
set d to -1
|
||||
else
|
||||
set d to 1
|
||||
end if
|
||||
set lst to {}
|
||||
if class of m is text then
|
||||
repeat with i from intM to intN by d
|
||||
set end of lst to chr(i)
|
||||
end repeat
|
||||
else
|
||||
repeat with i from intM to intN by d
|
||||
set end of lst to i
|
||||
end repeat
|
||||
end if
|
||||
return lst
|
||||
end enumFromTo
|
||||
|
||||
-- fromEnum :: Enum a => a -> Int
|
||||
on fromEnum(x)
|
||||
set c to class of x
|
||||
if c is boolean then
|
||||
if x then
|
||||
1
|
||||
else
|
||||
0
|
||||
end if
|
||||
else if c is text then
|
||||
if x ≠ "" then
|
||||
id of x
|
||||
else
|
||||
missing value
|
||||
end if
|
||||
else
|
||||
x as integer
|
||||
end if
|
||||
end fromEnum
|
||||
|
||||
-- filter :: (a -> Bool) -> [a] -> [a]
|
||||
on filter(f, xs)
|
||||
tell mReturn(f)
|
||||
set lst to {}
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to item i of xs
|
||||
if |λ|(v, i, xs) then set end of lst to v
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end filter
|
||||
|
||||
-- foldl :: (a -> b -> a) -> a -> [b] -> a
|
||||
on foldl(f, startValue, xs)
|
||||
tell mReturn(f)
|
||||
set v to startValue
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to |λ|(v, item i of xs, i, xs)
|
||||
end repeat
|
||||
return v
|
||||
end tell
|
||||
end foldl
|
||||
|
||||
-- map :: (a -> b) -> [a] -> [b]
|
||||
on map(f, xs)
|
||||
tell mReturn(f)
|
||||
set lng to length of xs
|
||||
set lst to {}
|
||||
repeat with i from 1 to lng
|
||||
set end of lst to |λ|(item i of xs, i, xs)
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end map
|
||||
|
||||
|
||||
-- Lift 2nd class handler function into 1st class script wrapper
|
||||
-- mReturn :: Handler -> Script
|
||||
on mReturn(f)
|
||||
if class of f is script then
|
||||
f
|
||||
else
|
||||
script
|
||||
property |λ| : f
|
||||
end script
|
||||
end if
|
||||
end mReturn
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
{{|number|:201},
|
||||
{firstFive:{"1901 March", "1902 August", "1903 May", "1904 January", "1904 July"}},
|
||||
{lastFive:{"2097 March", "2098 August", "2099 May", "2100 January", "2100 October"}},
|
||||
{leanYearCount:29},
|
||||
{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}}}
|
||||
51
Task/Five-weekends/AppleScript/five-weekends-4.applescript
Normal file
51
Task/Five-weekends/AppleScript/five-weekends-4.applescript
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
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()
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
"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"
|
||||
25
Task/Five-weekends/Arturo/five-weekends.arturo
Normal file
25
Task/Five-weekends/Arturo/five-weekends.arturo
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
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."]
|
||||
37
Task/Five-weekends/AutoHotkey/five-weekends.ahk
Normal file
37
Task/Five-weekends/AutoHotkey/five-weekends.ahk
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
Year := 1900
|
||||
End_Year := 2100
|
||||
31_Day_Months = 01,03,05,07,08,10,12
|
||||
|
||||
While Year <= End_Year
|
||||
{
|
||||
Loop, Parse, 31_Day_Months, CSV
|
||||
{
|
||||
FormatTime, Day, %Year%%A_LoopField%01, dddd
|
||||
IfEqual, Day, Friday
|
||||
{
|
||||
All_Months_With_5_Weekends .= A_LoopField . "/" . Year ", "
|
||||
5_Weekend_Count++
|
||||
Year_Has_5_Weekend_Month := 1
|
||||
}
|
||||
}
|
||||
IfEqual, Year_Has_5_Weekend_Month, 0
|
||||
{
|
||||
All_Years_Without_5_Weekend .= Year ", "
|
||||
No_5_Weekend_Count ++
|
||||
}
|
||||
Year ++
|
||||
Year_Has_5_Weekend_Month := 0
|
||||
}
|
||||
; Trim the spaces and comma off the last item.
|
||||
StringTrimRight, All_Months_With_5_Weekends, All_Months_With_5_Weekends, 5
|
||||
StringTrimRight, All_Years_Without_5_Weekend, All_Years_Without_5_Weekend, 4
|
||||
MsgBox,
|
||||
(
|
||||
Months with 5 day weekends between 1900 and 2100 : %5_Weekend_Count%
|
||||
%All_Months_With_5_Weekends%
|
||||
)
|
||||
MsgBox,
|
||||
(
|
||||
Years with no 5 day weekends between 1900 and 2100 : %No_5_Weekend_Count%
|
||||
%All_Years_Without_5_Weekend%
|
||||
)
|
||||
41
Task/Five-weekends/AutoIt/five-weekends.autoit
Normal file
41
Task/Five-weekends/AutoIt/five-weekends.autoit
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
#include <Date.au3>
|
||||
#include <Array.au3>
|
||||
$array = Five_weekends(1)
|
||||
_ArrayDisplay($array)
|
||||
$array = Five_weekends(2)
|
||||
_ArrayDisplay($array)
|
||||
$array = Five_weekends(3)
|
||||
_ArrayDisplay($array)
|
||||
|
||||
Func Five_weekends($ret = 1)
|
||||
If $ret < 1 Or $ret > 3 Then Return SetError(1, 0, 0)
|
||||
Local $avDateArray[1]
|
||||
Local $avYearArray[1]
|
||||
Local $avMonthArray[1]
|
||||
For $iYear = 1900 To 2100
|
||||
Local $checkyear = False
|
||||
For $iMonth = 1 To 12
|
||||
If _DateDaysInMonth($iYear, $iMonth) <> 31 Then ContinueLoop ; Month has less then 31 Days
|
||||
If _DateToDayOfWeek($iYear, $iMonth, "01") <> 6 Then ContinueLoop ;First Day is not a Friday
|
||||
_ArrayAdd($avMonthArray, $iYear & "-" & _DateToMonth($iMonth))
|
||||
$checkyear = True
|
||||
For $s = 1 To 31
|
||||
Local $Date = _DateToDayOfWeek($iYear, $iMonth, $s)
|
||||
If $Date = 6 Or $Date = 7 Or $Date = 1 Then ; if Date is Friday, Saturday or Sunday
|
||||
_ArrayAdd($avDateArray, $iYear & "\" & StringFormat("%02d", $iMonth) & "\" & StringFormat("%02d", $s))
|
||||
EndIf
|
||||
Next
|
||||
Next
|
||||
If Not $checkyear Then _ArrayAdd($avYearArray, $iYear)
|
||||
Next
|
||||
$avDateArray[0] = UBound($avDateArray) - 1
|
||||
$avYearArray[0] = UBound($avYearArray) - 1
|
||||
$avMonthArray[0] = UBound($avMonthArray) - 1
|
||||
If $ret = 1 Then
|
||||
Return $avDateArray
|
||||
ElseIf $ret = 2 Then
|
||||
Return $avYearArray
|
||||
ElseIf $ret = 3 Then
|
||||
Return $avMonthArray
|
||||
EndIf
|
||||
EndFunc ;==>Five_weekends
|
||||
18
Task/Five-weekends/BBC-BASIC/five-weekends.basic
Normal file
18
Task/Five-weekends/BBC-BASIC/five-weekends.basic
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
INSTALL @lib$+"DATELIB"
|
||||
DIM Month$(12)
|
||||
Month$() = "","January","February","March","April","May","June", \
|
||||
\ "July","August","September","October","November","December"
|
||||
|
||||
num% = 0
|
||||
FOR year% = 1900 TO 2100
|
||||
PRINT ; year% ": " ;
|
||||
oldnum% = num%
|
||||
FOR month% = 1 TO 12
|
||||
IF FN_dim(month%,year%) = 31 IF FN_dow(FN_mjd(1,month%,year%)) = 5 THEN
|
||||
num% += 1
|
||||
PRINT Month$(month%), ;
|
||||
ENDIF
|
||||
NEXT
|
||||
IF num% = oldnum% PRINT "(none)" ELSE PRINT
|
||||
NEXT year%
|
||||
PRINT "Total = " ; num%
|
||||
43
Task/Five-weekends/C++/five-weekends.cpp
Normal file
43
Task/Five-weekends/C++/five-weekends.cpp
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
#include <vector>
|
||||
#include <boost/date_time/gregorian/gregorian.hpp>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
using namespace boost::gregorian ;
|
||||
|
||||
void print( const date &d ) {
|
||||
std::cout << d.year( ) << "-" << d.month( ) << "\n" ;
|
||||
}
|
||||
|
||||
int main( ) {
|
||||
greg_month longmonths[ ] = {Jan, Mar , May , Jul ,
|
||||
Aug , Oct , Dec } ;
|
||||
int monthssize = sizeof ( longmonths ) / sizeof (greg_month ) ;
|
||||
typedef std::vector<date> DateVector ;
|
||||
DateVector weekendmonster ;
|
||||
std::vector<unsigned short> years_without_5we_months ;
|
||||
for ( unsigned short i = 1900 ; i < 2101 ; i++ ) {
|
||||
bool months_found = false ; //does a given year have 5 weekend months ?
|
||||
for ( int j = 0 ; j < monthssize ; j++ ) {
|
||||
date d ( i , longmonths[ j ] , 1 ) ;
|
||||
if ( d.day_of_week( ) == Friday ) { //for the month to have 5 weekends
|
||||
weekendmonster.push_back( d ) ;
|
||||
if ( months_found == false )
|
||||
months_found = true ;
|
||||
}
|
||||
}
|
||||
if ( months_found == false ) {
|
||||
years_without_5we_months.push_back( i ) ;
|
||||
}
|
||||
}
|
||||
std::cout << "Between 1900 and 2100 , there are " << weekendmonster.size( )
|
||||
<< " months with 5 complete weekends!\n" ;
|
||||
std::cout << "Months with 5 complete weekends are:\n" ;
|
||||
std::for_each( weekendmonster.begin( ) , weekendmonster.end( ) , print ) ;
|
||||
std::cout << years_without_5we_months.size( ) << " years had no months with 5 complete weekends!\n" ;
|
||||
std::cout << "These are:\n" ;
|
||||
std::copy( years_without_5we_months.begin( ) , years_without_5we_months.end( ) ,
|
||||
std::ostream_iterator<unsigned short>( std::cout , "\n" ) ) ;
|
||||
std::cout << std::endl ;
|
||||
return 0 ;
|
||||
}
|
||||
37
Task/Five-weekends/C-sharp/five-weekends-1.cs
Normal file
37
Task/Five-weekends/C-sharp/five-weekends-1.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
37
Task/Five-weekends/C-sharp/five-weekends-2.cs
Normal file
37
Task/Five-weekends/C-sharp/five-weekends-2.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
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);
|
||||
}
|
||||
30
Task/Five-weekends/C/five-weekends-1.c
Normal file
30
Task/Five-weekends/C/five-weekends-1.c
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
|
||||
static const char *months[] = {"January", "February", "March", "April", "May",
|
||||
"June", "July", "August", "September", "October", "November", "December"};
|
||||
static int long_months[] = {0, 2, 4, 6, 7, 9, 11};
|
||||
|
||||
int main() {
|
||||
int n = 0, y, i, m;
|
||||
struct tm t = {0};
|
||||
printf("Months with five weekends:\n");
|
||||
for (y = 1900; y <= 2100; y++) {
|
||||
for (i = 0; i < 7; i++) {
|
||||
m = long_months[i];
|
||||
t.tm_year = y-1900;
|
||||
t.tm_mon = m;
|
||||
t.tm_mday = 1;
|
||||
if (mktime(&t) == -1) { /* date not supported */
|
||||
printf("Error: %d %s\n", y, months[m]);
|
||||
continue;
|
||||
}
|
||||
if (t.tm_wday == 5) { /* Friday */
|
||||
printf(" %d %s\n", y, months[m]);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
printf("%d total\n", n);
|
||||
return 0;
|
||||
}
|
||||
40
Task/Five-weekends/C/five-weekends-2.c
Normal file
40
Task/Five-weekends/C/five-weekends-2.c
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int check_month(int y, int m)
|
||||
{
|
||||
char buf[1024], *ptr;
|
||||
int bytes, *a = &m;
|
||||
|
||||
sprintf(buf, "ncal -m %d -M %d", m, y);
|
||||
FILE *fp = popen(buf, "r");
|
||||
if (!fp) return -1;
|
||||
|
||||
bytes = fread(buf, 1, 1024, fp);
|
||||
fclose(fp);
|
||||
buf[bytes] = 0;
|
||||
|
||||
#define check_day(x) \
|
||||
ptr = strstr(buf, x);\
|
||||
if (5 != sscanf(ptr, x" %d %d %d %d %d", a, a, a, a, a)) return 0
|
||||
|
||||
check_day("Fr");
|
||||
check_day("Sa");
|
||||
check_day("Su");
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int y, m, cnt = 0;
|
||||
for (y = 1900; y <= 2100; y++) {
|
||||
for (m = 1; m <= 12; m++) {
|
||||
if (check_month(y, m) <= 0) continue;
|
||||
printf("%d-%02d ", y, m);
|
||||
if (++cnt % 16 == 0) printf("\n");
|
||||
}
|
||||
}
|
||||
printf("\nTotal: %d\n", cnt);
|
||||
|
||||
return 0;
|
||||
}
|
||||
53
Task/Five-weekends/COBOL/five-weekends.cobol
Normal file
53
Task/Five-weekends/COBOL/five-weekends.cobol
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
program-id. five-we.
|
||||
data division.
|
||||
working-storage section.
|
||||
1 wk binary.
|
||||
2 int-date pic 9(8).
|
||||
2 dow pic 9(4).
|
||||
2 friday pic 9(4) value 5.
|
||||
2 mo-sub pic 9(4).
|
||||
2 months-with-5 pic 9(4) value 0.
|
||||
2 years-no-5 pic 9(4) value 0.
|
||||
2 5-we-flag pic 9(4) value 0.
|
||||
88 5-we-true value 1 when false 0.
|
||||
1 31-day-mos pic 9(14) value 01030507081012.
|
||||
1 31-day-table redefines 31-day-mos.
|
||||
2 mo-no occurs 7 pic 99.
|
||||
1 cal-date.
|
||||
2 yr pic 9(4).
|
||||
2 mo pic 9(2).
|
||||
2 da pic 9(2) value 1.
|
||||
procedure division.
|
||||
perform varying yr from 1900 by 1
|
||||
until yr > 2100
|
||||
set 5-we-true to false
|
||||
perform varying mo-sub from 1 by 1
|
||||
until mo-sub > 7
|
||||
move mo-no (mo-sub) to mo
|
||||
compute int-date = function
|
||||
integer-of-date (function numval (cal-date))
|
||||
compute dow = function mod
|
||||
((int-date - 1) 7) + 1
|
||||
if dow = friday
|
||||
perform output-date
|
||||
add 1 to months-with-5
|
||||
set 5-we-true to true
|
||||
end-if
|
||||
end-perform
|
||||
if not 5-we-true
|
||||
add 1 to years-no-5
|
||||
end-if
|
||||
end-perform
|
||||
perform output-counts
|
||||
stop run
|
||||
.
|
||||
|
||||
output-counts.
|
||||
display "Months with 5 weekends: " months-with-5
|
||||
display "Years without 5 weekends: " years-no-5
|
||||
.
|
||||
|
||||
output-date.
|
||||
display yr "-" mo
|
||||
.
|
||||
end program five-we.
|
||||
3
Task/Five-weekends/Ceylon/five-weekends-1.ceylon
Normal file
3
Task/Five-weekends/Ceylon/five-weekends-1.ceylon
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
module rosetta.fiveweekends "1.0.0" {
|
||||
import ceylon.time "1.2.2";
|
||||
}
|
||||
55
Task/Five-weekends/Ceylon/five-weekends-2.ceylon
Normal file
55
Task/Five-weekends/Ceylon/five-weekends-2.ceylon
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import ceylon.time {
|
||||
date,
|
||||
Date
|
||||
}
|
||||
import ceylon.time.base {
|
||||
january,
|
||||
december,
|
||||
friday,
|
||||
Month
|
||||
}
|
||||
|
||||
shared void run() {
|
||||
[Date[],Integer[]] result = fiveWeekendsRecursive();
|
||||
|
||||
value fiveWeekendFirstOfMonths = result[0];
|
||||
Integer[] yearsWithNoFiveWeekendMonths = result[1];
|
||||
|
||||
print("# five weekend months = ``fiveWeekendFirstOfMonths.size``");
|
||||
print("# years without five weekend months = ``yearsWithNoFiveWeekendMonths.size``");
|
||||
yearsWithNoFiveWeekendMonths.each(print);
|
||||
}
|
||||
|
||||
[Date[], Integer[]] fiveWeekendsRecursive()
|
||||
=> fiveWeekendsRecursiveInner{ year = 1900;
|
||||
month = january;
|
||||
fiveWeekendFirstOfMonths = [];
|
||||
yearsWithNoFiveWeekendMonths = []; };
|
||||
|
||||
[Date[], Integer[]] fiveWeekendsRecursiveInner(Integer year,
|
||||
Month month,
|
||||
Date[] fiveWeekendFirstOfMonths,
|
||||
Integer[] yearsWithNoFiveWeekendMonths) {
|
||||
if (year > 2100) {
|
||||
return [fiveWeekendFirstOfMonths,yearsWithNoFiveWeekendMonths];
|
||||
}
|
||||
|
||||
Date firstOfMonth = date{ year = year; month = month; day = 1; };
|
||||
|
||||
Boolean isFiveWeekendMonth =
|
||||
(month.numberOfDays() == 31 && friday == firstOfMonth.dayOfWeek);
|
||||
|
||||
Boolean hasNoFiveWeekends =
|
||||
month == december &&
|
||||
! isFiveWeekendMonth &&
|
||||
fiveWeekendFirstOfMonths.filter((date) => date.year == year).size == 0;
|
||||
|
||||
return fiveWeekendsRecursiveInner(if (month == december) then year+1 else year,
|
||||
if (month == december) then january else month.plusMonths(1),
|
||||
if (isFiveWeekendMonth)
|
||||
then fiveWeekendFirstOfMonths.withTrailing(firstOfMonth)
|
||||
else fiveWeekendFirstOfMonths,
|
||||
if (hasNoFiveWeekends)
|
||||
then yearsWithNoFiveWeekendMonths.withTrailing(year)
|
||||
else yearsWithNoFiveWeekendMonths);
|
||||
}
|
||||
11
Task/Five-weekends/Clojure/five-weekends.clj
Normal file
11
Task/Five-weekends/Clojure/five-weekends.clj
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(import java.util.GregorianCalendar
|
||||
java.text.DateFormatSymbols)
|
||||
|
||||
(->> (for [year (range 1900 2101)
|
||||
month [0 2 4 6 7 9 11] ;; 31 day months
|
||||
:let [cal (GregorianCalendar. year month 1)
|
||||
day (.get cal GregorianCalendar/DAY_OF_WEEK)]
|
||||
:when (= day GregorianCalendar/FRIDAY)]
|
||||
(println month "-" year))
|
||||
count
|
||||
(println "Total Months: " ,))
|
||||
40
Task/Five-weekends/CoffeeScript/five-weekends-1.coffee
Normal file
40
Task/Five-weekends/CoffeeScript/five-weekends-1.coffee
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
startsOnFriday = (month, year) ->
|
||||
# 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
|
||||
new Date(year, month, 1).getDay() == 5
|
||||
|
||||
has31Days = (month, year) ->
|
||||
new Date(year, month, 31).getDate() == 31
|
||||
|
||||
checkMonths = (year) ->
|
||||
month = undefined
|
||||
count = 0
|
||||
month = 0
|
||||
while month < 12
|
||||
if startsOnFriday(month, year) and has31Days(month, year)
|
||||
count += 1
|
||||
console.log year + ' ' + month + ''
|
||||
month += 1
|
||||
count
|
||||
|
||||
fiveWeekends = ->
|
||||
startYear = 1900
|
||||
endYear = 2100
|
||||
year = undefined
|
||||
monthTotal = 0
|
||||
yearsWithoutFiveWeekends = []
|
||||
total = 0
|
||||
year = startYear
|
||||
while year <= endYear
|
||||
monthTotal = checkMonths(year)
|
||||
total += monthTotal
|
||||
# extra credit
|
||||
if monthTotal == 0
|
||||
yearsWithoutFiveWeekends.push year
|
||||
year += 1
|
||||
console.log 'Total number of months: ' + total + ''
|
||||
console.log ''
|
||||
console.log yearsWithoutFiveWeekends + ''
|
||||
console.log 'Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + ''
|
||||
return
|
||||
|
||||
fiveWeekends()
|
||||
30
Task/Five-weekends/CoffeeScript/five-weekends-2.coffee
Normal file
30
Task/Five-weekends/CoffeeScript/five-weekends-2.coffee
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
1901 2
|
||||
1902 7
|
||||
1903 4
|
||||
1904 0
|
||||
1904 6
|
||||
1905 11
|
||||
1907 2
|
||||
1908 4
|
||||
1909 0
|
||||
1909 9
|
||||
1910 6
|
||||
1911 11
|
||||
1912 2
|
||||
1913 7
|
||||
1914 4
|
||||
1915 0
|
||||
1915 9
|
||||
1916 11
|
||||
1918 2
|
||||
1919 7
|
||||
1920 9
|
||||
1921 6
|
||||
1922 11
|
||||
1924 7
|
||||
..
|
||||
|
||||
Total number of months: 201
|
||||
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
|
||||
|
||||
Years with no five-weekend months: 29
|
||||
46
Task/Five-weekends/Common-Lisp/five-weekends.lisp
Normal file
46
Task/Five-weekends/Common-Lisp/five-weekends.lisp
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
;; Given a date, get the day of the week. Adapted from
|
||||
;; http://lispcookbook.github.io/cl-cookbook/dates_and_times.html
|
||||
|
||||
(defun day-of-week (day month year)
|
||||
(nth-value
|
||||
6
|
||||
(decode-universal-time
|
||||
(encode-universal-time 0 0 0 day month year 0)
|
||||
0)))
|
||||
|
||||
(defparameter *long-months* '(1 3 5 7 8 10 12))
|
||||
|
||||
(defun sundayp (day month year)
|
||||
(= (day-of-week day month year) 6))
|
||||
|
||||
(defun ends-on-sunday-p (month year)
|
||||
(sundayp 31 month year))
|
||||
|
||||
;; We use the "long month that ends on Sunday" rule.
|
||||
(defun has-five-weekends-p (month year)
|
||||
(and (member month *long-months*)
|
||||
(ends-on-sunday-p month year)))
|
||||
|
||||
;; For the extra credit problem.
|
||||
(defun has-at-least-one-five-weekend-month-p (year)
|
||||
(let ((flag nil))
|
||||
(loop for month in *long-months* do
|
||||
(if (has-five-weekends-p month year)
|
||||
(setf flag t)))
|
||||
flag))
|
||||
|
||||
(defun solve-it ()
|
||||
(let ((good-months '())
|
||||
(bad-years 0))
|
||||
(loop for year from 1900 to 2100 do
|
||||
;; First form in the PROGN is for the extra credit.
|
||||
(progn (unless (has-at-least-one-five-weekend-month-p year)
|
||||
(incf bad-years))
|
||||
(loop for month in *long-months* do
|
||||
(when (has-five-weekends-p month year)
|
||||
(push (list month year) good-months)))))
|
||||
(let ((len (length good-months)))
|
||||
(format t "~A months have five weekends.~%" len)
|
||||
(format t "First 5 months: ~A~%" (subseq good-months (- len 5) len))
|
||||
(format t "Last 5 months: ~A~%" (subseq good-months 0 5))
|
||||
(format t "Years without a five-weekend month: ~A~%" bad-years))))
|
||||
31
Task/Five-weekends/D/five-weekends-1.d
Normal file
31
Task/Five-weekends/D/five-weekends-1.d
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import std.stdio, std.datetime, std.algorithm, std.range;
|
||||
|
||||
Date[] m5w(in Date start, in Date end) pure /*nothrow*/ {
|
||||
typeof(return) res;
|
||||
// adjust to 1st day
|
||||
for (Date when = Date(start.year, start.month, 1);
|
||||
when < end;
|
||||
when.add!"months"(1))
|
||||
// Such month must have 3+4*7 days and start at friday
|
||||
// for 5 FULL weekends.
|
||||
if (when.daysInMonth == 31 &&
|
||||
when.dayOfWeek == DayOfWeek.fri)
|
||||
res ~= when;
|
||||
return res;
|
||||
}
|
||||
|
||||
bool noM5wByYear(in int year) pure {
|
||||
return m5w(Date(year, 1, 1), Date(year, 12, 31)).empty;
|
||||
}
|
||||
|
||||
void main() {
|
||||
immutable m = m5w(Date(1900, 1, 1), Date(2100, 12, 31));
|
||||
writeln("There are ", m.length,
|
||||
" months of which the first and last five are:");
|
||||
foreach (d; m[0 .. 5] ~ m[$ - 5 .. $])
|
||||
writeln(d.toSimpleString()[0 .. $ - 3]);
|
||||
|
||||
immutable n = iota(1900, 2101).filter!noM5wByYear().walkLength();
|
||||
writefln("\nThere are %d years in the range that do not have " ~
|
||||
"months with five weekends.", n);
|
||||
}
|
||||
35
Task/Five-weekends/D/five-weekends-2.d
Normal file
35
Task/Five-weekends/D/five-weekends-2.d
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
void main() {
|
||||
import std.stdio, std.datetime, std.traits;
|
||||
|
||||
enum first_year = 1900;
|
||||
enum last_year = 2100;
|
||||
|
||||
uint totalNo5Weekends;
|
||||
immutable(Date)[] fiveWeekendMonths;
|
||||
foreach (immutable year; first_year .. last_year + 1) {
|
||||
bool has5Weekends = false;
|
||||
|
||||
foreach (immutable month; EnumMembers!Month) {
|
||||
immutable firstDay = Date(year, month, 1);
|
||||
if (firstDay.daysInMonth == 31 &&
|
||||
firstDay.dayOfWeek == DayOfWeek.fri) {
|
||||
has5Weekends = true;
|
||||
fiveWeekendMonths ~= firstDay;
|
||||
}
|
||||
}
|
||||
|
||||
if (!has5Weekends)
|
||||
totalNo5Weekends++;
|
||||
}
|
||||
|
||||
writefln("Total 5-weekend months between %d and %d: %d",
|
||||
first_year, last_year, fiveWeekendMonths.length);
|
||||
foreach (immutable date; fiveWeekendMonths[0 .. 5])
|
||||
writeln(date.month, ' ', date.year);
|
||||
"...".writeln;
|
||||
foreach (immutable date; fiveWeekendMonths[$ - 5 .. $])
|
||||
writeln(date.month, ' ', date.year);
|
||||
|
||||
writeln("\nTotal number of years with no 5-weekend months: ",
|
||||
totalNo5Weekends);
|
||||
}
|
||||
13
Task/Five-weekends/Dart/five-weekends.dart
Normal file
13
Task/Five-weekends/Dart/five-weekends.dart
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
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');
|
||||
}
|
||||
34
Task/Five-weekends/Delphi/five-weekends.delphi
Normal file
34
Task/Five-weekends/Delphi/five-weekends.delphi
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
program FiveWeekends;
|
||||
|
||||
{$APPTYPE CONSOLE}
|
||||
|
||||
uses SysUtils, DateUtils;
|
||||
|
||||
var
|
||||
lMonth, lYear: Integer;
|
||||
lDate: TDateTime;
|
||||
lFiveWeekendCount: Integer;
|
||||
lYearsWithout: Integer;
|
||||
lFiveWeekendFound: Boolean;
|
||||
begin
|
||||
for lYear := 1900 to 2100 do
|
||||
begin
|
||||
lFiveWeekendFound := False;
|
||||
for lMonth := 1 to 12 do
|
||||
begin
|
||||
lDate := EncodeDate(lYear, lMonth, 1);
|
||||
if (DaysInMonth(lDate) = 31) and (DayOfTheWeek(lDate) = DayFriday) then
|
||||
begin
|
||||
Writeln(FormatDateTime('mmm yyyy', lDate));
|
||||
Inc(lFiveWeekendCount);
|
||||
lFiveWeekendFound := True;
|
||||
end;
|
||||
end;
|
||||
if not lFiveWeekendFound then
|
||||
Inc(lYearsWithout);
|
||||
end;
|
||||
|
||||
Writeln;
|
||||
Writeln(Format('Months with 5 weekends: %d', [lFiveWeekendCount]));
|
||||
Writeln(Format('Years with no 5 weekend months: %d', [lYearsWithout]));
|
||||
end.
|
||||
36
Task/Five-weekends/ERRE/five-weekends.erre
Normal file
36
Task/Five-weekends/ERRE/five-weekends.erre
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
PROGRAM FIVE_WEEKENDS
|
||||
|
||||
DIM M$[12]
|
||||
|
||||
PROCEDURE MODULO(X,Y->MD)
|
||||
IF Y=0 THEN
|
||||
MD=X
|
||||
ELSE
|
||||
MD=X-Y*INT(X/Y)
|
||||
END IF
|
||||
END PROCEDURE
|
||||
|
||||
PROCEDURE WD(M,D,Y->RES%)
|
||||
IF M=1 OR M=2 THEN
|
||||
M+=12
|
||||
Y-=1
|
||||
END IF
|
||||
MODULO(365*Y+INT(Y/4)-INT(Y/100)+INT(Y/400)+D+INT((153*M+8)/5),7->RES)
|
||||
RES%=RES+1.0
|
||||
END PROCEDURE
|
||||
|
||||
BEGIN
|
||||
M$[]=("","JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER")
|
||||
PRINT(CHR$(12);) ! CLS
|
||||
FOR YEAR=1900 TO 2100 DO
|
||||
FOREACH MONTH IN (1,3,5,7,8,10,12) DO ! months with 31 days
|
||||
WD(MONTH,1,YEAR->RES%)
|
||||
IF RES%=6 THEN ! day #6 is Friday
|
||||
PRINT(YEAR;": ";M$[MONTH])
|
||||
CNT%=CNT%+1
|
||||
! IF CNT% MOD 20=0 THEN GET(K$) END IF ! press a key for next page
|
||||
END IF
|
||||
END FOR
|
||||
END FOR
|
||||
PRINT("Total =";CNT%)
|
||||
END PROGRAM
|
||||
18
Task/Five-weekends/Elixir/five-weekends.elixir
Normal file
18
Task/Five-weekends/Elixir/five-weekends.elixir
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
defmodule Date do
|
||||
@months { "January", "February", "March", "April", "May", "June",
|
||||
"July", "August", "September", "October", "November", "December" }
|
||||
|
||||
def five_weekends(year) do
|
||||
for m <-[1,3,5,7,8,10,12], :calendar.day_of_the_week(year, m, 31) == 7, do: elem(@months, m-1)
|
||||
end
|
||||
end
|
||||
|
||||
months = Enum.map(1900..2100, fn year -> {year, Date.five_weekends(year)} end)
|
||||
{none, months5} = Enum.partition(months, fn {_,m} -> Enum.empty?(m) end)
|
||||
count = Enum.reduce(months5, 0, fn {year, months}, acc ->
|
||||
IO.puts "#{year} : #{Enum.join(months, ", ")}"
|
||||
acc + length(months)
|
||||
end)
|
||||
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)}"
|
||||
29
Task/Five-weekends/Erlang/five-weekends-1.erl
Normal file
29
Task/Five-weekends/Erlang/five-weekends-1.erl
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env escript
|
||||
%%
|
||||
%% Calculate number of months with five weekends between years 1900-2100
|
||||
%%
|
||||
main(_) ->
|
||||
Years = [ [{Y,M} || M <- lists:seq(1,12)] || Y <- lists:seq(1900,2100) ],
|
||||
{CountedYears, {Has5W, TotM5W}} = lists:mapfoldl(
|
||||
fun(Months, {Has5W, Tot}) ->
|
||||
WithFive = [M || M <- Months, has_five(M)],
|
||||
CountM5W = length(WithFive),
|
||||
{{Months,CountM5W}, {Has5W++WithFive, Tot+CountM5W}}
|
||||
end, {[], 0}, Years),
|
||||
io:format("There are ~p months with five full weekends.~n"
|
||||
"Showing top and bottom 5:~n",
|
||||
[TotM5W]),
|
||||
lists:map(fun({Y,M}) -> io:format("~p-~p~n", [Y,M]) end,
|
||||
lists:sublist(Has5W,1,5) ++ lists:nthtail(TotM5W-5, Has5W)),
|
||||
No5W = [Y || {[{Y,_M}|_], 0} <- CountedYears],
|
||||
io:format("The following ~p years do NOT have any five-weekend months:~n",
|
||||
[length(No5W)]),
|
||||
lists:map(fun(Y) -> io:format("~p~n", [Y]) end, No5W).
|
||||
|
||||
has_five({Year, Month}) ->
|
||||
has_five({Year, Month}, calendar:last_day_of_the_month(Year, Month)).
|
||||
|
||||
has_five({Year, Month}, Days) when Days =:= 31 ->
|
||||
calendar:day_of_the_week({Year, Month, 1}) =:= 5;
|
||||
has_five({_Year, _Month}, _DaysNot31) ->
|
||||
false.
|
||||
51
Task/Five-weekends/Erlang/five-weekends-2.erl
Normal file
51
Task/Five-weekends/Erlang/five-weekends-2.erl
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
-module(five_weekends).
|
||||
|
||||
-export([report/0, print_5w_month/1, print_year_with_no_5w_month/1]).
|
||||
|
||||
report() ->
|
||||
Years = make_nested_period_list(1900, 2100),
|
||||
{CountedYears, {All5WMonths, CountOf5WMonths}} = lists:mapfoldl(
|
||||
fun(SingleYearSublist, {All5WMonths, CountOf5WMonths}) ->
|
||||
MonthsWith5W = [Month || Month <- SingleYearSublist, if_has_5w(Month)],
|
||||
CountOf5WMonthsFor1Year = length(MonthsWith5W),
|
||||
{ % Result of map for this year sublist:
|
||||
{SingleYearSublist,CountOf5WMonthsFor1Year},
|
||||
% Accumulate total result for our fold:
|
||||
{All5WMonths ++ MonthsWith5W, CountOf5WMonths + CountOf5WMonthsFor1Year}
|
||||
}
|
||||
end, {[], 0}, Years),
|
||||
io:format("There are ~p months with five full weekends.~n"
|
||||
"Showing top and bottom 5:~n",
|
||||
[CountOf5WMonths]),
|
||||
lists:map(fun print_5w_month/1, take_nth_first_and_last(5, All5WMonths)),
|
||||
YearsWithout5WMonths = find_years_without_5w_months(CountedYears),
|
||||
io:format("The following ~p years do NOT have any five-weekend months:~n",
|
||||
[length(YearsWithout5WMonths)]),
|
||||
lists:map(fun print_year_with_no_5w_month/1, YearsWithout5WMonths).
|
||||
|
||||
make_nested_period_list(FromYear, ToYear) ->
|
||||
[ make_monthtuple_sublist_for_year(Year) || Year <- lists:seq(FromYear, ToYear) ].
|
||||
|
||||
make_monthtuple_sublist_for_year(Year) ->
|
||||
[ {Year, Month} || Month <- lists:seq(1,12) ].
|
||||
|
||||
if_has_5w({Year, Month}) ->
|
||||
if_has_5w({Year, Month}, calendar:last_day_of_the_month(Year, Month)).
|
||||
|
||||
if_has_5w({Year, Month}, Days) when Days =:= 31 ->
|
||||
calendar:day_of_the_week({Year, Month, 1}) =:= 5;
|
||||
if_has_5w({_Year, _Month}, _DaysNot31) ->
|
||||
false.
|
||||
|
||||
print_5w_month({Year, Month}) ->
|
||||
io:format("~p-~p~n", [Year, Month]).
|
||||
|
||||
print_year_with_no_5w_month(Year) ->
|
||||
io:format("~p~n", [Year]).
|
||||
|
||||
take_nth_first_and_last(N, List) ->
|
||||
Len = length(List),
|
||||
lists:sublist(List, 1, N) ++ lists:nthtail(Len - N, List).
|
||||
|
||||
find_years_without_5w_months(List) ->
|
||||
[Y || {[{Y,_M}|_], 0} <- List].
|
||||
42
Task/Five-weekends/Euphoria/five-weekends.euphoria
Normal file
42
Task/Five-weekends/Euphoria/five-weekends.euphoria
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
--Five Weekend task from Rosetta Code wiki
|
||||
--User:Lnettnay
|
||||
|
||||
include std/datetime.e
|
||||
|
||||
atom numbermonths = 0
|
||||
sequence longmonths = {1, 3, 5, 7, 8, 10, 12}
|
||||
sequence yearsmonths = {}
|
||||
atom none = 0
|
||||
datetime dt
|
||||
|
||||
for year = 1900 to 2100 do
|
||||
atom flag = 0
|
||||
for month = 1 to length(longmonths) do
|
||||
dt = new(year, longmonths[month], 1)
|
||||
if weeks_day(dt) = 6 then --Friday is day 6
|
||||
flag = 1
|
||||
numbermonths += 1
|
||||
yearsmonths = append(yearsmonths, {year, longmonths[month]})
|
||||
end if
|
||||
end for
|
||||
|
||||
if flag = 0 then
|
||||
none += 1
|
||||
end if
|
||||
end for
|
||||
|
||||
puts(1, "Number of months with five full weekends from 1900 to 2100 = ")
|
||||
? numbermonths
|
||||
|
||||
puts(1, "First five and last five years, months\n")
|
||||
|
||||
for count = 1 to 5 do
|
||||
? yearsmonths[count]
|
||||
end for
|
||||
|
||||
for count = length(yearsmonths) - 4 to length(yearsmonths) do
|
||||
? yearsmonths[count]
|
||||
end for
|
||||
|
||||
puts(1, "Number of years that have no months with five full weekends = ")
|
||||
? none
|
||||
34
Task/Five-weekends/F-Sharp/five-weekends.fs
Normal file
34
Task/Five-weekends/F-Sharp/five-weekends.fs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
open System
|
||||
|
||||
[<EntryPoint>]
|
||||
let main argv =
|
||||
let (yearFrom, yearTo) = (1900, 2100)
|
||||
|
||||
let monthsWith5We year =
|
||||
[1; 3; 5; 7; 8; 10; 12] |>
|
||||
List.filter (fun month -> DateTime(year, month, 1).DayOfWeek = DayOfWeek.Friday)
|
||||
|
||||
let ym5we =
|
||||
[yearFrom .. yearTo]
|
||||
|> List.map (fun year -> year, (monthsWith5We year))
|
||||
|
||||
let countMonthsWith5We =
|
||||
ym5we
|
||||
|> List.sumBy (snd >> List.length)
|
||||
|
||||
let countYearsWithout5WeMonths =
|
||||
ym5we
|
||||
|> List.sumBy (snd >> List.isEmpty >> (function|true->1|_->0))
|
||||
|
||||
let allMonthsWith5we =
|
||||
ym5we
|
||||
|> List.filter (snd >> List.isEmpty >> not)
|
||||
|
||||
printfn "%d months in the range of years from %d to %d have 5 weekends."
|
||||
countMonthsWith5We yearFrom yearTo
|
||||
printfn "%d years in the range of years from %d to %d have no month with 5 weekends."
|
||||
countYearsWithout5WeMonths yearFrom yearTo
|
||||
printfn "Months with 5 weekends: %A ... %A"
|
||||
(List.take 5 allMonthsWith5we)
|
||||
(List.take 5 (List.skip ((List.length allMonthsWith5we) - 5) allMonthsWith5we))
|
||||
0
|
||||
16
Task/Five-weekends/Factor/five-weekends.factor
Normal file
16
Task/Five-weekends/Factor/five-weekends.factor
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
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
|
||||
57
Task/Five-weekends/Fortran/five-weekends.f
Normal file
57
Task/Five-weekends/Fortran/five-weekends.f
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
program Five_weekends
|
||||
implicit none
|
||||
|
||||
integer :: m, year, nfives = 0, not5 = 0
|
||||
logical :: no5weekend
|
||||
|
||||
type month
|
||||
integer :: n
|
||||
character(3) :: name
|
||||
end type month
|
||||
|
||||
type(month) :: month31(7)
|
||||
|
||||
month31(1) = month(13, "Jan")
|
||||
month31(2) = month(3, "Mar")
|
||||
month31(3) = month(5, "May")
|
||||
month31(4) = month(7, "Jul")
|
||||
month31(5) = month(8, "Aug")
|
||||
month31(6) = month(10, "Oct")
|
||||
month31(7) = month(12, "Dec")
|
||||
|
||||
do year = 1900, 2100
|
||||
no5weekend = .true.
|
||||
do m = 1, size(month31)
|
||||
if(month31(m)%n == 13) then
|
||||
if(Day_of_week(1, month31(m)%n, year-1) == 6) then
|
||||
write(*, "(a3, i5)") month31(m)%name, year
|
||||
nfives = nfives + 1
|
||||
no5weekend = .false.
|
||||
end if
|
||||
else
|
||||
if(Day_of_week(1, month31(m)%n, year) == 6) then
|
||||
write(*,"(a3, i5)") month31(m)%name, year
|
||||
nfives = nfives + 1
|
||||
no5weekend = .false.
|
||||
end if
|
||||
end if
|
||||
end do
|
||||
if(no5weekend) not5 = not5 + 1
|
||||
end do
|
||||
|
||||
write(*, "(a, i0)") "Number of months with five weekends between 1900 and 2100 = ", nfives
|
||||
write(*, "(a, i0)") "Number of years between 1900 and 2100 with no five weekend months = ", not5
|
||||
|
||||
contains
|
||||
|
||||
function Day_of_week(d, m, y)
|
||||
integer :: Day_of_week
|
||||
integer, intent(in) :: d, m, y
|
||||
integer :: j, k
|
||||
|
||||
j = y / 100
|
||||
k = mod(y, 100)
|
||||
Day_of_week = mod(d + (m+1)*26/10 + k + k/4 + j/4 + 5*j, 7)
|
||||
|
||||
end function Day_of_week
|
||||
end program Five_weekends
|
||||
61
Task/Five-weekends/FreeBASIC/five-weekends.basic
Normal file
61
Task/Five-weekends/FreeBASIC/five-weekends.basic
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
' version 23-06-2015
|
||||
' compile with: fbc -s console
|
||||
|
||||
Function wd(m As Integer, d As Integer, y As Integer) As Integer
|
||||
' Zellerish
|
||||
' 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday
|
||||
' 4 = Thursday, 5 = Friday, 6 = Saturday
|
||||
|
||||
If m < 3 Then ' If m = 1 Or m = 2 Then
|
||||
m += 12
|
||||
y -= 1
|
||||
End If
|
||||
Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7
|
||||
End Function
|
||||
|
||||
' ------=< MAIN >=------
|
||||
' only months with 31 day can have five weekends
|
||||
' these months are: January, March, May, July, August, October, December
|
||||
' in nr: 1, 3, 5, 7, 8, 10, 12
|
||||
' the 1e day needs to be on a friday (= 5)
|
||||
|
||||
Dim As String month_names(1 To 12) => {"January","February","March",_
|
||||
"April","May","June","July","August",_
|
||||
"September","October","November","December"}
|
||||
Dim As Integer m, yr, total, i, j, yr_without(200)
|
||||
Dim As String answer
|
||||
|
||||
For yr = 1900 To 2100 ' Gregorian calendar
|
||||
answer = ""
|
||||
For m = 1 To 12 Step 2
|
||||
If m = 9 Then m = 8
|
||||
If wd(m , 1 , yr) = 5 Then
|
||||
answer = answer + month_names(m) + ", "
|
||||
total = total + 1
|
||||
End If
|
||||
Next
|
||||
If answer <> "" Then
|
||||
Print Using "#### | "; yr;
|
||||
Print Left(answer, Len(answer) -2) ' get rid of extra " ,"
|
||||
Else
|
||||
i = i + 1
|
||||
yr_without(i) = yr
|
||||
End If
|
||||
Next
|
||||
|
||||
Print
|
||||
Print "nr of month for 1900 to 2100 that has five weekends";total
|
||||
Print
|
||||
Print i;" years don't have months with five weekends"
|
||||
|
||||
For j = 1 To i
|
||||
Print yr_without(j); " ";
|
||||
If j Mod 8 = 0 Then Print
|
||||
Next
|
||||
Print
|
||||
|
||||
' empty keyboard buffer
|
||||
While InKey <> "" : Wend
|
||||
Print : Print "hit any key to end program"
|
||||
Sleep
|
||||
End
|
||||
33
Task/Five-weekends/GAP/five-weekends.gap
Normal file
33
Task/Five-weekends/GAP/five-weekends.gap
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# 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
|
||||
FiveWeekends := function(y1, y2)
|
||||
local L, yL, badL, d, m, y;
|
||||
L := [ ];
|
||||
badL := [ ];
|
||||
for y in [y1 .. y2] do
|
||||
yL := [ ];
|
||||
for m in [1, 3, 5, 7, 8, 10, 12] do
|
||||
if WeekDay([1, m, y]) = "Fri" then
|
||||
d := StringDate([1, m, y]);
|
||||
Add(yL, d{[4 .. 11]});
|
||||
fi;
|
||||
od;
|
||||
if Length(yL) = 0 then
|
||||
Add(badL, y);
|
||||
else
|
||||
Append(L, yL);
|
||||
fi;
|
||||
od;
|
||||
return [ L, badL ];
|
||||
end;
|
||||
|
||||
r := FiveWeekends(1900, 2100);;
|
||||
n := Length(r[1]);
|
||||
# 201
|
||||
Length(r[2]);
|
||||
# 29
|
||||
r[1]{[1 .. 5]};
|
||||
# [ "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" ]
|
||||
38
Task/Five-weekends/Gambas/five-weekends.gambas
Normal file
38
Task/Five-weekends/Gambas/five-weekends.gambas
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
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
|
||||
Dim siYear, siMonth, siCount As Short 'Various variables
|
||||
Dim dDay As Date 'To store the day to check
|
||||
Dim sTemp As String 'Temp string
|
||||
|
||||
For siYear = 1900 To 2100 'Loop through each year
|
||||
For siMonth = 0 To 6 'Loop through each 31 day month
|
||||
dDay = Date(siYear, aMonth[siMonth], 1) 'Get the date of the 1st of the month
|
||||
If WeekDay(dDay) = 5 Then aMMStore.Add(Format(dDay, "mmmm yyyy")) 'If the 1st is a Friday then store the result
|
||||
Next
|
||||
Next
|
||||
|
||||
For Each sTemp In aMMStore 'For each item in the stored array..
|
||||
Inc siCount 'Increase siCount
|
||||
If siCount < 6 Then Print aMMStore[siCount] 'If 1 of the 1st 5 dates then print it
|
||||
If siCount = 6 Then Print String$(14, "-") 'Print a separator
|
||||
If siCount > aMMStore.Max - 4 Then Print aMMStore[siCount - 1] 'If 1 of the last 5 dates then print it
|
||||
Next
|
||||
|
||||
Print gb.NewLine & "Total months = " & Str(siCount) 'Print the number of months found
|
||||
|
||||
siCount = 0 'Reset siCount
|
||||
sTemp = aMMStore.Join(",") 'Put all the stored dates in one string joined by commas
|
||||
aMMStore.Clear 'Clear the store for reuse
|
||||
|
||||
For siYear = 1900 To 2100 'Loop through each year
|
||||
If Not InStr(sTemp, Str(siYear)) Then 'If the year is not in the stored string then..
|
||||
Inc siCount 'Increase siCount (Amount of years that don't have 5 weekend months)
|
||||
aMMStore.Add(Str(siYear)) 'Add to the store
|
||||
End If
|
||||
Next
|
||||
|
||||
Print gb.NewLine & "There are " & Str(siCount) &
|
||||
" 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
|
||||
50
Task/Five-weekends/Go/five-weekends.go
Normal file
50
Task/Five-weekends/Go/five-weekends.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var n int // for task item 2
|
||||
var first, last time.Time // for task item 3
|
||||
haveNone := make([]int, 0, 29) // for extra credit
|
||||
fmt.Println("Months with five weekends:") // for task item 1
|
||||
for year := 1900; year <= 2100; year++ {
|
||||
var hasOne bool // for extra credit
|
||||
for _, month := range []time.Month{1, 3, 5, 7, 8, 10, 12} {
|
||||
t := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
|
||||
if t.Weekday() == time.Friday {
|
||||
// task item 1: show month
|
||||
fmt.Println(" ", t.Format("2006 January"))
|
||||
n++
|
||||
hasOne = true
|
||||
last = t
|
||||
if first.IsZero() {
|
||||
first = t
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasOne {
|
||||
haveNone = append(haveNone, year)
|
||||
}
|
||||
}
|
||||
fmt.Println(n, "total\n") // task item 2: number of months
|
||||
// task item 3
|
||||
fmt.Println("First five dates of weekends:")
|
||||
for i := 0; i < 5; i++ {
|
||||
fmt.Println(" ", first.Format("Monday, January 2, 2006"))
|
||||
first = first.Add(7 * 24 * time.Hour)
|
||||
}
|
||||
fmt.Println("Last five dates of weekends:")
|
||||
for i := 0; i < 5; i++ {
|
||||
fmt.Println(" ", last.Format("Monday, January 2, 2006"))
|
||||
last = last.Add(7 * 24 * time.Hour)
|
||||
}
|
||||
// extra credit
|
||||
fmt.Println("\nYears with no months with five weekends:")
|
||||
for _, y := range haveNone {
|
||||
fmt.Println(" ", y)
|
||||
}
|
||||
fmt.Println(len(haveNone), "total")
|
||||
}
|
||||
17
Task/Five-weekends/Groovy/five-weekends-1.groovy
Normal file
17
Task/Five-weekends/Groovy/five-weekends-1.groovy
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
enum Day {
|
||||
Sun, Mon, Tue, Wed, Thu, Fri, Sat
|
||||
static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) }
|
||||
}
|
||||
|
||||
def date = Date.&parse.curry('yyyy-M-dd')
|
||||
def isLongMonth = { firstDay -> (firstDay + 31).format('dd') == '01'}
|
||||
|
||||
def fiveWeekends = { years ->
|
||||
years.collect { year ->
|
||||
(1..12).collect { month ->
|
||||
date("${year}-${month}-01")
|
||||
}.findAll { firstDay ->
|
||||
isLongMonth(firstDay) && Day.valueOf(firstDay) == Day.Fri
|
||||
}
|
||||
}.flatten()
|
||||
}
|
||||
5
Task/Five-weekends/Groovy/five-weekends-2.groovy
Normal file
5
Task/Five-weekends/Groovy/five-weekends-2.groovy
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
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)) }
|
||||
4
Task/Five-weekends/Groovy/five-weekends-3.groovy
Normal file
4
Task/Five-weekends/Groovy/five-weekends-3.groovy
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
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 }
|
||||
34
Task/Five-weekends/Harbour/five-weekends.harbour
Normal file
34
Task/Five-weekends/Harbour/five-weekends.harbour
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
PROCEDURE Main()
|
||||
LOCAL y, m, d, nFound, cNames, nTot := 0, nNotFives := 0
|
||||
LOCAL aFounds := {}
|
||||
|
||||
SET DATE ANSI
|
||||
|
||||
FOR y := 1900 TO 2100
|
||||
nFound := 0 ; cNames := ""
|
||||
FOR m := 1 TO 12
|
||||
d := CtoD( hb_NtoS( y ) +"/" + hb_NtoS( m ) + "/1" )
|
||||
IF CDoW( d ) == "Friday"
|
||||
IF DaysInMonth( m ) == 31
|
||||
nFound++
|
||||
cNames += CMonth( d ) + " "
|
||||
ENDIF
|
||||
ENDIF
|
||||
NEXT
|
||||
IF nFound > 0
|
||||
AAdd( aFounds, hb_NtoS( y ) + " : " + hb_NtoS( nFound ) + " ( " + Rtrim( cNames ) + " )" )
|
||||
nTot += nFound
|
||||
ELSE
|
||||
nNotFives++
|
||||
ENDIF
|
||||
NEXT
|
||||
? "Total months with five weekends: " + hb_NtoS( nTot )
|
||||
? "(see bellow the first and last five years/months with five weekends)"
|
||||
?
|
||||
AEval( aFounds, { | e, n | Iif( n < 6, Qout( e ), NIL ) } )
|
||||
Qout("...")
|
||||
AEval( aFounds, { | e, n | Iif( n > Len(aFounds)-5, Qout( e ), NIL ) } )
|
||||
?
|
||||
? "Years with no five weekends months: " + hb_NtoS( nNotFives )
|
||||
|
||||
RETURN
|
||||
104
Task/Five-weekends/Haskell/five-weekends-1.hs
Normal file
104
Task/Five-weekends/Haskell/five-weekends-1.hs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import Data.List (intercalate)
|
||||
|
||||
data DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday |
|
||||
Saturday | Sunday
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- the whole thing bases upon an infinite list of weeks
|
||||
|
||||
daysFrom1_1_1900 :: [DayOfWeek]
|
||||
daysFrom1_1_1900 = concat $ repeat [Monday, Tuesday, Wednesday,
|
||||
Thursday, Friday, Saturday, Sunday]
|
||||
|
||||
data Month = January | February | March | April | May | June | July |
|
||||
August | September | October | November | December
|
||||
deriving (Show)
|
||||
|
||||
type Year = Int
|
||||
type YearCalendar = (Year, [DayOfWeek])
|
||||
type MonthlyCalendar = (Year, [(Month, [DayOfWeek])])
|
||||
|
||||
-- makes groups of 365 or 366 days for each year (infinite list)
|
||||
|
||||
yearsFrom :: [DayOfWeek] -> Year -> [YearCalendar]
|
||||
yearsFrom s i = (i, yeardays) : yearsFrom rest (i + 1)
|
||||
where
|
||||
yeardays = take (leapOrNot i) s
|
||||
yearlen = length yeardays
|
||||
rest = drop yearlen s
|
||||
leapOrNot n = if isLeapYear n then 366 else 365
|
||||
|
||||
yearsFrom1900 :: [YearCalendar]
|
||||
yearsFrom1900 = yearsFrom daysFrom1_1_1900 1900
|
||||
|
||||
-- makes groups of days for each month of the year
|
||||
|
||||
months :: YearCalendar -> MonthlyCalendar
|
||||
months (y, d) = (y, [(January, january), (February, february),
|
||||
(March, march), (April, april), (May, may), (June, june),
|
||||
(July, july), (August, august), (September, september),
|
||||
(October, october), (November, november), (December, december)])
|
||||
where
|
||||
leapOrNot = if isLeapYear y then 29 else 28
|
||||
january = take 31 d
|
||||
february = take leapOrNot $ drop 31 d
|
||||
march = take 31 $ drop (31 + leapOrNot) d
|
||||
april = take 30 $ drop (62 + leapOrNot) d
|
||||
may = take 31 $ drop (92 + leapOrNot) d
|
||||
june = take 30 $ drop (123 + leapOrNot) d
|
||||
july = take 31 $ drop (153 + leapOrNot) d
|
||||
august = take 31 $ drop (184 + leapOrNot) d
|
||||
september = take 30 $ drop (215 + leapOrNot) d
|
||||
october = take 31 $ drop (245 + leapOrNot) d
|
||||
november = take 30 $ drop (276 + leapOrNot) d
|
||||
december = take 31 $ drop (306 + leapOrNot) d
|
||||
|
||||
-- see if a year is a leap year
|
||||
|
||||
isLeapYear n
|
||||
| n `mod` 100 == 0 = n `mod` 400 == 0
|
||||
| otherwise = n `mod` 4 == 0
|
||||
|
||||
-- make a list of the months of a year that have 5 weekends
|
||||
-- (they must have 31 days and the first day must be Friday)
|
||||
-- if the year doesn't contain any 5-weekended months, then
|
||||
-- return the year and an empty list
|
||||
|
||||
whichFiveWeekends :: MonthlyCalendar -> (Year, [Month])
|
||||
whichFiveWeekends (y, ms) = (y, map (\(m, _) -> m) found) -- extract the months & leave out their days
|
||||
where found = filter (\(m, a@(d:ds)) -> and [length a == 31,
|
||||
d == Friday]) ms
|
||||
|
||||
-- take all days from 1900 until 2100, grouping them by years, then by
|
||||
-- months, and calculating whether they have any 5-weekended months
|
||||
-- or not
|
||||
|
||||
calendar :: [MonthlyCalendar]
|
||||
calendar = map months $ yearsFrom1900
|
||||
|
||||
fiveWeekends1900To2100 :: [(Year, [Month])]
|
||||
fiveWeekends1900To2100 = takeWhile (\(y, _) -> y <= 2100) $
|
||||
map whichFiveWeekends calendar
|
||||
|
||||
main = do
|
||||
-- count the number of years with 5 weekends
|
||||
let answer1 = foldl (\c (_, m) -> c + length m) 0 fiveWeekends1900To2100
|
||||
-- take only the years with 5-weekended months
|
||||
answer2 = filter (\(_, m) -> not $ null m) fiveWeekends1900To2100
|
||||
-- take only the years without 5-weekended months
|
||||
answer30 = filter (\(_, m) -> null m) fiveWeekends1900To2100
|
||||
-- count how many years without 5-weekended months there are
|
||||
answer31 = length answer30
|
||||
-- show the years without 5-weekended months
|
||||
answer32 = intercalate ", " $ map (\(y, m) -> show y) answer30
|
||||
putStrLn $ "There are " ++ show answer1 ++ " months with 5 weekends between 1900 and 2100."
|
||||
putStrLn "\nThe first ones are:"
|
||||
mapM_ (putStrLn . formatMonth) $ take 5 $ answer2
|
||||
putStrLn "\nThe last ones are:"
|
||||
mapM_ (putStrLn . formatMonth) $ reverse $ take 5 $ reverse answer2
|
||||
putStrLn $ "\n" ++ show answer31 ++ " years don't have at least one five-weekened month"
|
||||
putStrLn "\nThose are:"
|
||||
putStrLn answer32
|
||||
|
||||
formatMonth :: (Year, [Month]) -> String
|
||||
formatMonth (y, m) = show y ++ ": " ++ intercalate ", " [ show x | x <- m ]
|
||||
47
Task/Five-weekends/Haskell/five-weekends-2.hs
Normal file
47
Task/Five-weekends/Haskell/five-weekends-2.hs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import Data.List (intercalate)
|
||||
import Data.List.Split (chunksOf)
|
||||
import Data.Time (Day, fromGregorian, gregorianMonthLength)
|
||||
import Data.Time.Calendar.WeekDate (toWeekDate)
|
||||
|
||||
---------------- MONTHS WITH FIVE WEEKENDS ---------------
|
||||
|
||||
fiveFridayMonths :: Integer -> [(Integer, Int)]
|
||||
fiveFridayMonths y =
|
||||
[1 .. 12]
|
||||
>>= \m ->
|
||||
[ (y, m)
|
||||
| isFriday (fromGregorian y m 1),
|
||||
31 == gregorianMonthLength y m
|
||||
]
|
||||
|
||||
isFriday :: Day -> Bool
|
||||
isFriday d = 5 == day
|
||||
where
|
||||
(_, _, day) = toWeekDate d
|
||||
|
||||
--------------------------- TEST -------------------------
|
||||
main :: IO ()
|
||||
main = do
|
||||
let years = [1900 .. 2100]
|
||||
xs = fiveFridayMonths <$> years
|
||||
lean =
|
||||
concat $
|
||||
zipWith
|
||||
(\months year -> [year | null months])
|
||||
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 $
|
||||
('\t' :) . unwords . fmap show
|
||||
<$> chunksOf 5 lean
|
||||
]
|
||||
26
Task/Five-weekends/Icon/five-weekends.icon
Normal file
26
Task/Five-weekends/Icon/five-weekends.icon
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
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
|
||||
102
Task/Five-weekends/Inform-7/five-weekends.inf
Normal file
102
Task/Five-weekends/Inform-7/five-weekends.inf
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
Calendar is a room.
|
||||
|
||||
When play begins:
|
||||
let happy month count be 0;
|
||||
let sad year count be 0;
|
||||
repeat with Y running from Y1900 to Y2100:
|
||||
if Y is a sad year, increment the sad year count;
|
||||
repeat with M running through months:
|
||||
if M of Y is a happy month:
|
||||
say "[M] [year number of Y].";
|
||||
increment the happy month count;
|
||||
say "Found [happy month count] month[s] with five weekends and [sad year count] year[s] with no such months.";
|
||||
end the story.
|
||||
|
||||
Section - Years
|
||||
|
||||
A year is a kind of value. Y1 specifies a year.
|
||||
|
||||
To decide which number is year number of (Y - year):
|
||||
decide on Y / Y1.
|
||||
|
||||
To decide if (N - number) is divisible by (M - number):
|
||||
decide on whether or not the remainder after dividing N by M is zero.
|
||||
|
||||
Definition: a year (called Y) is a leap year:
|
||||
let YN be the year number of Y;
|
||||
if YN is divisible by 400, yes;
|
||||
if YN is divisible by 100, no;
|
||||
if YN is divisible by 4, yes;
|
||||
no.
|
||||
|
||||
Section - Months
|
||||
|
||||
A month is a kind of value. The months are defined by the Table of Months.
|
||||
|
||||
Table of Months
|
||||
month month number
|
||||
January 1
|
||||
February 2
|
||||
March 3
|
||||
April 4
|
||||
May 5
|
||||
June 6
|
||||
July 7
|
||||
August 8
|
||||
September 9
|
||||
October 10
|
||||
November 11
|
||||
December 12
|
||||
|
||||
A month has a number called length. The length of a month is usually 31.
|
||||
September, April, June, and November have length 30. February has length 28.
|
||||
|
||||
To decide which number is number of days in (M - month) of (Y - year):
|
||||
let L be the length of M;
|
||||
if M is February and Y is a leap year, decide on L + 1;
|
||||
otherwise decide on L.
|
||||
|
||||
Section - Weekdays
|
||||
|
||||
A weekday is a kind of value. The weekdays are defined by the Table of Weekdays.
|
||||
|
||||
Table of Weekdays
|
||||
weekday weekday number
|
||||
Saturday 0
|
||||
Sunday 1
|
||||
Monday 2
|
||||
Tuesday 3
|
||||
Wednesday 4
|
||||
Thursday 5
|
||||
Friday 6
|
||||
|
||||
To decide which weekday is weekday of the/-- (N - number) of (M - month) of (Y - year):
|
||||
let MN be the month number of M;
|
||||
let YN be the year number of Y;
|
||||
if MN is less than 3:
|
||||
increase MN by 12;
|
||||
decrease YN by 1;
|
||||
let h be given by Zeller's Congruence;
|
||||
let WDN be the remainder after dividing h by 7;
|
||||
decide on the weekday corresponding to a weekday number of WDN in the Table of Weekdays.
|
||||
|
||||
Equation - Zeller's Congruence
|
||||
h = N + ((MN + 1)*26)/10 + YN + YN/4 + 6*(YN/100) + YN/400
|
||||
where h is a number, N is a number, MN is a number, and YN is a number.
|
||||
|
||||
To decide which number is number of (W - weekday) days in (M - month) of (Y - year):
|
||||
let count be 0;
|
||||
repeat with N running from 1 to the number of days in M of Y:
|
||||
if W is the weekday of the N of M of Y, increment count;
|
||||
decide on count.
|
||||
|
||||
Section - Happy Months and Sad Years
|
||||
|
||||
To decide if (M - month) of (Y - year) is a happy month:
|
||||
if the number of days in M of Y is 31 and the weekday of the 1st of M of Y is Friday, decide yes;
|
||||
decide no.
|
||||
|
||||
To decide if (Y - year) is a sad year:
|
||||
repeat with M running through months:
|
||||
if M of Y is a happy month, decide no;
|
||||
decide yes.
|
||||
7
Task/Five-weekends/J/five-weekends-1.j
Normal file
7
Task/Five-weekends/J/five-weekends-1.j
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
require 'types/datetime numeric'
|
||||
find5wkdMonths=: verb define
|
||||
years=. range 2{. y
|
||||
months=. 1 3 5 7 8 10 12
|
||||
m5w=. (#~ 0 = weekday) >,{years;months;31 NB. 5 full weekends iff 31st is Sunday(0)
|
||||
>'MMM YYYY' fmtDate toDayNo m5w
|
||||
)
|
||||
16
Task/Five-weekends/J/five-weekends-2.j
Normal file
16
Task/Five-weekends/J/five-weekends-2.j
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
# find5wkdMonths 1900 2100 NB. number of months found
|
||||
201
|
||||
(5&{. , '...' , _5&{.) find5wkdMonths 1900 2100 NB. First and last 5 months found
|
||||
Mar 1901
|
||||
Aug 1902
|
||||
May 1903
|
||||
Jan 1904
|
||||
Jul 1904
|
||||
...
|
||||
Mar 2097
|
||||
Aug 2098
|
||||
May 2099
|
||||
Jan 2100
|
||||
Oct 2100
|
||||
# (range -. {:"1@(_ ". find5wkdMonths)) 1900 2100 NB. number of years without 5 weekend months
|
||||
29
|
||||
32
Task/Five-weekends/Java/five-weekends.java
Normal file
32
Task/Five-weekends/Java/five-weekends.java
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
public class FiveFSS {
|
||||
private static boolean[] years = new boolean[201];
|
||||
private static int[] month31 = {Calendar.JANUARY, Calendar.MARCH, Calendar.MAY,
|
||||
Calendar.JULY, Calendar.AUGUST, Calendar.OCTOBER, Calendar.DECEMBER};
|
||||
|
||||
public static void main(String[] args) {
|
||||
StringBuilder months = new StringBuilder();
|
||||
int numMonths = 0;
|
||||
for (int year = 1900; year <= 2100; year++) {
|
||||
for (int month : month31) {
|
||||
Calendar date = new GregorianCalendar(year, month, 1);
|
||||
if (date.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
|
||||
years[year - 1900] = true;
|
||||
numMonths++;
|
||||
//months are 0-indexed in Calendar
|
||||
months.append((date.get(Calendar.MONTH) + 1) + "-" + year +"\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("There are "+numMonths+" months with five weekends from 1900 through 2100:");
|
||||
System.out.println(months);
|
||||
System.out.println("Years with no five-weekend months:");
|
||||
for (int year = 1900; year <= 2100; year++) {
|
||||
if(!years[year - 1900]){
|
||||
System.out.println(year);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
45
Task/Five-weekends/JavaScript/five-weekends-1.js
Normal file
45
Task/Five-weekends/JavaScript/five-weekends-1.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
function startsOnFriday(month, year)
|
||||
{
|
||||
// 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
|
||||
return new Date(year, month, 1).getDay() === 5;
|
||||
}
|
||||
function has31Days(month, year)
|
||||
{
|
||||
return new Date(year, month, 31).getDate() === 31;
|
||||
}
|
||||
function checkMonths(year)
|
||||
{
|
||||
var month, count = 0;
|
||||
for (month = 0; month < 12; month += 1)
|
||||
{
|
||||
if (startsOnFriday(month, year) && has31Days(month, year))
|
||||
{
|
||||
count += 1;
|
||||
document.write(year + ' ' + month + '<br>');
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
function fiveWeekends()
|
||||
{
|
||||
var
|
||||
startYear = 1900,
|
||||
endYear = 2100,
|
||||
year,
|
||||
monthTotal = 0,
|
||||
yearsWithoutFiveWeekends = [],
|
||||
total = 0;
|
||||
for (year = startYear; year <= endYear; year += 1)
|
||||
{
|
||||
monthTotal = checkMonths(year);
|
||||
total += monthTotal;
|
||||
// extra credit
|
||||
if (monthTotal === 0)
|
||||
yearsWithoutFiveWeekends.push(year);
|
||||
}
|
||||
document.write('Total number of months: ' + total + '<br>');
|
||||
document.write('<br>');
|
||||
document.write(yearsWithoutFiveWeekends + '<br>');
|
||||
document.write('Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '<br>');
|
||||
}
|
||||
fiveWeekends();
|
||||
61
Task/Five-weekends/JavaScript/five-weekends-2.js
Normal file
61
Task/Five-weekends/JavaScript/five-weekends-2.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
var Months = [
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||
'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'
|
||||
];
|
||||
|
||||
var leap = 0,
|
||||
// Relative offsets between first day of each month
|
||||
offset = [3,0,3,2,3,2,3,3,2,3,2,3],
|
||||
|
||||
// Months that contain 31 days
|
||||
longMonths = [1,3,5,7,8,10,12],
|
||||
|
||||
startYear = 1900,
|
||||
year = startYear,
|
||||
endYear = 2100,
|
||||
|
||||
// Jan 1, 1900 starts on a Monday
|
||||
day = 1,
|
||||
|
||||
totalPerYear = 0,
|
||||
total = 0,
|
||||
without = 0;
|
||||
|
||||
for (; year < endYear + 1; year++) {
|
||||
leap = totalPerYear = 0;
|
||||
|
||||
if (year % 4 === 0) {
|
||||
if (year % 100 === 0) {
|
||||
if (year % 400 === 0) {
|
||||
leap = 1;
|
||||
}
|
||||
} else {
|
||||
leap = 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < offset.length; i++) {
|
||||
for (var j = 0; day === 5 && j < longMonths.length; j++) {
|
||||
if (i + 1 === longMonths[j]) {
|
||||
console.log(year + '-' + Months[i]);
|
||||
totalPerYear++;
|
||||
total++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// February -- if leap year, then +1 day
|
||||
if (i == 1) {
|
||||
day = (day + leap) % 7;
|
||||
} else {
|
||||
day = (day + offset[i]) % 7;
|
||||
}
|
||||
}
|
||||
|
||||
if (totalPerYear === 0) {
|
||||
without++;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
54
Task/Five-weekends/JavaScript/five-weekends-3.js
Normal file
54
Task/Five-weekends/JavaScript/five-weekends-3.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
(function () {
|
||||
'use strict';
|
||||
|
||||
// longMonthsStartingFriday :: Int -> Int
|
||||
function longMonthsStartingFriday(y) {
|
||||
return [0, 2, 4, 6, 7, 9, 11]
|
||||
.filter(function (m) {
|
||||
return (new Date(Date.UTC(y, m, 1)))
|
||||
.getDay() === 5;
|
||||
});
|
||||
}
|
||||
|
||||
// range :: Int -> Int -> [Int]
|
||||
function range(m, n) {
|
||||
return Array.apply(null, Array(n - m + 1))
|
||||
.map(function (x, i) {
|
||||
return m + i;
|
||||
});
|
||||
}
|
||||
|
||||
var lstNames = [
|
||||
'January', '', 'March', '', 'May', '',
|
||||
'July', 'August', '', 'October', '', 'December'
|
||||
],
|
||||
|
||||
lstYears = range(1900, 2100),
|
||||
|
||||
lstFullMonths = lstYears
|
||||
.reduce(function (a, y) {
|
||||
var strYear = y.toString();
|
||||
|
||||
return a.concat(
|
||||
longMonthsStartingFriday(y)
|
||||
.map(function (m) {
|
||||
return strYear + ' ' + lstNames[m];
|
||||
})
|
||||
);
|
||||
}, []),
|
||||
|
||||
lstLeanYears = lstYears
|
||||
.filter(function (y) {
|
||||
return longMonthsStartingFriday(y)
|
||||
.length === 0;
|
||||
});
|
||||
|
||||
return JSON.stringify({
|
||||
number: lstFullMonths.length,
|
||||
firstFive: lstFullMonths.slice(0, 5),
|
||||
lastFive: lstFullMonths.slice(-5),
|
||||
leanYearCount: lstLeanYears.length
|
||||
},
|
||||
null, 2
|
||||
);
|
||||
})();
|
||||
60
Task/Five-weekends/JavaScript/five-weekends-4.js
Normal file
60
Task/Five-weekends/JavaScript/five-weekends-4.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
(() => {
|
||||
// longMonthsStartingFriday :: Int -> [Int]
|
||||
const longMonthsStartingFriday = y =>
|
||||
filter(m => (new Date(Date.UTC(y, m, 1)))
|
||||
.getDay() === 5, [0, 2, 4, 6, 7, 9, 11]);
|
||||
|
||||
// Years -> YearMonths
|
||||
// fullMonths :: [Int] -> [String]
|
||||
const fullMonths = xs =>
|
||||
foldl((a, y) => a.concat(
|
||||
map(m => `${y.toString()} ${[
|
||||
'January', '', 'March', '', 'May', '',
|
||||
'July', 'August', '', 'October', '', 'December'
|
||||
][m]}`, longMonthsStartingFriday(y))
|
||||
), [], xs);
|
||||
|
||||
// leanYears :: [Int] -> [Int]
|
||||
const leanYears = years =>
|
||||
filter(y => longMonthsStartingFriday(y)
|
||||
.length === 0, years);
|
||||
|
||||
// GENERIC ----------------------------------------------------------------
|
||||
|
||||
// A list of functions applied to a list of arguments
|
||||
// <*> :: [(a -> b)] -> [a] -> [b]
|
||||
const ap = (fs, xs) => //
|
||||
[].concat.apply([], fs.map(f => //
|
||||
[].concat.apply([], xs.map(x => [f(x)]))));
|
||||
|
||||
// enumFromTo :: Int -> Int -> [Int]
|
||||
const enumFromTo = (m, n) =>
|
||||
Array.from({
|
||||
length: Math.floor(n - m) + 1
|
||||
}, (_, i) => m + i);
|
||||
|
||||
// filter :: (a -> Bool) -> [a] -> [a]
|
||||
const filter = (f, xs) => xs.filter(f);
|
||||
|
||||
// foldl :: (b -> a -> b) -> b -> [a] -> b
|
||||
const foldl = (f, a, xs) => xs.reduce(f, a);
|
||||
|
||||
// map :: (a -> b) -> [a] -> [b]
|
||||
const map = (f, xs) => xs.map(f);
|
||||
|
||||
// show :: a -> String
|
||||
const show = x => JSON.stringify(x, null, 2);
|
||||
|
||||
|
||||
// TEST -------------------------------------------------------------------
|
||||
const [lstFullMonths, lstLeanYears] = ap(
|
||||
[fullMonths, leanYears], [enumFromTo(1900, 2100)]
|
||||
);
|
||||
|
||||
return show({
|
||||
number: lstFullMonths.length,
|
||||
firstFive: lstFullMonths.slice(0, 5),
|
||||
lastFive: lstFullMonths.slice(-5),
|
||||
leanYearCount: lstLeanYears.length
|
||||
});
|
||||
})();
|
||||
15
Task/Five-weekends/Jq/five-weekends-1.jq
Normal file
15
Task/Five-weekends/Jq/five-weekends-1.jq
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
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.
|
||||
#
|
||||
def day_of_week(year; month; day):
|
||||
if month == 1 or month == 2 then
|
||||
[month + 12, year - 1]
|
||||
else
|
||||
[month, year]
|
||||
end
|
||||
| day + (13*(.[0] + 1)/5|floor)
|
||||
+ (.[1]%100) + ((.[1]%100)/4|floor)
|
||||
+ (.[1]/400|floor) - 2*(.[1]/100|floor)
|
||||
| . % 7
|
||||
;
|
||||
25
Task/Five-weekends/Jq/five-weekends-2.jq
Normal file
25
Task/Five-weekends/Jq/five-weekends-2.jq
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
def weekday_of_last_day_of_month(year; month):
|
||||
def day_before(day): (6+day) % 7;
|
||||
|
||||
if month==12 then day_before( day_of_week(year+1; 1; 1) )
|
||||
else day_before( day_of_week( year; month+1; 1 ) )
|
||||
end
|
||||
;
|
||||
|
||||
# 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.
|
||||
#
|
||||
def five_weekends(from; to):
|
||||
reduce range(from; to) as $year
|
||||
([]; reduce (1,3,5,7,8,10,12) as $month # months with 31 days
|
||||
(.;
|
||||
weekday_of_last_day_of_month($year; $month) as $day
|
||||
| if $day == 1 then . + [[ $year, $month]] else . end ))
|
||||
;
|
||||
|
||||
# Input [year, month] as conventional integers; print e.g. "Jan 2001"
|
||||
def pp:
|
||||
def month:
|
||||
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][.-1];
|
||||
"\(.[1] | month) \(.[0])"
|
||||
;
|
||||
7
Task/Five-weekends/Jq/five-weekends-3.jq
Normal file
7
Task/Five-weekends/Jq/five-weekends-3.jq
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
five_weekends(1900;2101)
|
||||
| "There are \(length) months with 5 weekends from 1900 to 2100 inclusive;",
|
||||
"the first and last five are as follows:",
|
||||
( .[0: 5][] | pp),
|
||||
"...",
|
||||
( .[length-5: ][] | pp),
|
||||
"In this period, there are \( [range(1900;2101)] - map( .[0] ) | length ) years which have no five-weekend months."
|
||||
15
Task/Five-weekends/Jq/five-weekends-4.jq
Normal file
15
Task/Five-weekends/Jq/five-weekends-4.jq
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
$ 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:
|
||||
Mar 1901
|
||||
Aug 1902
|
||||
May 1903
|
||||
Jan 1904
|
||||
Jul 1904
|
||||
...
|
||||
Mar 2097
|
||||
Aug 2098
|
||||
May 2099
|
||||
Jan 2100
|
||||
Oct 2100
|
||||
In this period, there are 29 years which have no five-weekend months.
|
||||
21
Task/Five-weekends/Julia/five-weekends.julia
Normal file
21
Task/Five-weekends/Julia/five-weekends.julia
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
isweekend(dt::Date) = Dates.dayofweek(dt) ∈ (Dates.Friday, Dates.Saturday, Dates.Sunday)
|
||||
|
||||
function hasfiveweekend(month::Integer, year::Integer)
|
||||
dmin = Date(year, month, 1)
|
||||
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("Number of months with 5 full-weekends: $(length(months))")
|
||||
println("First five such months:")
|
||||
for (y, m) in months[1:5] println(" - $y-$m") end
|
||||
println("Last five such months:")
|
||||
for (y, m) in months[end-4:end] println(" - $y-$m") end
|
||||
|
||||
# extra credit
|
||||
yrs = getindex.(months, 1)
|
||||
nyrs = 2100 - 1899 - length(unique(yrs))
|
||||
|
||||
println("Number of year with not one 5-full-weekend month: $nyrs")
|
||||
14
Task/Five-weekends/K/five-weekends.k
Normal file
14
Task/Five-weekends/K/five-weekends.k
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
cal_j:(_jd[19000101]+!(-/_jd 21010101 19000101)) / enumerate the calendar
|
||||
is_we:(cal_j!7) _lin 4 5 6 / identify friday saturdays and sundays
|
||||
m:__dj[cal_j]%100 / label the months
|
||||
mi:&15=+/'is_we[=m] / group by month and sum the weekend days
|
||||
`0:,"There are ",($#mi)," months with five weekends"
|
||||
m5:(?m)[mi]
|
||||
`0:$5#m5
|
||||
`0:,"..."
|
||||
`0:$-5#m5
|
||||
y:1900+!201 / enumerate the years in the range
|
||||
y5:?_ m5%100 / label the years of the months
|
||||
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
|
||||
27
Task/Five-weekends/Kotlin/five-weekends.kotlin
Normal file
27
Task/Five-weekends/Kotlin/five-weekends.kotlin
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// version 1.0.6
|
||||
|
||||
import java.util.*
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val calendar = GregorianCalendar(1900, 0, 1)
|
||||
val months31 = arrayOf(1, 3, 5, 7, 8, 10, 12)
|
||||
val monthsWithFive = mutableListOf<String>()
|
||||
val yearsWithNone = mutableListOf<Int>()
|
||||
for (year in 1900..2100) {
|
||||
var countInYear = 0 // counts months in a given year with 5 weekends
|
||||
for (month in 1..12) {
|
||||
if ((month in months31) && (Calendar.FRIDAY == calendar[Calendar.DAY_OF_WEEK])) {
|
||||
countInYear++
|
||||
monthsWithFive.add("%02d".format(month) + "-" + year)
|
||||
}
|
||||
calendar.add(Calendar.MONTH, 1)
|
||||
}
|
||||
if (countInYear == 0) yearsWithNone.add(year)
|
||||
}
|
||||
println("There are ${monthsWithFive.size} months with 5 weekends")
|
||||
println("The first 5 are ${monthsWithFive.take(5)}")
|
||||
println("The final 5 are ${monthsWithFive.takeLast(5)}")
|
||||
println()
|
||||
println("There are ${yearsWithNone.size} years with no months which have 5 weekends, namely:")
|
||||
println(yearsWithNone)
|
||||
}
|
||||
52
Task/Five-weekends/Lasso/five-weekends.lasso
Normal file
52
Task/Five-weekends/Lasso/five-weekends.lasso
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
local(
|
||||
months = array(1, 3, 5, 7, 8, 10, 12),
|
||||
fivemonths = array,
|
||||
emptyears = array,
|
||||
checkdate = date,
|
||||
countyear
|
||||
)
|
||||
|
||||
#checkdate -> day = 1
|
||||
|
||||
loop(-from = 1900, -to = 2100) => {
|
||||
|
||||
#countyear = false
|
||||
|
||||
#checkdate -> year = loop_count
|
||||
|
||||
with month in #months
|
||||
do {
|
||||
#checkdate -> month = #month
|
||||
if(#checkdate -> dayofweek == 6) => {
|
||||
#countyear = true
|
||||
#fivemonths -> insert(#checkdate -> format(`YYYY MMM`))
|
||||
}
|
||||
}
|
||||
|
||||
if(not #countyear) => {
|
||||
#emptyears -> insert(loop_count)
|
||||
}
|
||||
|
||||
}
|
||||
local(
|
||||
monthcount = #fivemonths -> size,
|
||||
output = 'Total number of months ' + #monthcount + '<br /> Starting five months '
|
||||
)
|
||||
|
||||
loop(5) => {
|
||||
#output -> append(#fivemonths -> get(loop_count) + ', ')
|
||||
}
|
||||
|
||||
#output -> append('<br /> Ending five months ')
|
||||
|
||||
loop(-from = #monthcount - 5, -to = #monthcount) => {
|
||||
#output -> append(#fivemonths -> get(loop_count) + ', ')
|
||||
}
|
||||
|
||||
#output -> append('<br /> Years with no five weekend months ' + #emptyears -> size + '<br />')
|
||||
|
||||
with year in #emptyears do {
|
||||
#output -> append(#year + ', ')
|
||||
}
|
||||
|
||||
#output
|
||||
30
Task/Five-weekends/Lua/five-weekends.lua
Normal file
30
Task/Five-weekends/Lua/five-weekends.lua
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
local months={"JAN","MAR","MAY","JUL","AUG","OCT","DEC"}
|
||||
local daysPerMonth={31+28,31+30,31+30,31,31+30,31+30,0}
|
||||
|
||||
function find5weMonths(year)
|
||||
local list={}
|
||||
local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7
|
||||
|
||||
for i,v in ipairs(daysPerMonth) do
|
||||
if startday==4 then list[#list+1]=months[i] end
|
||||
if i==1 and year%4==0 and year%100~=0 or year%400==0 then
|
||||
startday=startday+1
|
||||
end
|
||||
startday=(startday+v)%7
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
local cnt_months=0
|
||||
local cnt_no5we=0
|
||||
|
||||
for y=1900,2100 do
|
||||
local list=find5weMonths(y)
|
||||
cnt_months=cnt_months+#list
|
||||
if #list==0 then
|
||||
cnt_no5we=cnt_no5we+1
|
||||
end
|
||||
print(y.." "..#list..": "..table.concat(list,", "))
|
||||
end
|
||||
print("Months with 5 weekends: ",cnt_months)
|
||||
print("Years without 5 weekends in the same month:",cnt_no5we)
|
||||
25
Task/Five-weekends/MATLAB/five-weekends.m
Normal file
25
Task/Five-weekends/MATLAB/five-weekends.m
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
longmonth = [1 3 5 7 8 10 12];
|
||||
|
||||
i = 1;
|
||||
|
||||
for y = 1900:2100
|
||||
for m = 1:numel(longmonth)
|
||||
[num,name] = weekday(datenum(y,longmonth(m),1));
|
||||
if num == 6
|
||||
x(i,:) = datestr(datenum(y,longmonth(m),1),'mmm yyyy'); %#ok<SAGROW>
|
||||
i = i+1;
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
fprintf('There are %i months with 5 weekends between 1900 and 2100.\n',length(x))
|
||||
|
||||
fprintf('\n The first 5 months are:\n')
|
||||
for j = 1:5
|
||||
fprintf('\t %s \n',x(j,:))
|
||||
end
|
||||
|
||||
fprintf('\n The final 5 months are:\n')
|
||||
for j = length(x)-4:length(x)
|
||||
fprintf('\t %s \n',x(j,:))
|
||||
end
|
||||
37
Task/Five-weekends/MUMPS/five-weekends.mumps
Normal file
37
Task/Five-weekends/MUMPS/five-weekends.mumps
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
FIVE
|
||||
;List and count the months between 1/1900 and 12/2100 that have 5 full weekends
|
||||
;Extra credit - list and count years with no months with five full weekends
|
||||
;Using the test that the 31st of a month is on a Sunday
|
||||
;Uses the VA's public domain routine %DTC (Part of the Kernel) named here DIDTC
|
||||
NEW YEAR,MONTH,X,Y,CNTMON,NOT,NOTLIST
|
||||
; YEAR is the year we're testing
|
||||
; MONTH is the month we're testing
|
||||
; X is the date in "internal" format, as an input to DOW^DIDTC
|
||||
; Y is the day of the week (0=Sunday, 1=Monday...) output from DOW^DIDTC
|
||||
; CNTMON is a count of the months that have 5 full weekends
|
||||
; NOT is a flag if there were no months with 5 full weekends yet that year
|
||||
; NOTLIST is a list of years that do not have any months with 5 full weekends
|
||||
SET CNTMON=0,NOTLIST=""
|
||||
WRITE !!,"The following months have five full weekends:"
|
||||
FOR YEAR=200:1:400 DO ;years since 12/31/1700 epoch
|
||||
. SET NOT=0
|
||||
. FOR MONTH="01","03","05","07","08","10","12" DO
|
||||
. . SET X=YEAR_MONTH_"31"
|
||||
. . DO DOW^DIDTC
|
||||
. . IF (Y=0) DO
|
||||
. . . SET NOT=NOT+1,CNTMON=CNTMON+1
|
||||
. . . WRITE !,MONTH_"-"_(YEAR+1700)
|
||||
. SET:(NOT=0) NOTLIST=NOTLIST_$SELECT($LENGTH(NOTLIST)>1:",",1:"")_(YEAR+1700)
|
||||
WRITE !,"For a total of "_CNTMON_" months."
|
||||
WRITE !!,"There are "_$LENGTH(NOTLIST,",")_" years with no five full weekends in any month."
|
||||
WRITE !,"They are: "_NOTLIST
|
||||
KILL YEAR,MONTH,X,Y,CNTMON,NOT,NOTLIST
|
||||
QUIT
|
||||
F ;Same logic as the main entry point, shortened format
|
||||
N R,M,X,Y,C,N,L S C=0,L=""
|
||||
W !!,"The following months have five full weekends:"
|
||||
F R=200:1:400 D
|
||||
. S N=0 F M="01","03","05","07","08","10","12" S X=R_M_"31" D DOW^DIDTC I 'Y S N=N+1,C=C+1 W !,M_"-"_(R+1700)
|
||||
. 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
|
||||
17
Task/Five-weekends/Maple/five-weekends.maple
Normal file
17
Task/Five-weekends/Maple/five-weekends.maple
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
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();
|
||||
8
Task/Five-weekends/Mathematica/five-weekends.math
Normal file
8
Task/Five-weekends/Mathematica/five-weekends.math
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
years = {1900, 2100}; months = {1 ,3 ,5 ,7 ,8 ,10 ,12};
|
||||
result = Select[Tuples[{Range@@years, months}], (DateString[# ~ Join ~ 1, "DayNameShort"] == "Fri")&];
|
||||
|
||||
Print[result // Length," months with 5 weekends" ];
|
||||
Print["First months: ", DateString[#,{"MonthName"," ","Year"}]& /@ result[[1 ;; 5]]];
|
||||
Print["Last months: " , DateString[#,{"MonthName"," ","Year"}]& /@ result[[-5 ;; All]]];
|
||||
Print[# // Length, " years without 5 weekend months:\n", #] &@
|
||||
Complement[Range @@ years, Part[Transpose@result, 1]];
|
||||
17
Task/Five-weekends/Maxima/five-weekends.maxima
Normal file
17
Task/Five-weekends/Maxima/five-weekends.maxima
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
left(a, n) := makelist(a[i], i, 1, n)$
|
||||
right(a, n) := block([m: length(a)], makelist(a[i], i, m - n + 1, m))$
|
||||
|
||||
a: [ ]$
|
||||
for year from 1900 thru 2100 do
|
||||
for month in [1, 3, 5, 7, 8, 10, 12] do
|
||||
if weekday(year, month, 1) = 'friday then
|
||||
a: endcons([year, month], a)$
|
||||
|
||||
length(a);
|
||||
201
|
||||
|
||||
left(a, 5);
|
||||
[[1901,3],[1902,8],[1903,5],[1904,1],[1904,7]]
|
||||
|
||||
right(a, 5);
|
||||
[[2097,3],[2098,8],[2099,5],[2100,1],[2100,10]]
|
||||
46
Task/Five-weekends/NetRexx/five-weekends.netrexx
Normal file
46
Task/Five-weekends/NetRexx/five-weekends.netrexx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
/* NetRexx ************************************************************
|
||||
* 30.08.2012 Walter Pachl derived from Rexx version 3
|
||||
* omitting dead code left there
|
||||
**********************************************************************/
|
||||
options replace format comments java crossref savelog symbols
|
||||
Numeric digits 20
|
||||
nr5fwe=0
|
||||
years_without_5fwe=0
|
||||
mnl='Jan Mar May Jul Aug Oct Dec'
|
||||
ml='1 3 5 7 8 10 12'
|
||||
Loop j=1900 To 2100
|
||||
year_has_5fwe=0
|
||||
Loop mi=1 To ml.words()
|
||||
m=ml.word(mi)
|
||||
jd=greg2jul(j,m,1)
|
||||
IF jd//7=4 Then Do /* 1st m j is a Friday */
|
||||
nr5fwe=nr5fwe+1
|
||||
year_has_5fwe=1
|
||||
If j<=1905 | 2095<=j Then
|
||||
Say mnl.word(mi) j 'has 5 full weekends'
|
||||
End
|
||||
End
|
||||
If j=1905 Then Say '...'
|
||||
if year_has_5fwe=0 Then years_without_5fwe=years_without_5fwe+1
|
||||
End
|
||||
Say ' '
|
||||
Say nr5fwe 'occurrences of 5 full weekends in a month'
|
||||
Say years_without_5fwe 'years without 5 full weekends'
|
||||
exit
|
||||
|
||||
method greg2jul(yy,mm,d) public static returns Rexx
|
||||
/***********************************************************************
|
||||
* Converts a Gregorian date to the corresponding Julian day number
|
||||
* 19891101 Walter Pachl REXXified algorithm published in CACM
|
||||
* (Fliegel & vanFlandern, CACM Vol.11 No.10 October 1968)
|
||||
***********************************************************************/
|
||||
numeric digits 12
|
||||
/***********************************************************************
|
||||
* The published formula:
|
||||
* res=d-32075+1461*(yy+4800+(mm-14)%12)%4+,
|
||||
* 367*(mm-2-((mm-14)%12)*12)%12-3*((yy+4900+(mm-14)%12)%100)%4
|
||||
***********************************************************************/
|
||||
mma=(mm-14)%12
|
||||
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 */
|
||||
77
Task/Five-weekends/NewLISP/five-weekends.l
Normal file
77
Task/Five-weekends/NewLISP/five-weekends.l
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
#!/usr/local/bin/newlisp
|
||||
|
||||
(context 'KR)
|
||||
|
||||
(define (Kraitchik year month day)
|
||||
; See https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Kraitchik.27s_variation
|
||||
; Function adapted for specific task (not for general usage).
|
||||
(if (or (= 1 month) (= 2 month))
|
||||
(dec year)
|
||||
)
|
||||
;- - - -
|
||||
(setf m-table '(_ 1 4 3 6 1 4 6 2 5 0 3 5)) ; - - - First element of list is dummy!
|
||||
(setf m (m-table month))
|
||||
;- - - -
|
||||
(setf c-table '(0 5 3 1))
|
||||
(setf century%4 (mod (int (slice (string year) 0 2)) 4))
|
||||
(setf c (c-table century%4))
|
||||
;- - - -
|
||||
(setf yy* (slice (string year) -2))
|
||||
(if (= "0" (yy* 0))
|
||||
(setf yy* (yy* 1))
|
||||
)
|
||||
(setf yy (int yy*))
|
||||
(setf y (mod (+ (/ yy 4) yy) 7))
|
||||
;- - - -
|
||||
(setf dow-table '(6 0 1 2 3 4 5))
|
||||
(dow-table (mod (+ day m c y) 7))
|
||||
)
|
||||
|
||||
(context 'MAIN)
|
||||
|
||||
(setf Fives 0)
|
||||
(setf NotFives 0)
|
||||
(setf Report '())
|
||||
(setf months-table '((1 "Jan") (3 "Mar") (5 "May") (7 "Jul") (8 "Aug") (10 "Oct") (12 "Dec")))
|
||||
|
||||
(for (y 1900 2100)
|
||||
(setf FivesFound 0)
|
||||
(setf Names "")
|
||||
(dolist (m '(1 3 5 7 8 10 12))
|
||||
(setf Dow (KR:Kraitchik y m 1))
|
||||
(if (= 5 Dow)
|
||||
(begin
|
||||
(++ FivesFound)
|
||||
(setf Names (string Names " " (lookup m months-table)))
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
(if (zero? FivesFound)
|
||||
(++ NotFives)
|
||||
(begin
|
||||
(setf Report (append Report (list (list y FivesFound (string "(" Names " )")))))
|
||||
(setf Fives (+ Fives FivesFound))
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
;- - - - Display all report data
|
||||
;(dolist (x Report)
|
||||
; (println (x 0) ": " (x 1) " " (x 2))
|
||||
;)
|
||||
|
||||
|
||||
;- - - - Display only first five and last five records
|
||||
(dolist (x (slice Report 0 5))
|
||||
(println (x 0) ": " (x 1) " " (x 2))
|
||||
)
|
||||
(println "...")
|
||||
(dolist (x (slice Report -5))
|
||||
(println (x 0) ": " (x 1) " " (x 2))
|
||||
)
|
||||
|
||||
(println "\nTotal months with five weekends: " Fives)
|
||||
(println "Years with no five weekends months: " NotFives)
|
||||
(exit)
|
||||
14
Task/Five-weekends/Nim/five-weekends.nim
Normal file
14
Task/Five-weekends/Nim/five-weekends.nim
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import times
|
||||
|
||||
const LongMonths = {mJan, mMar, mMay, mJul, mAug, mOct, mDec}
|
||||
|
||||
var sumNone = 0
|
||||
for year in 1900..2100:
|
||||
var none = true
|
||||
for month in LongMonths:
|
||||
if initDateTime(1, month, year, 0, 0, 0).weekday == dFri:
|
||||
echo month, " ", year
|
||||
none = false
|
||||
if none: inc sumNone
|
||||
|
||||
echo "\nYears without a 5 weekend month: ", sumNone
|
||||
27
Task/Five-weekends/OCaml/five-weekends.ocaml
Normal file
27
Task/Five-weekends/OCaml/five-weekends.ocaml
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
open CalendarLib
|
||||
|
||||
let list_first_five = function
|
||||
| x1 :: x2 :: x3 :: x4 :: x5 :: _ -> [x1; x2; x3; x4; x5]
|
||||
| _ -> invalid_arg "list_first_five"
|
||||
|
||||
let () =
|
||||
let months = ref [] in
|
||||
for year = 1900 to 2100 do
|
||||
for month = 1 to 12 do
|
||||
let we = ref 0 in
|
||||
let num_days = Date.days_in_month (Date.make_year_month year month) in
|
||||
for day = 1 to num_days - 2 do
|
||||
let d0 = Date.day_of_week (Date.make year month day)
|
||||
and d1 = Date.day_of_week (Date.make year month (day + 1))
|
||||
and d2 = Date.day_of_week (Date.make year month (day + 2)) in
|
||||
if (d0, d1, d2) = (Date.Fri, Date.Sat, Date.Sun) then incr we
|
||||
done;
|
||||
if !we = 5 then months := (year, month) :: !months
|
||||
done;
|
||||
done;
|
||||
Printf.printf "Number of months with 5 weekends: %d\n" (List.length !months);
|
||||
print_endline "First and last months between 1900 and 2100:";
|
||||
let print_month (year, month) = Printf.printf "%d-%02d\n" year month in
|
||||
List.iter print_month (list_first_five (List.rev !months));
|
||||
List.iter print_month (List.rev (list_first_five !months));
|
||||
;;
|
||||
12
Task/Five-weekends/Oforth/five-weekends.fth
Normal file
12
Task/Five-weekends/Oforth/five-weekends.fth
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
: fiveWeekEnd(y1, y2)
|
||||
| y m |
|
||||
|
||||
ListBuffer new
|
||||
y1 y2 for: y [
|
||||
Date.JANUARY Date.DECEMBER for: m [
|
||||
Date.DaysInMonth(y, m) 31 ==
|
||||
[ y, m, 01 ] asDate dayOfWeek Date.FRIDAY == and
|
||||
ifTrue: [ [ y, m ] over add ]
|
||||
]
|
||||
]
|
||||
dup size println dup left(5) println right(5) println ;
|
||||
20
Task/Five-weekends/PARI-GP/five-weekends.parigp
Normal file
20
Task/Five-weekends/PARI-GP/five-weekends.parigp
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
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);
|
||||
ly[12]=29;
|
||||
for(year=1900,2100,
|
||||
v=if((year+1)%4,ny,ly); \\ Works for 1600 to 2398
|
||||
for(month=1,12,
|
||||
if(v[month] == 31 && !day,
|
||||
if(month<11,
|
||||
print(year" "month+2)
|
||||
,
|
||||
print(year+1" 1")
|
||||
);
|
||||
s++
|
||||
);
|
||||
day = (day + v[month])%7
|
||||
)
|
||||
);
|
||||
s
|
||||
};
|
||||
25
Task/Five-weekends/PL-I/five-weekends.pli
Normal file
25
Task/Five-weekends/PL-I/five-weekends.pli
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
weekends: procedure options (main); /* 28/11/2011 */
|
||||
declare tally fixed initial (0);
|
||||
declare (d, dend, dn) fixed (10);
|
||||
declare (date_start, date_end) picture '99999999';
|
||||
declare Leap fixed (1);
|
||||
|
||||
date_start = '01011900';
|
||||
do date_start = date_start to '01012100';
|
||||
d = days(date_start, 'DDMMYYYY');
|
||||
date_end = date_start + 30110000;
|
||||
dend = days(date_end, 'DDMMYYYY');
|
||||
Leap = dend-d-364;
|
||||
do dn = d, d+59+Leap, d+120+Leap, d+181+Leap, d+212+Leap,
|
||||
d+273+Leap, d+334+Leap;
|
||||
if weekday(dn) = 6 then
|
||||
do;
|
||||
put skip list (daystodate(dn, 'MmmYYYY') || ' has 5 weekends' );
|
||||
tally = tally + 1;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
|
||||
put skip list ('Total number of months having 3-day weekends =', tally);
|
||||
|
||||
end weekends;
|
||||
34
Task/Five-weekends/Perl/five-weekends.pl
Normal file
34
Task/Five-weekends/Perl/five-weekends.pl
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
#!/usr/bin/perl -w
|
||||
use DateTime ;
|
||||
|
||||
my @happymonths ;
|
||||
my @workhardyears ;
|
||||
my @longmonths = ( 1 , 3 , 5 , 7 , 8 , 10 , 12 ) ;
|
||||
my @years = 1900..2100 ;
|
||||
foreach my $year ( @years ) {
|
||||
my $countmonths = 0 ;
|
||||
foreach my $month ( @longmonths ) {
|
||||
my $dt = DateTime->new( year => $year ,
|
||||
month => $month ,
|
||||
day => 1 ) ;
|
||||
if ( $dt->day_of_week == 5 ) {
|
||||
$countmonths++ ;
|
||||
my $yearfound = $dt->year ;
|
||||
my $monthfound = $dt->month_name ;
|
||||
push ( @happymonths , "$yearfound $monthfound" ) ;
|
||||
}
|
||||
}
|
||||
if ( $countmonths == 0 ) {
|
||||
push ( @workhardyears, $year ) ;
|
||||
}
|
||||
}
|
||||
print "There are " . @happymonths . " months with 5 full weekends!\n" ;
|
||||
print "The first 5 and the last 5 of them are:\n" ;
|
||||
foreach my $i ( 0..4 ) {
|
||||
print "$happymonths[ $i ]\n" ;
|
||||
}
|
||||
foreach my $i ( -5..-1 ) {
|
||||
print "$happymonths[ $i ]\n" ;
|
||||
}
|
||||
print "No long weekends in the following " . @workhardyears . " years:\n" ;
|
||||
map { print "$_\n" } @workhardyears ;
|
||||
33
Task/Five-weekends/Phix/five-weekends.phix
Normal file
33
Task/Five-weekends/Phix/five-weekends.phix
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
(phixonline)-->
|
||||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #000000;">nmonths</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
|
||||
<span style="color: #004080;">string</span> <span style="color: #000000;">months</span>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<span style="color: #000000;">months</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #000000;">nmonths</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<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;">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>
|
||||
<span style="color: #008080;">else</span>
|
||||
<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>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<!--
|
||||
47
Task/Five-weekends/Picat/five-weekends.picat
Normal file
47
Task/Five-weekends/Picat/five-weekends.picat
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
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.
|
||||
17
Task/Five-weekends/PicoLisp/five-weekends.l
Normal file
17
Task/Five-weekends/PicoLisp/five-weekends.l
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
(setq Lst
|
||||
(make
|
||||
(for Y (range 1900 2100)
|
||||
(for M (range 1 12)
|
||||
(and
|
||||
(date Y M 31)
|
||||
(= "Friday" (day (date Y M 1)))
|
||||
(link (list (get *Mon M) Y)) ) ) ) ) )
|
||||
|
||||
(prinl "There are " (length Lst) " months with five weekends:")
|
||||
(mapc println (head 5 Lst))
|
||||
(prinl "...")
|
||||
(mapc println (tail 5 Lst))
|
||||
(prinl)
|
||||
(setq Lst (diff (range 1900 2100) (uniq (mapcar cadr Lst))))
|
||||
(prinl "There are " (length Lst) " years with no five-weekend months:")
|
||||
(println Lst)
|
||||
18
Task/Five-weekends/Pike/five-weekends.pike
Normal file
18
Task/Five-weekends/Pike/five-weekends.pike
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
int(0..1) weekends(object day)
|
||||
{
|
||||
return (<5,6,7>)[day->week_day()];
|
||||
}
|
||||
|
||||
int(0..1) has5(object month)
|
||||
{
|
||||
return sizeof(filter(month->days(), weekends))==15;
|
||||
}
|
||||
|
||||
object range = Calendar.Year(1900)->distance(Calendar.Year(2101));
|
||||
array have5 = filter(range->months(), has5);
|
||||
|
||||
write("found %d months:\n%{%s\n%}...\n%{%s\n%}",
|
||||
sizeof(have5), have5[..4]->format_nice(), have5[<4..]->format_nice());
|
||||
|
||||
array rest = range->years() - have5->year();
|
||||
write("%d years without any 5 weekend month:\n %{%d,%}\n", sizeof(rest), rest->year_no());
|
||||
20
Task/Five-weekends/PowerShell/five-weekends.psh
Normal file
20
Task/Five-weekends/PowerShell/five-weekends.psh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
$fiveWeekends = @()
|
||||
$yearsWithout = @()
|
||||
foreach ($y in 1900..2100) {
|
||||
$hasFiveWeekendMonth = $FALSE
|
||||
foreach ($m in @("01","03","05","07","08",10,12)) {
|
||||
if ((Get-Date "$y-$m-1").DayOfWeek -eq "Friday") {
|
||||
$fiveWeekends += "$y-$m"
|
||||
$hasFiveWeekendMonth = $TRUE
|
||||
}
|
||||
}
|
||||
if ($hasFiveWeekendMonth -eq $FALSE) {
|
||||
$yearsWithout += $y
|
||||
}
|
||||
}
|
||||
Write-Output "Between the years 1900 and 2100, inclusive, there are $($fiveWeekends.count) months with five full weekends:"
|
||||
Write-Output "$($fiveWeekends[0..4] -join ","),...,$($fiveWeekends[-5..-1] -join ",")"
|
||||
|
||||
Write-Output ""
|
||||
Write-Output "Extra Credit: these $($yearsWithout.count) years have no such month:"
|
||||
Write-Output ($yearsWithout -join ",")
|
||||
72
Task/Five-weekends/Prolog/five-weekends.pro
Normal file
72
Task/Five-weekends/Prolog/five-weekends.pro
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
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).
|
||||
66
Task/Five-weekends/PureBasic/five-weekends.basic
Normal file
66
Task/Five-weekends/PureBasic/five-weekends.basic
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
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
|
||||
Protected days
|
||||
days = (year) * 365 + (month - 1) * 31 + day - 1 - 719527 ;DAYS_UNTIL_1970_01_01 = 719527
|
||||
If month >= 3
|
||||
days - Int(0.4 * month + 2.3)
|
||||
Else
|
||||
year - 1
|
||||
EndIf
|
||||
days + Int(year/4) - Int(year/100) + Int(year/400)
|
||||
|
||||
ProcedureReturn days
|
||||
EndProcedure
|
||||
|
||||
Procedure startsOnFriday(year, month)
|
||||
;0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
|
||||
Protected referenceDay = DayOfWeek(Date(1970, 1, 1, 0, 0, 0)) ;link to the first day in the PureBasic's date library
|
||||
Protected resultDay = (((DateG(year, month, 1) + referenceDay) % 7) + 7) % 7
|
||||
If resultDay = 5
|
||||
ProcedureReturn #True
|
||||
EndIf
|
||||
EndProcedure
|
||||
|
||||
Procedure has31Days(month)
|
||||
Select month
|
||||
Case 1, 3, 5, 7 To 8, 10, 12
|
||||
ProcedureReturn #True
|
||||
EndSelect
|
||||
EndProcedure
|
||||
|
||||
Procedure checkMonths(year)
|
||||
Protected month, count
|
||||
For month = 1 To 12
|
||||
If startsOnFriday(year, month) And has31Days(month)
|
||||
count + 1
|
||||
PrintN(Str(year) + " " + Str(month))
|
||||
EndIf
|
||||
Next
|
||||
ProcedureReturn count
|
||||
EndProcedure
|
||||
|
||||
Procedure fiveWeekends()
|
||||
Protected startYear = 1900, endYear = 2100, year, monthTotal, total
|
||||
NewList yearsWithoutFiveWeekends()
|
||||
|
||||
For year = startYear To endYear
|
||||
monthTotal = checkMonths(year)
|
||||
total + monthTotal
|
||||
;extra credit
|
||||
If monthTotal = 0
|
||||
AddElement(yearsWithoutFiveWeekends())
|
||||
yearsWithoutFiveWeekends() = year
|
||||
EndIf
|
||||
Next
|
||||
|
||||
PrintN("Total number of months: " + Str(total) + #CRLF$)
|
||||
PrintN("Years with no five-weekend months: " + Str(ListSize(yearsWithoutFiveWeekends())) )
|
||||
EndProcedure
|
||||
|
||||
If OpenConsole()
|
||||
fiveWeekends()
|
||||
|
||||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
|
||||
CloseConsole()
|
||||
EndIf
|
||||
38
Task/Five-weekends/Python/five-weekends-1.py
Normal file
38
Task/Five-weekends/Python/five-weekends-1.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
from datetime import (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 five_weekends_per_month(start: date = START,
|
||||
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 {len(dates)} months of which the first and last five are:")
|
||||
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
|
||||
- len({d.year for d in dates}))
|
||||
print(f"\nThere are {years_without_five_weekends_months} years in the "
|
||||
f"range that do not have months with five weekends")
|
||||
12
Task/Five-weekends/Python/five-weekends-2.py
Normal file
12
Task/Five-weekends/Python/five-weekends-2.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
LONGMONTHS = (1, 3, 5, 7, 8, 10, 12) # Jan Mar May Jul Aug Oct Dec
|
||||
|
||||
|
||||
def five_weekends_per_month2(start: date = START,
|
||||
stop: date = STOP) -> list[date]:
|
||||
return [last_day
|
||||
for year in range(start.year, stop.year)
|
||||
for month in LONG_MONTHS
|
||||
if (last_day := date(year, month, 31)).weekday() == 6] # Sunday
|
||||
|
||||
dates2 = five_weekends_per_month2()
|
||||
assert dates2 == dates
|
||||
65
Task/Five-weekends/Quackery/five-weekends.quackery
Normal file
65
Task/Five-weekends/Quackery/five-weekends.quackery
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
[ 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$ ] ]
|
||||
6
Task/Five-weekends/R/five-weekends.r
Normal file
6
Task/Five-weekends/R/five-weekends.r
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
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 = ", "))
|
||||
31
Task/Five-weekends/REXX/five-weekends-1.rexx
Normal file
31
Task/Five-weekends/REXX/five-weekends-1.rexx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/*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. */
|
||||
parse arg yStart yStop . /*get the "start" and "stop" years.*/
|
||||
if yStart=='' | yStart=="," then yStart= 1900 /*Not specified? Then use the default.*/
|
||||
if yStop =='' | yStop =="," then yStop = 2100 /* " " " " " " */
|
||||
years=yStop - yStart + 1 /*calculate the number of yrs in range.*/
|
||||
haps=0 /*number of five weekends happenings. */
|
||||
!.=0; @5w= 'five-weekend months' /*flag if a year has any five-weekends.*/
|
||||
do y=yStart to yStop /*process the years specified. */
|
||||
do m=1 for 12; wd.=0 /*process each month and also each year*/
|
||||
do d=1 for month.m; dat_= y"-"right(m,2,0)'-'right(d,2,0)
|
||||
parse upper value date('W', dat_, "I") with ? 3
|
||||
wd.?=wd.?+1 /*? is the first two chars of weekday.*/
|
||||
end /*d*/ /*WD.su = number of Sundays in a month.*/
|
||||
if wd.su\==5 | wd.fr\==5 | wd.sa\==5 then iterate /*five weekends ?*/
|
||||
say 'There are five weekends in' y date('M', dat_, "I")
|
||||
haps=haps+1; !.y=1 /*bump counter; indicate yr has 5 WE's.*/
|
||||
end /*m*/
|
||||
end /*y*/
|
||||
say
|
||||
say "There were " haps ' occurrence's(haps) "of" @5w 'in year's(years) yStart"──►"yStop
|
||||
say; #=0
|
||||
do y=yStart to yStop; if !.y then iterate /*skip if OK.*/
|
||||
#=#+1; say 'Year ' y " doesn't have any" @5wem'.'
|
||||
end /*y*/
|
||||
say
|
||||
say "There are " # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop
|
||||
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.*/
|
||||
37
Task/Five-weekends/REXX/five-weekends-2.rexx
Normal file
37
Task/Five-weekends/REXX/five-weekends-2.rexx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/*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. */
|
||||
@months='January February March April May June July August September October November December'
|
||||
parse arg yStart yStop . /*get the "start" and "stop" years.*/
|
||||
if yStart=='' | yStart=="," then yStart= 1900 /*Not specified? Then use the default.*/
|
||||
if yStop =='' | yStop =="," then yStop = 2100 /* " " " " " " */
|
||||
years=yStop - yStart + 1 /*calculate the number of yrs in range.*/
|
||||
haps=0 /*number of five weekends happenings. */
|
||||
!.=0; @5w= 'five-weekend months' /*flag if a year has any five-weekends.*/
|
||||
do y=yStart to yStop /*process the years specified. */
|
||||
do m=1 for 12; wd.=0 /*process each month and also each year*/
|
||||
do d=1 for month.m
|
||||
?=dow(m,d,y) /*get the day-of-week for mm/dd/yyyy*/
|
||||
wd.?=wd.?+1 /*?: 1=Sun, 2=Mon, 3=Tue ∙∙∙ 7=Sat.*/
|
||||
end /*d*/
|
||||
if wd.1\==5 | wd.6\==5 | wd.7\==5 then iterate /*not a weekend ? */
|
||||
say 'There are five weekends in' y word(@months, m)
|
||||
haps=haps+1; !.y=1 /*bump counter; indicate yr has 5 WE's.*/
|
||||
end /*m*/
|
||||
end /*y*/
|
||||
say
|
||||
say 'There were ' haps " occurrence"s(haps) 'of' @5w "in year"s(years) yStart'──►'yStop
|
||||
#=0; say
|
||||
do y=yStart to yStop; if !.y then iterate /*skip if OK.*/
|
||||
#=#+1
|
||||
say 'Year ' y " doesn't have any five-weekend months."
|
||||
end /*y*/
|
||||
say
|
||||
say "There are " # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
dow: procedure; parse arg m,d,y; if m<3 then do; m=m+12; y=y-1; end
|
||||
yL=left(y,2); yr=right(y,2); w=(d+(m+1)*26%10+yr+yr%4+yL%4+5*yL) // 7
|
||||
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.*/
|
||||
55
Task/Five-weekends/REXX/five-weekends-3.rexx
Normal file
55
Task/Five-weekends/REXX/five-weekends-3.rexx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
/* REXX ***************************************************************
|
||||
* Short(er) solution focussed at the task's description
|
||||
* Only 7 months can have 5 full weekends
|
||||
* and it's enough to test if the 1st day of the month is a Friday
|
||||
* 30.08.2012 Walter Pachl
|
||||
**********************************************************************/
|
||||
Numeric digits 20
|
||||
nr5fwe=0
|
||||
years_without_5fwe=0
|
||||
mnl='Jan Mar May Jul Aug Oct Dec'
|
||||
ml='1 3 5 7 8 10 12'
|
||||
Do j=1900 to 2100
|
||||
year_has_5fwe=0
|
||||
Do mi=1 To words(ml)
|
||||
m=word(ml,mi)
|
||||
jd=greg2jul(j m 1)
|
||||
IF jd//7=4 Then Do /* 1st m j is a Friday */
|
||||
nr5fwe=nr5fwe+1
|
||||
year_has_5fwe=1
|
||||
If j<=1905 | 2095<=j Then
|
||||
Say word(mnl,mi) j 'has 5 full weekends'
|
||||
End
|
||||
End
|
||||
If j=1905 Then Say '...'
|
||||
if year_has_5fwe=0 Then years_without_5fwe=years_without_5fwe+1
|
||||
End
|
||||
Say ' '
|
||||
Say nr5fwe 'occurrences of 5 full weekends in a month'
|
||||
Say years_without_5fwe 'years without 5 full weekends'
|
||||
exit
|
||||
|
||||
greg2jul: Procedure
|
||||
/***********************************************************************
|
||||
* Converts a Gregorian date to the corresponding Julian day number
|
||||
* 19891101 Walter Pachl REXXified algorithm published in CACM
|
||||
* (Fliegel & vanFlandern, CACM Vol.11 No.10 October 1968)
|
||||
* 19891125 PA copy leapyear test into this to avoid the dependency
|
||||
***********************************************************************/
|
||||
numeric digits 12
|
||||
Parse Arg yy mm d
|
||||
If mm<1 | 12<mm Then Call err 'month ('mm') not within 1 to 12'
|
||||
mdl='31' (28+leapyear(yy)) '31 30 31 30 31 31 30 31 30 31'
|
||||
md=word(mdl,mm)
|
||||
If d<1 | md<d Then Call err 'day ('d') not within 1 to' md
|
||||
/***********************************************************************
|
||||
* The published formula:
|
||||
* res=d-32075+1461*(yy+4800+(mm-14)%12)%4+,
|
||||
* 367*(mm-2-((mm-14)%12)*12)%12-3*((yy+4900+(mm-14)%12)%100)%4
|
||||
***********************************************************************/
|
||||
mma=(mm-14)%12
|
||||
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 */
|
||||
|
||||
leapyear: Return ( (arg(1)//4=0) & (arg(1)//100<>0) ) | (arg(1)//400=0)
|
||||
30
Task/Five-weekends/REXX/five-weekends-4.rexx
Normal file
30
Task/Five-weekends/REXX/five-weekends-4.rexx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/*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. */
|
||||
parse arg yStart yStop . /*get the "start" and "stop" years.*/
|
||||
if yStart=='' | yStart=="," then yStart= 1900 /*Not specified? Then use the default.*/
|
||||
if yStop =='' | yStop =="," then yStop = 2100 /* " " " " " " */
|
||||
years=yStop - yStart + 1 /*calculate the number of yrs in range.*/
|
||||
haps=0 /*number of five weekends happenings. */
|
||||
!.=0; @5w= 'five-weekend months' /*flag if a year has any five-weekends.*/
|
||||
do y=yStart to yStop /*process the years specified. */
|
||||
do m=1 for 12; wd.=0 /*process each month and also each year*/
|
||||
do d=1 for month.m; dat_= y"-"right(m, 2, 0)'-'right(d, 2, 0)
|
||||
parse upper value date('W', dat_, "I") with ? 3
|
||||
wd.?=wd.?+1 /*?: 1=Sun, 2=Mon, 3=Tue ∙∙∙ 7=Sat.*/
|
||||
end /*d*/ /*WD.su=number of Sundays in the month.*/
|
||||
if wd.su\==5 | wd.fr\==5 | wd.sa\==5 then iterate /*is this a weekend ? */
|
||||
say 'There are five weekends in' y date('M', dat_, "I")
|
||||
haps=haps+1; !.y=1 /*bump counter; indicate yr has 5 WE's.*/
|
||||
end /*m*/
|
||||
end /*y*/
|
||||
say
|
||||
say 'There were ' haps " occurrence"s(haps) 'of' @5w "in year"s(years) yStart'──►'yStop
|
||||
#=0; say
|
||||
do y=yStart to yStop; if !.y then iterate /*skip if OK.*/
|
||||
#=#+1
|
||||
say 'Year ' y " doesn't have any five-weekend months."
|
||||
end /*y*/
|
||||
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. */
|
||||
27
Task/Five-weekends/REXX/five-weekends-5.rexx
Normal file
27
Task/Five-weekends/REXX/five-weekends-5.rexx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/*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.*/
|
||||
month.4=30; month.6=30; month.9=30; month.11=30 /*all the months with thirty-days. */
|
||||
parse arg yStart yStop . /*get the "start" and "stop" years.*/
|
||||
if yStart=='' | yStart=="," then yStart= 1900 /*Not specified? Then use the default.*/
|
||||
if yStop =='' | yStop =="," then yStop = 2100 /* " " " " " " */
|
||||
years=yStop - yStart + 1 /*calculate the number of yrs in range.*/
|
||||
haps=0 /*number of five weekends happenings. */
|
||||
!.=0; @5w= 'five-weekend months' /*flag if a year has any five-weekends.*/
|
||||
do y=yStart to yStop /*process the years specified. */
|
||||
do m=1 for 12; if month.m==0 then iterate /*only test 31-day months.*/
|
||||
dat_= y"-"right(m,2,0)'-01' /*get the date in the desired format. */
|
||||
if left(date('W',dat_,"I"),2)\=='Fr' then iterate /*isn't not a Friday? */
|
||||
say 'There are five weekends in' y date('M', dat_, "I")
|
||||
haps=haps+1; !.y=1 /*bump counter; indicate yr has 5 WE's.*/
|
||||
end /*m*/
|
||||
end /*y*/
|
||||
say
|
||||
say 'There were ' haps " occurrence"s(haps) 'of' @5w "in year"s(years) yStart'──►'yStop
|
||||
#=0; say
|
||||
do y=yStart to yStop; if !.y then iterate /*skip if OK.*/
|
||||
#=#+1
|
||||
say 'Year ' y " doesn't have any five-weekend months."
|
||||
end /*y*/
|
||||
say
|
||||
say "There are " # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop
|
||||
26
Task/Five-weekends/Racket/five-weekends.rkt
Normal file
26
Task/Five-weekends/Racket/five-weekends.rkt
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
#lang racket
|
||||
(require srfi/19)
|
||||
|
||||
(define long-months '(1 3 5 7 8 10 12))
|
||||
(define days #(sun mon tue wed thu fri sat))
|
||||
|
||||
(define (week-day date)
|
||||
(vector-ref days (date-week-day date)))
|
||||
|
||||
(define (five-weekends-a-month start end)
|
||||
(for*/list ([year (in-range start (+ end 1))]
|
||||
[month long-months]
|
||||
[date (in-value (make-date 0 0 0 0 31 month year 0))]
|
||||
#:when (eq? (week-day date) 'sun))
|
||||
date))
|
||||
|
||||
(define weekends (five-weekends-a-month 1900 2100))
|
||||
(define count (length weekends))
|
||||
|
||||
(displayln (~a "There are " count " months with five weekends."))
|
||||
(displayln "The first five are: ")
|
||||
(for ([w (take weekends 5)])
|
||||
(displayln (date->string w "~b ~Y")))
|
||||
(displayln "The last five are: ")
|
||||
(for ([w (drop weekends (- count 5))])
|
||||
(displayln (date->string w "~b ~Y")))
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue