//In what years between 2008 and 2121 will the 25th of December be a Sunday?

IMPORT STD;

BaseYear := 2008;
EndYear  := 2121;

ChristmasDay := RECORD
  UNSIGNED1 DayofWeek;
  UNSIGNED2 Year;
END;

ChristmasDay FindDate(INTEGER Ctr) := TRANSFORM
  SELF.DayofWeek := (STD.Date.FromGregorianYMD((BaseYear-1) + Ctr,12,25)) % 7; //0=Sunday
  SELF.Year := (BaseYear-1) + Ctr;
END;

YearDS := DATASET(EndYear-BaseYear,FindDate(COUNTER));
OUTPUT(YearDS(DayofWeek=0),{Year});

/* Outputs:
   2011
   2016
   2022
   2033
   2039
   2044
   2050
   2061
   2067
   2072
   2078
   2089
   2095
   2101
   2107
   2112
   2118
*/


Enum.each(2008..2121, fn year ->
  wday = Date.from_erl!({year, 12, 25}) |> Date.day_of_week
  if wday==7, do: IO.puts "25 December #{year} is sunday"
end)


(require 'calendar)

(defun sunday-p (y)
  "Is Dec 25th a Sunday in this year?"
  (= (calendar-day-of-week (list 12 25 y)) 0))

(defun xmas-sunday (a b)
  "In which years in the range a, b is Dec 25th a Sunday?"
  (seq-filter #'sunday-p (number-sequence a b)))

(print (xmas-sunday 2008 2121))


% Implemented by bengt kleberg
-module(yuletide).
-export([main/0, sunday_years/2]).

main() ->
	[io:fwrite("25 December ~p is Sunday~n", [X]) || X <- sunday_years(2008, 2121)].

sunday_years( Start, Stop ) ->
	[X || X <- lists:seq(Start, Stop), is_sunday(calendar:day_of_the_week({X, 12, 25}))].

is_sunday( 7 ) -> true;
is_sunday( _ ) -> false.


PROGRAM DAY_OF_THE_WEEK

PROCEDURE MODULO(X,Y->RES)
   IF Y=0 THEN
      RES=X
     ELSE
      RES=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
PRINT(CHR$(12);) ! CLS
FOR YR=2008 TO 2121 DO
    WD(12,25,YR->RES%)
    IF RES%=1 THEN  ! day 1 is Sunday......
      PRINT("Dec";25;",";YR)
    END IF
END FOR
GET(K$)
END PROGRAM


--Day of the week task from Rosetta Code wiki
--User:Lnettnay

--In what years between 2008 and 2121 will the 25th of December be a Sunday

include std/datetime.e

datetime dt

for year = 2008 to 2121 do
        dt = new(year, 12, 25)
        if weeks_day(dt) = 1 then -- Sunday = 1
                ? year
        end if
end for


open System

[ 2008 .. 2121 ]
|> List.choose (fun y -> if DateTime(y,12,25).DayOfWeek = DayOfWeek.Sunday then Some(y) else None)
|> printfn "%A"


USING: calendar math.ranges prettyprint sequences ;
2008 2121 [a,b] [ 12 25 <date> sunday? ] filter .


#APPTYPE CONSOLE

'In what years between 2008 and 2121 will the 25th of December be a Sunday?
DIM date AS INTEGER, dayname AS STRING
FOR DIM year = 2008 TO 2121
	date = year * 10000 + 1225
	dayname = dateconv(date,"dddd")
	IF dayname = "Sunday" THEN
		PRINT "Christmas Day is on a Sunday in ", year
	END IF
NEXT
PAUSE


\ Zeller's Congruence
: weekday ( d m y -- wd) \ 1 mon..7 sun
  over 3 < if 1- swap 12 + swap then
  100 /mod
  dup 4 / swap 2* -
  swap dup 4 / + +
  swap 1+ 13 5 */ + +
  ( in zeller 0=sat, so -2 to 0= mon, then mod, then 1+ for 1=mon)
  2- 7 mod 1+ ;

: yuletide
  ." December 25 is Sunday in "
  2122 2008 do
    25 12 i weekday
    7 = if i . then
  loop cr ;


PROGRAM YULETIDE

IMPLICIT NONE

INTEGER :: day, year

WRITE(*, "(A)", ADVANCE="NO") "25th of December is a Sunday in"
DO year = 2008, 2121
   day = Day_of_week(25, 12, year)
   IF (day == 1) WRITE(*, "(I5)", ADVANCE="NO") year
END DO

CONTAINS

FUNCTION Day_of_week(d, m, y)
   INTEGER :: Day_of_week, j, k, mm, yy
   INTEGER, INTENT(IN) :: d, m, y

   mm=m
   yy=y
   IF(mm.le.2) THEN
      mm=mm+12
      yy=yy-1
   END IF
   j = yy / 100
   k = MOD(yy, 100)
   Day_of_week = MOD(d + ((mm+1)*26)/10 + k + k/4 + j/4 + 5*j, 7)
END FUNCTION Day_of_week

END PROGRAM YULETIDE


window 1

long              y
CFDateRef         dt
NSInteger         day
CFCalendarRef     cal
DateComponentsRef comps

cal = fn CalendarCurrent

comps = fn DateComponentsInit
DateComponentsSetMonth( comps, 12 )
DateComponentsSetDay( comps, 25 )

for y = 2008 to 2121
  DateComponentsSetYear( comps, y )
  dt = fn CalendarDateFromComponents( cal, comps )
  day = fn CalendarComponentFromDate( cal, NSCalendarUnitWeekday, dt )
  if ( day == 1 )
    print y
  end if
next

HandleEvents


Public Sub Main()
Dim siCount As Short

For siCount = 2008 To 2121
  If WeekDay(Date(siCount, 12, 25)) = 0 Then Print Format(Date(siCount, 12, 25), "dddd dd mmmm yyyy") & " falls on a Sunday"
Next

End


package main

import "fmt"
import "time"

func main() {
    for year := 2008; year <= 2121; year++ {
        if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==
            time.Sunday {
            fmt.Printf("25 December %d is Sunday\n", year)
        }
    }
}


def yuletide = { start, stop -> (start..stop).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } }


import Data.Time (fromGregorian)
import Data.Time.Calendar.WeekDate (toWeekDate)

--------------------- DAY OF THE WEEK --------------------

isXmasSunday :: Integer -> Bool
isXmasSunday year = 7 == weekDay
  where
    (_, _, weekDay) = toWeekDate $ fromGregorian year 12 25

--------------------------- TEST -------------------------
main :: IO ()
main =
  mapM_
    putStrLn
    [ "Sunday 25 December " <> show year
      | year <- [2008 .. 2121],
        isXmasSunday year
    ]


DO year = 1, 1000000
   TIME(Year=year, MOnth=12, Day=25, TO, WeekDay=weekday)
   IF( weekday == 7) WRITE(StatusBar) year
ENDDO

END


link datetime

procedure main()
writes("December 25th is a Sunday in: ")
every writes((dayoweek(25,12,y := 2008 to 2122)=="Sunday",y)," ")
end


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Yuletide{
	public static void main(String[] args) {
		for(int i = 2008;i<=2121;i++){
			Calendar cal = new GregorianCalendar(i, Calendar.DECEMBER,
					25);
			if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
				System.out.println(cal.getTime());
			}
		}
	}
}


for (var year = 2008; year <= 2121; year++){
    var xmas = new Date(year, 11, 25)
    if ( xmas.getDay() === 0 )
        console.log(year)
}


# Use Zeller's Congruence to determine the day of the week, given
# year, month and day as integers in the conventional way.
# If iso == "iso" or "ISO", then emit an integer in 1 -- 7 where
# 1 represents Monday, 2 Tuesday, etc;
# otherwise emit 0 for Saturday, 1 for Sunday, etc.
#
def day_of_week(year; month; day; iso):
  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)
  | if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
    else . % 7
    end;


using Dates

lo, hi = 2008, 2121
xmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25))
filter!(xmas) do dt
    dayofweek(dt) == Dates.Sunday
end

println("Years from $lo to $hi having Christmas on Sunday: ")
foreach(println, year.(xmas))


// version 1.0.6

import java.util.*

fun main(args: Array<String>) {
    println("Christmas day in the following years falls on a Sunday:\n")
    val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25)
    for (year in 2008..2121) {
        if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year)
        calendar.add(Calendar.YEAR, 1)
    }
}


loop(-From=2008, -to=2121) => {^
  local(tDate = date('12/25/' + loop_count))
  #tDate->dayOfWeek == 1 ? '\r' + #tDate->format('%D') + ' is a Sunday'
^}


    count = 0
    for year = 2008 to 2121
        dateString$="12/25/";year
        dayNumber=date$(dateString$)

        if dayNumber mod 7 = 5 then
            count = count + 1
            print dateString$
        end if

    next year

    print count; " years when Christmas Day falls on a Sunday"
    end


put "December 25 is a Sunday in:"
refDateObj = date(1905,1,2)
repeat with year = 2008 to 2121
  dateObj = date(year, 12, 25)
  dayOfWeek = ((dateObj - refDateObj) mod 7)+1 -- 1=Monday..7=Sunday
  if dayOfWeek=7 then put year
end repeat


function xmasSunday startDate endDate
    convert the long date to dateitems
    put it into xmasDay
    put 12 into item 2 of xmasDay
    put 25 into item 3 of xmasDay
    repeat with i = startDate to endDate
        put i into item 1 of xmasDay
        convert xmasDay to dateItems
        if item 7 of xmasDay is 1 then put i & comma after xmasYear
    end repeat
    if the last char of xmasYear is comma then delete the last char of xmasYear
    return xmasYear
end xmasSunday


; Determine if a Gregorian calendar year is leap
to leap? :year
  output (and
    equal? 0 modulo :year 4
    not member? modulo :year 400 [100 200 300]
  )
end

; Convert Gregorian calendar date to a simple day count from
; day 1 = January 1, 1 CE
to day_number :year :month :day
  local "elapsed make "elapsed difference :year 1
  output (sum  product 365 :elapsed
              int quotient :elapsed 4
              minus int quotient :elapsed 100
              int quotient :elapsed 400
              int quotient difference product 367 :month 362 12
              ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2
              :day)
end

; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday
to day_of_week :day_number
  output modulo :day_number 7
end

; True if the given day is a Sunday
to sunday? :year :month :day
  output equal? 0 day_of_week day_number :year :month :day
end

; Put it all together to answer the question posed in the problem
print filter [sunday? ? 12 25] iseq 2008 2121
bye


require("date")

for year=2008,2121 do
   if date(year, 12, 25):getweekday() == 1 then
      print(year)
   end
end


Print "December 25 is a Sunday in:"
For Year=2008 to 2121 {
      if  Str$(Date("25/12/"+str$(Year,"")),"w")="1" Then {
            Print Year
      }
}
\\ is the same with this:
Print "December 25 is a Sunday in:"
For Year=2008 to 2121 {
      if  Str$(Date(str$(Year,"")+"-12-25"),"w")="1" Then {
            Print Year
      }
}


xmas:= proc()
	local i, dt;
	for i from 2008 to 2121 by 1 do
		dt := Date(i, 12, 25);
		if (Calendar:-DayOfWeek(dt) = 1) then
			print(i);
		end if;
	end do;
end proc;

xmas();


MODULE Yule EXPORTS Main;

IMPORT IO, Fmt, Date, Time;

VAR date: Date.T;
    time: Time.T;

BEGIN
  FOR year := 2008 TO 2121 DO
    date.day := 25;
    date.month := Date.Month.Dec;
    date.year := year;

    TRY
      time := Date.ToTime(date);
    EXCEPT
    | Date.Error =>
      IO.Put(Fmt.Int(year) & " is the last year we can specify\n");
      EXIT;
    END;

    date := Date.FromTime(time);

    IF date.weekDay = Date.WeekDay.Sun THEN
      IO.Put("25th of December " & Fmt.Int(year) & " is Sunday\n");
    END;
  END;
END Yule.


DOWHOLIDAY
 ;In what years between 2008 and 2121 will December 25 be a Sunday?
 ;Uses the VA's public domain routine %DTC (Part of the Kernel) named here DIDTC
 NEW BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y
 ;BDT - the beginning year to check
 ;EDT - the end year to check
 ;BDT and EDT are year offsets from the epoch date 1/1/1700
 ;CHECK - the month and day to look at
 ;CHKFOR - what day of the week to look for
 ;LIST - list of years in which the condition is true
 ;I - the year currently being checked
 ;X - the date in an "internal" format, for input to DOW^DIDTC
 ;Y - the output from DOW^DIDTC
 SET BDT=308,EDT=421,CHECK="1225",CHKFOR=0,LIST=""
 FOR I=BDT:1:EDT SET X=I_CHECK D DOW^DIDTC SET:(Y=0) LIST=$SELECT($LENGTH(LIST):LIST_", ",1:"")_(I+1700)
 IF $LENGTH(LIST)=0 WRITE !,"There are no years that have Christmas on a Sunday in the given range."
 IF $LENGTH(LIST) WRITE !,"The following years have Christmas on a Sunday: ",LIST
 KILL BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y
 QUIT


import Nanoquery.Util

// loop through the years 2008 through 2121
for year in range(2008, 2121)
	if (new(Date,"12/25/" + str(year)).getDayOfWeek() = "Sunday")
		println "In " + year + ", December 25th is a Sunday."
	end if
end for


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

yearRanges = [int 2008, 2121]
searchday = ''
cal = Calendar

loop year = yearRanges[0] to yearRanges[1]
  cal = GregorianCalendar(year, Calendar.DECEMBER, 25)
  dayIndex = cal.get(Calendar.DAY_OF_WEEK)
  if dayIndex = Calendar.SUNDAY then searchday = searchday year
  end year

say 'Between' yearRanges[0] 'and' yearRanges[1]', Christmas day falls on a Sunday on the following years:'
searchday = searchday.strip.changestr(' ', ',')
say '  'searchday

return


import times

for year in 2008..2121:
  if getDayOfWeek(25, mDec, year) == dSun:
    stdout.write year, ' '
echo ""


MODULE DayOfWeek;
IMPORT NPCT:Dates, Out;
VAR
  year: INTEGER;
  date: Dates.Date;
BEGIN
  FOR year := 2008 TO 2121 DO
    date := Dates.NewDate(25,12,year);
    IF date.DayOfWeek() = Dates.sunday THEN
     Out.Int(date.year,4);Out.Ln
    END
  END
END DayOfWeek.


#import <Foundation/Foundation.h>

int main()
{
   @autoreleasepool {
      for(NSUInteger i=2008; i<2121; i++)
      {
         NSCalendarDate *d = [[NSCalendarDate alloc]
                              initWithYear: i
                              month: 12
                              day: 25
                              hour: 0 minute: 0 second:0
                              timeZone: [NSTimeZone timeZoneWithAbbreviation:@"CET"] ];
         if ( [d dayOfWeek] == 0 )
         {
            printf("25 Dec %u is Sunday\n", i);
         }
      }

   }
   return 0;
}


#load "unix.cma"
open Unix

try
  for i = 2008 to 2121 do
    (* I'm lazy so we'll just borrow the current time
       instead of having to set all the fields explicitly *)
    let mytime = { (localtime (time ())) with
                   tm_year  = i - 1900;
                   tm_mon   = 11;
                   tm_mday  = 25 } in
    try
      let _, mytime = mktime mytime in
        if mytime.tm_wday = 0 then
          Printf.printf "25 December %d is Sunday\n" i
    with e ->
      Printf.printf "%d is the last year we can specify\n" (i-1);
      raise e
  done
with _ -> ()


import: date
seqFrom(2008, 2121) filter(#[ 12 25 Date newDate dayOfWeek Date.SUNDAY == ]) .


date = .datetime~new(2008, 12, 25)
lastdate = .datetime~new(2121, 12, 25)

resultList = .array~new -- our collector of years

-- date objects are directly comparable
loop while date <= lastdate
  if date~weekday == 7 then resultList~append(date~year)
  -- step to the next year
  date = date~addYears(1)
end

say "Christmas falls on Sunday in the years" resultList~toString("Line", ", ")


<@ SAI>
	<@ ITEFORLI3>2121|2008|
		<@ LETVARCAP>Christmas Day|25-Dec-<@ SAYVALFOR>...</@></@>
		<@ TSTDOWVARLIT>Christmas Day|1</@>
		<@ IFF>
			<@ SAYCAP>Christmas Day <@ SAYVALFOR>...</@> is a Sunday</@><@ SAYKEY>__Newline</@>
		</@>
	</@>
</@>


#! /usr/bin/perl -w

use Time::Local;
use strict;

foreach my $i (2008 .. 2121)
{
  my $time = timelocal(0,0,0,25,11,$i);
  my ($s,$m,$h,$md,$mon,$y,$wd,$yd,$is) = localtime($time);
  if ( $wd == 0 )
  {
    print "25 Dec $i is Sunday\n";
  }
}

exit 0;


-- demo\rosetta\Day_of_the_week.exw
sequence res = {}
for y=2008 to 2121 do
    if day_of_week(y,12,25,true)="Sunday" then
        res = append(res,y)
    end if
end for
?res


(for (Y 2008 (>= 2121 Y) (inc Y))
   (when (= "Sunday" (day (date Y 12 25)))
      (printsp Y) ) )


filter(Calendar.Year(2008)->range(Calendar.Year(2121))->years()->month(12)->day(25), lambda(object day){ return day->week_day()==7; })->year()->format_nice();


declare i picture '9999';
do i = 2008 to 2121;
   if weekday(days('25Dec' || i, 'DDMmmYYYY')) = 1 then
      put skip list ('Christmas day ' || i || ' is a Sunday');
end;


2008..2121 | Where-Object { (Get-Date $_-12-25).DayOfWeek -eq "Sunday" }


main() :-
    christmas_days_falling_on_sunday(2011, 2121, SundayList),
    writeln(SundayList).

christmas_days_falling_on_sunday(StartYear, EndYear, SundayList) :-
    numlist(StartYear, EndYear, YearRangeList),
    include(is_christmas_day_a_sunday, YearRangeList, SundayList).

is_christmas_day_a_sunday(Year) :-
    Date = date(Year, 12, 25),
    day_of_the_week(Date, DayOfTheWeek),
    DayOfTheWeek == 7.


For i=2008 To 2037
  If DayOfWeek(Date(i,12,25,0,0,0))=0
    PrintN(Str(i))
  EndIf
Next


from calendar import weekday, SUNDAY

[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]


  [ 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 )

say "The 25th of December is a Sunday in: " cr
2121 1+ 2008 - times
  [ 25 12 i^ 2008 + dayofweek
    0 = if [ i^ 2008 + echo sp ] ]


years <- 2008:2121
xmas <- as.POSIXlt(paste0(years, '/12/25'))
years[xmas$wday==0]
# 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118

# Also:
xmas=seq(as.Date("2008/12/25"), as.Date("2121/12/25"), by="year")
as.numeric(format(xmas[weekdays(xmas)== 'Sunday'], "%Y"))

# Still another solution, using ISOdate and weekdays
with(list(years=2008:2121), years[weekdays(ISOdate(years, 12, 25)) == "Sunday"])

# Or with "subset"
subset(data.frame(years=2008:2121), weekdays(ISOdate(years, 12, 25)) == "Sunday")$years

# Simply replace "Sunday" with whatever it's named in your country,
# or set locale first, with
Sys.setlocale(cat="LC_ALL", "en")

# Under MS Windows, write instead
Sys.setlocale("LC_ALL", "English")


#lang racket

(require racket/date)

(define (xmas-on-sunday? year)
  (zero? (date-week-day (seconds->date (find-seconds 0 0 12 25 12 year)))))

(for ([y (in-range 2008 2121)] #:when (xmas-on-sunday? y))
  (displayln y))


rebol [
	Title: "Yuletide Holiday"
	URL: http://rosettacode.org/wiki/Yuletide_Holiday
]

for y 2008 2121 1 [
	d: to-date reduce [y 12 25]
	if 7 = d/weekday [prin [y ""]]
]


Red []
repeat yy 114 [
  d: to-date reduce [25 12 (2007 + yy )]
  if 7 = d/weekday [ print d ] ;; 7 = sunday
]
;; or
print "version 2"

d: to-date [25 12 2008]
while [d <= 25/12/2121 ] [
  if 7 = d/weekday [
    print rejoin [d/day '. d/month '. d/year ]
  ]
  d/year: d/year + 1
]


    do year=2008 to 2121
    if date('w', year"1225", 's') == 'Sunday'  then say year
    end   /*year*/


require 'date'

(2008..2121).each {|year| puts "25 Dec #{year}" if Date.new(year, 12, 25).sunday? }


for year = 2008 to 2121
 if val(date$("12-25-";year)) mod 7 = 5 then print "For ";year;"xmas is Sunday"
next year


extern crate chrono;

use chrono::prelude::*;

fn main() {
    let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>();
    println!("Years = {:?}", years);
}


$constant SUNDAY = 0

rem - compute p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)

comment
    return day of week (Sun = 0, Mon = 1, etc.) for a
    given Gregorian calendar date using Zeller's congruence
end
function dayofweek (mo, da, yr = integer) = integer
    var y, c, z = integer
    if mo < 3 then
        begin
            mo = mo + 10
            yr = yr - 1
        end
    else mo = mo - 2
    y = mod(yr,100)
    c = int(yr / 100)
    z = int((26 * mo - 2) / 10)
    z = z + da + y + int(y/4) + int(c/4) - 2 * c + 777
    z = mod(z,7)
end = z

rem - main program
var year = integer
print "Christmas will fall on a Sunday in"
for year=2008 to 2121
   if dayofweek(12,25,year) = SUNDAY then
      print year
next year
end


import java.util.{ Calendar, GregorianCalendar }
import Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }

object DayOfTheWeek extends App {
  val years = 2008 to 2121

  val yuletide =
    years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY)

  // If you want a test: (optional)
  assert(yuletide ==
    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))

  println(yuletide.mkString(
    s"${yuletide.length} Years between ${years.head} and ${years.last}" +
      " including where Christmas is observed on Sunday:\n", ", ", "."))
}


$ include "seed7_05.s7i";
  include "time.s7i";

const proc: main is func
  local
    var integer: year is 0;
  begin
    for year range 2008 to 2122 do
      if dayOfWeek(date(year, 12, 25)) = 7 then
        writeln("Christmas comes on a sunday in " <& year);
      end if;
    end for;
  end func;


// In what years between 2008 and 2121 will the 25th of December be a Sunday?

repeat with year = 2008 to 2121
	set Christmas to "12/25/" & year
	if the WeekDayName of Christmas is Sunday then
		put "Christmas in " & year & " falls on a Sunday"
	end if
end repeat


require('Time::Local')

for year in (2008 .. 2121) {
    var time = %S<Time::Local>.timelocal(0,0,0,25,11,year)
    var wd = Time(time).local.wday
    if (wd == 0) {
        say "25 Dec #{year} is Sunday"
    }
}


BEGIN
    INTEGER M,D,Y;
    M := 12;
    D := 25;
    FOR Y := 2008 STEP 1 UNTIL 2121 DO BEGIN
        INTEGER W,A,MM,YY;
        A := (14 - M)//12;
        MM := M + 12*A - 2;
        YY := Y - A;
        W := D + ((13*MM - 1)//5) + YY + (YY//4) - (YY//100) + (YY//400);
        W := MOD(W,7);
        IF W = 0 THEN
        BEGIN OUTINT(Y,0);
              OUTIMAGE;
        END;
    END;
END.


2008 to: 2121 do: [ :year | |date|
     date := Date newDay: 25 monthIndex: 12 year: year.
     date dayName = #Sunday
       ifTrue: [ date displayNl ]
]


SELECT EXTRACT(YEAR FROM dt) AS year_with_xmas_on_sunday
FROM   (
         SELECT  add_months(DATE '2008-12-25', 12 * (level - 1)) AS dt
         FROM    dual
         CONNECT BY level <= 2121 - 2008 + 1
       )
WHERE  to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'
ORDER  BY 1
;


(* Call:  yearsOfSundayXmas(2008, 2121)   *)
fun yearsOfSundayXmas(fromYear, toYear) =
  if fromYear>toYear then
    ()
  else
    let
      val d = Date.date {year=fromYear, month=Date.Dec, day=25,
              hour=0, minute=0, second=0,
                      offset=SOME Time.zeroTime}
      val wd = Date.weekDay d
    in
      if wd=Date.Sun then
        (
          print(Int.toString fromYear ^ "\n");
          yearsOfSundayXmas(fromYear+1, toYear)
        )
      else
        yearsOfSundayXmas(fromYear+1, toYear)
    end;


year = 2008
while (year <= 2121)
    {
    if Date('#' $ year $ '1225').WeekDay() is 0
        Print(year)
    ++year
    }


import Cocoa

var year=2008
let formatter=NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"

let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
while (year<2122){
    var date:NSDate!=formatter.dateFromString(String(year)+"-12-25")
    var components=gregorian.components(NSCalendarUnit.CalendarUnitWeekday, fromDate: date)
    var dayOfWeek:NSInteger=components.weekday
    if(dayOfWeek==1){
        println(year)
    }
    year++
}


package require Tcl 8.5

for {set y 2008} {$y <= 2121} {incr y} {
    if {[clock format [clock scan "$y-12-25" -format {%Y-%m-%d}] -format %w] == 0} {
        puts "xmas $y is a sunday"
    }
}


$$ MODE TUSCRIPT
PRINT "25th of December will be a Sunday in the following years: "
LOOP year=2008,2121
SET dayofweek = DATE (number,25,12,year,nummer)
IF (dayofweek==7) PRINT year
ENDLOOP


// Find years with Sunday Christmas
var f = 2008;
var t = 2121;
console.log(`Sunday Christmases ${f} - ${t}`);
for (y = f; y <= t; y++) {
  var x = (y * 365) + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 6;
  if (x % 7 == 0)
    process.stdout.write(`${y}\t`);
}
process.stdout.write("\n");


#! /bin/bash

for (( i=2008; i<=2121; ++i ))
do
 date -d "$i-12-25"
done  |grep Sun

exit 0


#import std
#import nat
#import stt

christmases = time_to_string* string_to_time*TS 'Dec 25 0:0:0 '-*@hS %nP* nrange/2008 2121

#show+

sunday_years = ~&zS sep` * =]'Sun'*~ christmases


Option Explicit

Sub MainDayOfTheWeek()
    Debug.Print "Xmas will be a Sunday in : " & XmasSunday(2008, 2121)
End Sub

Private Function XmasSunday(firstYear As Integer, lastYear As Integer) As String
Dim i As Integer, temp$
    For i = firstYear To lastYear
        If Weekday(CDate("25/12/" & i)) = vbSunday Then temp = temp & ", " & i
    Next
    XmasSunday = Mid(temp, 2)
End Function


For year = 2008 To 2121
    If Weekday(DateSerial(year, 12, 25)) = 1 Then
        WScript.Echo year
    End If
Next


local i as dword

for i := 2008 upto 2121
	if DOW(ConDate(i, 12, 25)) = 1
		? AsString(i)
	endif
next i


import time

fn main() {
    for year := 2008; year <= 2121; year++ {
        date := time.parse('${year}-12-25 00:00:00') or { continue }
        if date.long_weekday_str() == 'Sunday' {
            println('December 25 ${year} is a ${date.long_weekday_str()}')
        }
    }
}


import "/date" for Date

System.print("Years between 2008 and 2121 when 25th December falls on Sunday:")
for (year in 2008..2121) {
    if (Date.new(year, 12, 25).dayOfWeek == 7) System.print(year)
}


include c:\cxpl\codes;                  \intrinsic 'code' declarations

func    WeekDay(Year, Month, Day);      \Return day of week (0=Sat 1=Sun..6=Fri)
int     Year, Month, Day;
[if Month<=2 then [Month:= Month+12;  Year:= Year-1];
return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7);
];      \WeekDay

int     Year;
[for Year:= 2008 to 2121 do
    if WeekDay(Year, 12, 25) = 1 then   \25th of December is a Sunday
        [IntOut(0, Year);  CrLf(0)];
]


sub wd(m, d, y)
  If m < 3 Then        // If m = 1 Or m = 2 Then
    m = m + 12
    y = y - 1
  End If
  Return mod((y + int(y / 4) - int(y / 100) + int(y / 400) + d + int((153 * m + 8) / 5)), 7)
End sub

// ------=< MAIN >=------

For yr = 2008 To 2121
  If wd(12, 25, yr) = 0 Then
    Print "Dec 25 ", yr
  EndIf
Next


var [const] D=Time.Date;
foreach y in ([2008..2121]){
   if (D.Sunday==D.weekDay(y,12,25)) println(y)
}


module Main;
(*Access to Mono System package *)
import System;

var
	now: System.DateTime;
begin
	now := System.DateTime.Now;
	System.Console.Write(now.ToString("yyyy-MM-dd :"));
	System.Console.WriteLine(now.DayOfWeek);
end Main.


10 CLS
20 FOR y=2008 TO 2121
30 LET year=y: LET m=12: LET d=25: GO SUB 1000
40 IF wd=0 THEN PRINT d;" ";m;" ";y
50 NEXT y
60 STOP
1000 REM week day
1010 IF m=1 OR m=2 THEN LET m=m+12: LET year=year-1
1020 LET wd=FN m(year+INT (year/4)-INT (year/100)+INT (year/400)+d+INT ((153*m+8)/5),7)
1030 RETURN
1100 DEF FN m(a,b)=a-INT (a/b)*b


        JSR SYS_READ_CALENDAR ;outputs calendar date to BIOS RAM

	MOVE.B #'2',D0                  ;a character in single or double quotes refers to its ascii equivalent.
	JSR PrintChar
	MOVE.B #'0',D0
	JSR PrintChar

	LEA BIOS_YEAR,A1
	MOVE.B (A1)+,D0			;stores last 2 digits of year into D0, in binary coded decimal
	JSR UnpackNibbles8		;separate the digits into high and low nibbles: D0 = 00020001
	ADD.L #$00300030,D0		;convert both numerals to their ascii equivalents.
	SWAP D0				;print the "2" first
	JSR PrintChar
	SWAP D0				;then the "1"
	JSR PrintChar

	MOVE.B #'-',D0
	JSR PrintChar

	MOVE.B (A1)+,D0			;get the month
	JSR UnpackNibbles8
	ADD.L #$00300030,D0
	SWAP D0
	JSR PrintChar
	SWAP D0
	JSR PrintChar

	MOVE.B #'-',D0
	JSR PrintChar

	MOVE.B (A1)+,D0			;get the day
	JSR UnpackNibbles8
	ADD.L #$00300030,D0
	SWAP D0
	JSR PrintChar
	SWAP D0
	JSR PrintChar

	;now the date is printed.

	;Now do it again only written out:
	jsr NewLine

	CLR.L D0				;reset D0
	MOVE.B (A1),D0			;A1 happens to point to the weekday
	LSL.W #2,D0				;we are indexing into a table of longs
	LEA Days_Lookup,A2
	LEA (A2,D0),A2
	MOVEA.L (A2),A3			;dereference the pointer into A3, which the PrintString routine takes as an argument.

	JSR PrintString

	CLR.L D0
	LEA BIOS_MONTH,A1		;GET THE MONTH
	MOVE.B (A1)+,D0
	LSL.W #2,D0
	LEA Months_Lookup,A2
	LEA (A2,D0),A2
	MOVEA.L (A2),A3

	JSR PrintString

	MOVE.B (A1),D0			;GET THE DAY
	JSR UnpackNibbles8
	ADD.L #$00300030,D0
	SWAP D0
	JSR PrintChar
	SWAP D0
	JSR PrintChar

	MOVE.B #',',D0
	JSR PrintChar
	MOVE.B #' ',D0
	JSR PrintChar

	MOVE.B #'2',D0
	JSR PrintChar
	MOVE.B #'0',D0
	JSR PrintChar

	LEA BIOS_YEAR,A1
	MOVE.B (A1)+,D0			;stores last 2 digits of year into D0, in binary coded decimal
	JSR UnpackNibbles8		;separate the digits into high and low nibbles: D0 = 00020001
	ADD.L #$00300030,D0		;convert both numerals to their ascii equivalents.
	SWAP D0					;print the "2" first
	JSR PrintChar
	SWAP D0					;then the "1"
	JSR PrintChar

forever:
	bra forever                              ;trap the program counter

UnpackNibbles8:
; INPUT: D0 = THE VALUE YOU WISH TO UNPACK.
; HIGH NIBBLE IN HIGH WORD OF D0, LOW NIBBLE IN LOW WORD. SWAP D0 TO GET THE OTHER HALF.
	pushWord D1
		CLR.W D1
		MOVE.B D0,D1
		CLR.L D0
		MOVE.B D1,D0	 ;now D0 = D1 = $000000II, where I = input

		AND.B #$F0,D0	 ;chop off bottom nibble
		LSR.B #4,D0		 ;downshift top nibble into bottom nibble of the word
		SWAP D0			 ;store in high word
		AND.B #$0F,D1	 ;chop off bottom nibble
		MOVE.B D1,D0	 ;store in low word
	popWord D1
	rts


d:new
"%Y-%M-%D" over d:format . cr
"%W, %N %D, %Y" over d:format . cr
bye


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program dateFormat64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ GETTIME,   169     // call system linux gettimeofday

/*******************************************/
/* Structures                               */
/********************************************/
/* example structure  time  */
    .struct  0
timeval_sec:                     //
    .struct  timeval_sec + 8
timeval_usec:                     //
    .struct  timeval_usec + 8
timeval_end:
    .struct  0
timezone_min:                     //
    .struct  timezone_min + 8
timezone_dsttime:                 //
    .struct  timezone_dsttime + 8
timezone_end:

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessError:       .asciz "Error detected !!!!. \n"
szMessResult:      .asciz "Date : @/@/@ \n"        // message result
szMessResult1:     .asciz "Date day : @ @ @ @ \n"  // message result
szJan:             .asciz "Janvier"
szFev:             .asciz "Fèvrier"
szMars:            .asciz "Mars"
szAvril:           .asciz "Avril"
szMai:             .asciz "Mai"
szJuin:            .asciz "Juin"
szJuil:            .asciz "Juillet"
szAout:            .asciz "Aout"
szSept:            .asciz "Septembre"
szOct:             .asciz "Octobre"
szNov:             .asciz "Novembre"
szDec:             .asciz "Décembre"
szLundi:           .asciz "Lundi"
szMardi:           .asciz "Mardi"
szMercredi:        .asciz "Mercredi"
szJeudi:           .asciz "Jeudi"
szVendredi:        .asciz "Vendredi"
szSamedi:          .asciz "Samedi"
szDimanche:        .asciz "Dimanche"
szCarriageReturn:  .asciz "\n"
.align 4
tbDayMonthYear:    .quad  0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335
                   .quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
                   .quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
                   .quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
tbMonthName:       .quad szJan
                   .quad szFev
                   .quad szMars
                   .quad szAvril
                   .quad szMai
                   .quad szJuin
                   .quad szJuil
                   .quad szAout
                   .quad szSept
                   .quad szOct
                   .quad szNov
                   .quad szDec
tbDayName:         .quad szLundi
                   .quad szMardi
                   .quad szMercredi
                   .quad szJeudi
                   .quad szVendredi
                   .quad szSamedi
                   .quad szDimanche

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
stTVal:                .skip timeval_end
stTZone:               .skip timezone_end
sZoneConv:             .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                              // entry of program
    ldr x0,qAdrstTVal
    ldr x1,qAdrstTZone
    mov x8,#GETTIME
    svc 0
    cmp x0,#-1                     // error ?
    beq 99f
    ldr x1,qAdrstTVal
    ldr x0,[x1,#timeval_sec]       // timestamp in second
    bl dateFormatNum
    ldr x0,[x1,#timeval_sec]       // timestamp in second
    bl dateFormatAlpha
    ldr x0,qTStest1
    bl dateFormatNum
    ldr x0,qTStest1
    bl dateFormatAlpha
    ldr x0,qTStest2
    bl dateFormatNum
    ldr x0,qTStest2
    bl dateFormatAlpha
    ldr x0,qTStest3
    bl dateFormatNum
    ldr x0,qTStest3
    bl dateFormatAlpha
    b 100f
99:
    ldr x0,qAdrszMessError
    bl affichageMess
100:                               // standard end of the program
    mov x0,#0                      // return code
    mov x8,#EXIT                   // request to exit program
    svc 0                          // perform the system call

qAdrszMessError:          .quad szMessError
qAdrstTVal:               .quad stTVal
qAdrstTZone:              .quad stTZone
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsZoneConv:            .quad sZoneConv
qTStest1:                 .quad 1609508339    // 01/01/2021
qTStest2:                 .quad 1657805939    // 14/07/2022
qTStest3:                 .quad 1767221999    // 31/12/2025
/******************************************************************/
/*     date format numeric                                        */
/******************************************************************/
/* x0 contains the  timestamp in seconds */
dateFormatNum:
    stp x1,lr,[sp,-16]!            // save  registers
    ldr x2,qSecJan2020
    sub x0,x0,x2                   // total secondes to 01/01/2020
    mov x1,60
    udiv x0,x0,x1                  // divide secondes
    udiv x0,x0,x1                  // divide minutes
    mov x1,#24
    udiv x0,x0,x1                  // divide hours
    mov x11,x0
    mov x1,#(365 * 4 + 1)
    udiv x9,x0,x1
    lsl x9,x9,#2                   // multiply by 4 = year1
    mov x1,#(365 * 4 + 1)
    udiv x2,x11,x1
    msub x10,x2,x1,x11

    ldr x1,qAdrtbDayMonthYear
    mov x2,#3
    mov x3,#12
1:
    mul x11,x3,x2
    ldr x4,[x1,x11,lsl 3]         // load days by year
    cmp x10,x4
    bge 2f
    sub x2,x2,1
    cbnz x2,1b
2:                                // x2 = year2
    mov x5,11
    mul x11,x3,x2
    lsl x11,x11,3
    add x11,x11,x1                // table address
3:
    ldr x4,[x11,x5,lsl 3]         // load days by month
    cmp x10,x4
    bge 4f
    subs x5,x5,1
    bne 3b
4:                                 // x5 = month - 1
    mul x11,x3,x2
    add x11,x11,x5
    ldr x1,qAdrtbDayMonthYear
    ldr x3,[x1,x11,lsl 3]
    sub x0,x10,x3
    add x0,x0,1                    // final compute day
    ldr x1,qAdrsZoneConv
    bl conversion10                // this function do not zero final
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at first // character
    mov x3,x0
    add x0,x5,1                    // final compute month
    cmp x0,12
    sub x1,x0,12
    csel x0,x1,x0,gt
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x3
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next // character
    mov x3,x0
    ldr x11,qYearStart
    add x0,x9,x11
    add x0,x0,x2                   // final compute year = 2020 + yeax1 + yeax2
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x3
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next // character
    bl affichageMess
100:
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrszMessResult:         .quad szMessResult
/******************************************************************/
/*     date format alphanumeric                                   */
/******************************************************************/
/* x0 contains the  timestamp in seconds */
dateFormatAlpha:
    stp x1,lr,[sp,-16]!            // save  registers
    ldr x2,qSecJan2020
    sub x0,x0,x2                   // total secondes to 01/01/2020
    mov x6,x0
    mov x1,60
    udiv x0,x0,x1
    udiv x0,x0,x1
    mov x1,24
    udiv x0,x0,x1
    mov x7,x0
    mov x1,(365 * 4 + 1)
    udiv x9,x0,x1
    lsl x9,x9,#2                   // multiply by 4 = year1
    mov x1,(365 * 4 + 1)
    udiv x0,x7,x1
    msub x10,x0,x1,x7
    ldr x1,qAdrtbDayMonthYear
    mov x8,3
    mov x3,12
1:
    mul x7,x3,x8
    ldr x4,[x1,x7,lsl 3]          // load days by year
    cmp x10,x4
    bge 2f
    sub x8,x8,1
    cmp x8,0
    bne 1b
2:                                 // x8 = yeax2
    mov x5,#11
    mul x7,x3,x8
    lsl x7,x7,3
    add x7,x7,x1
3:
    ldr x4,[x7,x5,lsl 3]          // load days by month
    cmp x10,x4
    bge 4f
    subs x5,x5,1
    bne 3b
4:                                 // x5 = month - 1

    mov x0,x6                      // number secondes depuis 01/01/2020
    ldr x1,qNbSecByDay
    udiv x0,x6,x1
    mov x1,7
    udiv x2,x0,x1
    msub x3,x2,x1,x0
    add x2,x3,2
    cmp x2,7
    sub x3,x2,7
    csel x2,x3,x2,ge
    ldr x1,qAdrtbDayName
    ldr x1,[x1,x2,lsl 3]
    ldr x0,qAdrszMessResult1

    bl strInsertAtCharInc          // insert result at next // character
    mov x3,x0
    mov x7,12
    mul x11,x7,x8
    add x11,x11,x5
    ldr x1,qAdrtbDayMonthYear
    ldr x7,[x1,x11,lsl 3]
    sub x0,x10,x7
    add x0,x0,1                   // final compute day
    ldr x1,qAdrsZoneConv
    bl conversion10                // this function do not zero final
    mov x0,x3
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at first // character
    mov x3,x0
    ldr x1,qAdrtbMonthName
    cmp x5,12
    sub x2,x5,12
    csel x5,x2,x5,ge
    ldr x1,[x1,x5,lsl 3]          // month name
    mov x0,x3
    bl strInsertAtCharInc          // insert result at first // character
    mov x3,x0
    ldr x0,qYearStart
    add x0,x0,x8
    add x0,x0,x9                      // final compute year = 2020 + yeax1 + yeax2

    ldr x1,qAdrsZoneConv
    bl conversion10                // this function do not zero final
    mov x0,x3
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at first // character
    bl affichageMess
100:
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrszMessResult1:         .quad szMessResult1
qSecJan2020:              .quad 1577836800
qAdrtbDayMonthYear:       .quad tbDayMonthYear
qYearStart:               .quad 2020
qAdrtbMonthName:          .quad tbMonthName
qAdrtbDayName:            .quad tbDayName
qNbSecByDay:              .quad 3600 * 24
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


report zdate.
data: lv_month type string,
      lv_weekday type string,
      lv_date type string,
      lv_day type c.

call function 'DATE_COMPUTE_DAY'
  exporting date = sy-datum
  importing day  = lv_day.
select single ltx from t247 into lv_month
  where spras = sy-langu and
  mnr = sy-datum+4(2).

select single langt from t246 into lv_weekday
  where sprsl = sy-langu and
  wotnr = lv_day.

concatenate lv_weekday ', ' lv_month ' ' sy-datum+6(2) ', ' sy-datum(4) into lv_date respecting blanks.
write lv_date.
concatenate sy-datum(4) '-' sy-datum+4(2) '-' sy-datum+6(2) into lv_date.
write / lv_date.


DEFINE PTR="CARD"

TYPE Date=[
  INT year
  BYTE month
  BYTE day]

PTR ARRAY DayOfWeeks(7)
PTR ARRAY Months(12)

PROC Init()
  DayOfWeeks(0)="Sunday"   DayOfWeeks(1)="Monday"
  DayOfWeeks(2)="Tuesday"  DayOfWeeks(3)="Wednesday"
  DayOfWeeks(4)="Thursday" DayOfWeeks(5)="Friday"
  DayOfWeeks(6)="Saturday"
  Months(0)="January"   Months(1)="February"
  Months(2)="March"     Months(3)="April"
  Months(4)="May"       Months(5)="June"
  Months(6)="July"      Months(7)="August"
  Months(8)="September" Months(9)="October"
  Months(10)="November" Months(11)="December"
RETURN

;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
BYTE FUNC DayOfWeek(Date POINTER d)	;1<=m<=12, y>1752
  BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
  BYTE res
  INT y

  y=d.year
  IF d.month<3 THEN
    y==-1
  FI
  res=(y+y/4-y/100+y/400+t(d.month-1)+d.day) MOD 7
RETURN (res)

PROC PrintB2(BYTE x)
  IF x<10 THEN
    Put('0)
  FI
  PrintB(x)
RETURN

PROC PrintDateShort(Date POINTER d)
  PrintI(d.year) Put('-)
  PrintB2(d.month) Put('-)
  PrintB2(d.day)
RETURN

PROC PrintDateLong(Date POINTER d)
  BYTE wd

  wd=DayOfWeek(d)
  Print(DayOfWeeks(wd)) Print(", ")
  Print(Months(d.month-1)) Put(' )
  PrintB(d.day) Print(", ")
  PrintI(d.year)
RETURN

PROC Main()
  Date d

  Init()

  ;There is no function to get the current date
  ;on Atari 8-bit computer
  d.year=2021 d.month=9 d.day=1

  PrintDateShort(d) PutE()
  PrintDateLong(d) PutE()
RETURN


with Ada.Calendar;             use Ada.Calendar;
with Ada.Calendar.Formatting;  use Ada.Calendar.Formatting;
with Ada.Text_IO;              use Ada.Text_IO;

procedure Date_Format is
   function Image (Month : Month_Number) return String is
   begin
      case Month is
         when 1  => return "January";
         when 2  => return "February";
         when 3  => return "March";
         when 4  => return "April";
         when 5  => return "May";
         when 6  => return "June";
         when 7  => return "July";
         when 8  => return "August";
         when 9  => return "September";
         when 10 => return "October";
         when 11 => return "November";
         when 12 => return "December";
      end case;
   end Image;
   function Image (Day : Day_Name) return String is
   begin
      case Day is
         when Monday    => return "Monday";
         when Tuesday   => return "Tuesday";
         when Wednesday => return "Wednesday";
         when Thursday  => return "Thursday";
         when Friday    => return "Friday";
         when Saturday  => return "Saturday";
         when Sunday    => return "Sunday";
      end case;
   end Image;
   Today : Time := Clock;
begin
   Put_Line (Image (Today) (1..10));
   Put_Line
   (  Image (Day_Of_Week (Today)) & ", "
   &  Image (Ada.Calendar.Month (Today))
   &  Day_Number'Image (Ada.Calendar.Day (Today)) & ","
   &  Year_Number'Image (Ada.Calendar.Year (Today))
   );
end Date_Format;


# define the layout of the date/time as provided by the call to local time #
STRUCT ( INT sec, min, hour, mday, mon, year, wday, yday, isdst) tm = (6,5,4,3,2,1,7,~,8);

FORMAT # some useful format declarations #
  ymd repr = $4d,"-"2d,"-"2d$,
  month repr =    $c("January","February","March","April","May","June","July",
                     "August","September","October","November","December")$,
  week day repr = $c("Sunday","Monday","Tuesday","Wednesday",
                     "Thursday","Friday","Saturday")$,
  dmdy repr =     $f(week day repr)", "f(month repr)" "g(-0)", "g(-4)$,

  mon  = $c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")$,
  wday = $c("Sun","Mon","Tue","Wed","Thu","Fri","Sat")$,
  tz   = $c("MSK","MSD")$,
  unix time repr = $f(wday)" "f(mon)z-d," "dd,":"dd,":"dd," "f(tz)" "dddd$;

[]INT now = local time;

printf((ymd repr,       now[year OF tm:mday OF tm], $l$));
printf((dmdy repr,      now[wday OF tm], now[mon OF tm], now[mday OF tm], now[year OF tm], $l$));

printf((unix time repr, now[wday OF tm], now[mon OF tm], now[mday OF tm],
                        now[hour OF tm:sec OF tm], now[isdst OF tm]+1, now[year OF tm], $l$))


Datetime dtNow = datetime.now();
String strDt1 = dtNow.format('yyyy-MM-dd');
String strDt2 = dtNow.format('EEEE, MMMM dd, yyyy');
system.debug(strDt1); // "2007-11-10"
system.debug(strDt2); //"Sunday, November 10, 2007"


set {year:y, month:m, day:d, weekday:w} to (current date)

tell (y * 10000 + m * 100 + d) as text to set shortFormat to text 1 thru 4 & "-" & text 5 thru 6 & "-" & text 7 thru 8
set longFormat to (w as text) & (", " & m) & (space & d) & (", " & y)

return (shortFormat & linefeed & longFormat)


/* ARM assembly Raspberry PI  */
/*  program dateFormat.s   */

/* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */

/*******************************************/
/* Constantes                              */
/*******************************************/
.equ STDOUT, 1           @ Linux output console
.equ EXIT,   1           @ Linux syscall
.equ WRITE,  4           @ Linux syscall
.equ BRK,    0x2d        @ Linux syscall
.equ CHARPOS,     '@'

.equ GETTIME,   0x4e     @ call system linux gettimeofday

/*******************************************/
/* Structures                               */
/********************************************/
/* example structure  time  */
    .struct  0
timeval_sec:                     @
    .struct  timeval_sec + 4
timeval_usec:                     @
    .struct  timeval_usec + 4
timeval_end:
    .struct  0
timezone_min:                     @
    .struct  timezone_min + 4
timezone_dsttime:                 @
    .struct  timezone_dsttime + 4
timezone_end:

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessError:       .asciz "Error detected !!!!. \n"
szMessResult:      .asciz "Date : @/@/@ \n"  @ message result
szMessResult1:     .asciz "Date day : @ @ @ @ \n"  @ message result
szJan:             .asciz "Janvier"
szFev:             .asciz "Février"
szMars:            .asciz "Mars"
szAvril:            .asciz "Avril"
szMai:             .asciz "Mai"
szJuin:            .asciz "Juin"
szJuil:            .asciz "Juillet"
szAout:            .asciz "Aout"
szSept:            .asciz "Septembre"
szOct:             .asciz "Octobre"
szNov:             .asciz "Novembre"
szDec:             .asciz "Décembre"
szLundi:           .asciz "Lundi"
szMardi:           .asciz "Mardi"
szMercredi:        .asciz "Mercredi"
szJeudi:           .asciz "Jeudi"
szVendredi:        .asciz "Vendredi"
szSamedi:          .asciz "Samedi"
szDimanche:        .asciz "Dimanche"
szCarriageReturn:  .asciz "\n"
.align 4
tbDayMonthYear:    .int  0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335
                   .int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
                   .int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
                   .int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
tbMonthName:       .int szJan
                   .int szFev
                   .int szMars
                   .int szAvril
                   .int szMai
                   .int szJuin
                   .int szJuil
                   .int szAout
                   .int szSept
                   .int szOct
                   .int szNov
                   .int szDec
tbDayName:         .int szLundi
                   .int szMardi
                   .int szMercredi
                   .int szJeudi
                   .int szVendredi
                   .int szSamedi
                   .int szDimanche

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
stTVal:                .skip timeval_end
stTZone:               .skip timezone_end
sZoneConv:             .skip 100
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                              @ entry of program
    ldr r0,iAdrstTVal
    ldr r1,iAdrstTZone
    mov r7,#GETTIME
    svc 0
    cmp r0,#-1                     @ error ?
    beq 99f
    ldr r1,iAdrstTVal
    ldr r0,[r1,#timeval_sec]       @ timestemp in second
    bl dateFormatNum
    ldr r0,[r1,#timeval_sec]       @ timestemp in second
    bl dateFormatAlpha
    ldr r0,iTStest1
    bl dateFormatNum
    ldr r0,iTStest1
    bl dateFormatAlpha
    ldr r0,iTStest2
    bl dateFormatNum
    ldr r0,iTStest2
    bl dateFormatAlpha
    ldr r0,iTStest3
    bl dateFormatNum
    ldr r0,iTStest3
    bl dateFormatAlpha
    b 100f
99:
    ldr r0,iAdrszMessError
    bl affichageMess
100:                               @ standard end of the program
    mov r0,#0                      @ return code
    mov r7,#EXIT                   @ request to exit program
    svc 0                          @ perform the system call

iAdrszMessError:          .int szMessError
iAdrstTVal:               .int stTVal
iAdrstTZone:              .int stTZone
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsZoneConv:            .int sZoneConv
iTStest1:                 .int 1609508339    @ 01/01/2021
iTStest2:                 .int 1657805939    @ 14/07/2022
iTStest3:                 .int 1767221999    @ 31/12/2025
/******************************************************************/
/*     date format numeric                                        */
/******************************************************************/
/* r0 contains the  timestamp in seconds */
dateFormatNum:
    push {r1-r11,lr}                             @ save  registers
    ldr r2,iSecJan2020
    sub r0,r0,r2                   @ total secondes to 01/01/2020
    mov r1,#60
    bl division
    mov r0,r2
    mov r6,r3                      @ compute secondes
    mov r1,#60
    bl division
    mov r7,r3                      @ compute minutes
    mov r0,r2
    mov r1,#24
    bl division
    mov r8,r3                      @ compute hours
    mov r0,r2
    mov r11,r0
    mov r1,#(365 * 4 + 1)
    bl division
    lsl r9,r2,#2                   @ multiply by 4 = year1
    mov r1,#(365 * 4 + 1)
    mov r0,r11
    bl division
    mov r10,r3

    ldr r1,iAdrtbDayMonthYear
    mov r2,#3
    mov r3,#12
1:
    mul r11,r3,r2
    ldr r4,[r1,r11,lsl #2]         @ load days by year
    cmp r10,r4
    bge 2f
    sub r2,r2,#1
    cmp r2,#0
    bne 1b
2:                                 @ r2 = year2
    mov r5,#11
    mul r11,r3,r2
    lsl r11,#2
    add r11,r1                     @ table address
3:
    ldr r4,[r11,r5,lsl #2]         @ load days by month
    cmp r10,r4
    bge 4f
    subs r5,r5,#1
    bne 3b
4:                                 @ r5 = month - 1
    mul r11,r3,r2
    add r11,r5
    ldr r1,iAdrtbDayMonthYear
    ldr r3,[r1,r11,lsl #2]
    sub r0,r10,r3
    add r0,r0,#1                   @ final compute day
    ldr r1,iAdrsZoneConv
    bl conversion10                @ this function do not zero final
    mov r11,#0                     @ store zero final
    strb r11,[r1,r0]
    ldr r0,iAdrszMessResult
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at first @ character
    mov r3,r0
    add r0,r5,#1                   @ final compute month
    cmp r0,#12
    subgt r0,#12
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r11,#0                      @ store zero final
    strb r11,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    ldr r11,iYearStart
    add r0,r9,r11
    add r0,r0,r2                   @ final compute year = 2020 + year1 + year2
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r11,#0                     @ store zero final
    strb r11,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    bl affichageMess
100:
    pop {r1-r11,lr}                @ restaur registers
    bx lr                          @ return
iAdrszMessResult:         .int szMessResult
/******************************************************************/
/*     date format alphanumeric                                   */
/******************************************************************/
/* r0 contains the  timestamp in seconds */
dateFormatAlpha:
    push {r1-r10,lr}               @ save  registers
    ldr r2,iSecJan2020
    sub r0,r0,r2                   @ total secondes to 01/01/2020
    mov r6,r0
    mov r1,#60
    bl division
    mov r0,r2
    mov r1,#60
    bl division
    mov r0,r2
    mov r1,#24
    bl division
    mov r0,r2
    mov r8,r0
    mov r1,#(365 * 4 + 1)
    bl division
    lsl r9,r2,#2                   @ multiply by 4 = year1
    mov r1,#(365 * 4 + 1)
    mov r0,r8
    bl division
    mov r10,r3                     @ reste

    ldr r1,iAdrtbDayMonthYear
    mov r7,#3
    mov r3,#12
1:
    mul r8,r3,r7
    ldr r4,[r1,r8,lsl #2]          @ load days by year
    cmp r10,r4
    bge 2f
    sub r7,r7,#1
    cmp r7,#0
    bne 1b
2:                                 @ r7 = year2
    mov r5,#11
    mul r8,r3,r7
    lsl r8,#2
    add r8,r1
3:
    ldr r4,[r8,r5,lsl #2]          @ load days by month
    cmp r10,r4
    bge 4f
    subs r5,r5,#1
    bne 3b
4:                                 @ r5 = month - 1

    mov r0,r6                      @ number secondes depuis 01/01/2020
    ldr r1,iNbSecByDay
    bl division
    mov r0,r2
    mov r1,#7
    bl division
    add r2,r3,#2
    cmp r2,#7
    subge r2,#7
    ldr r1,iAdrtbDayName
    ldr r1,[r1,r2,lsl #2]
    ldr r0,iAdrszMessResult1
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r8,#12
    mul r11,r8,r7
    add r11,r5
    ldr r1,iAdrtbDayMonthYear
    ldr r8,[r1,r11,lsl #2]
    sub r0,r10,r8
    add r0,r0,#1                   @ final compute day
    ldr r1,iAdrsZoneConv
    bl conversion10                @ this function do not zero final
    mov r8,#0                      @ store zero final
    strb r8,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at first @ character
    mov r3,r0
    ldr r1,iAdrtbMonthName
    cmp r5,#12
    subge r5,#12
    ldr r1,[r1,r5,lsl #2]          @ month name
    mov r0,r3
    bl strInsertAtCharInc          @ insert result at first @ character
    mov r3,r0
    ldr r0,iYearStart
    add r0,r7
    add r0,r9                      @ final compute year = 2020 + year1 + year2

    ldr r1,iAdrsZoneConv
    bl conversion10                @ this function do not zero final
    mov r8,#0                      @ store zero final
    strb r8,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at first @ character
    bl affichageMess
100:
    pop {r1-r10,lr}                @ restaur registers
    bx lr                          @ return
iAdrszMessResult1:         .int szMessResult1
iSecJan2020:              .int 1577836800
iAdrtbDayMonthYear:       .int tbDayMonthYear
iYearStart:               .int 2020
iAdrtbMonthName:          .int tbMonthName
iAdrtbDayName:            .int tbDayName
iNbSecByDay:              .int 3600 * 24
/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
.include "../affichage.inc"


	org	100h
	jmp	demo
	;;;	Given an 0-terminated ASCII string containing digits in [DE],
	;;;	see if it matches its check digit. Returns with zero flag set
	;;;	if the string matches.
damm:	mvi	c,0	; Interim digit in C, starts off at 0.
	ldax	d	; Get current byte from string
	inx	d 	; Advance the pointer
	ana	a	; Is the byte zero?
	jnz	$+5	; If not, go look up interim digit
	cmp	c	; But if so, see if the interim digit is also zero
	ret		; And return whether this was the case
	sui	'0'	; Subtract ASCII 0
	mov	b,a	; Keep digit to be processed in B
	mov	a,c	; Calculate C*10 (interim digit row index)
	add	a	; * 2
	add	a	; * 4
	add	c	; * 5
	add	a	; * 10
	add	b	; Add column index
	lxi	h,dammit
	add	l	; Table lookup (assuming H doesn't change, i.e. it
	mov	l,a	; doesn't cross a page boundary).
	mov	c,m	; Get new interim digit from table
	jmp	damm+2	; And check next character
	;;;	Table of interim digits
	;;;	NOTE: must not cross page boundary
dammit:	db	0,3,1,7,5,9,8,6,4,2
	db	7,0,9,2,1,5,4,8,6,3
	db	4,2,0,6,8,7,1,3,5,9
	db	1,7,5,0,9,8,3,4,2,6
	db	6,1,2,3,0,4,5,9,7,8
	db	3,6,7,4,2,0,9,5,8,1
	db	5,8,6,9,7,2,0,1,3,4
	db	8,9,4,5,3,6,2,0,1,7
	db	9,4,3,8,6,1,7,2,0,5
	db	2,5,8,1,4,3,6,7,9,0
	;;;	Demo code: see if the argument on the CP/M command line
	;;;	matches its input.
demo:	lxi	h,80h	; Zero-terminate input
	mov	e,m
	mvi	d,0
	inx	d
	dad	d
	mov	m,d
	lxi	d,82h	; Command line argument, skipping first space
	call	damm	; See if it validates
	mvi	c,9
	lxi	d,ok	; Print OK...
	jz	5	; ...if the checksum matches,
	lxi	d,no	; Print NOT OK otherwise.
	jmp	5
no:	db	'NOT '
ok:	db	'OK$'


	cpu	8086
	bits	16
section	.text
	org	100h
	jmp	demo
	;;;	Given a 0-terminated ASCII string containing digits in
	;;;	[DS:SI], see if the check digit matches. Returns with zero flag
	;;;	set if it matches.
damm:	xor	cl,cl	; Interim digit starts out at 0
	mov	bx,.tab	; Index for table lookup
.dgt:	lodsb		; Get next string byte
	test	al,al	; If it is zero, we're done
	jz	.out
	sub	al,'0'	; Make ASCII digit
	mov	ah,cl	; Table lookup, AH = interim digit
	aad		; AL += AH * 10 (such handy instructions the 8086 has)
	cs 	xlatb	; AL = CS:table[AL]
	mov	cl,al	; CL = new interim digit
	jmp	.dgt	; Get next string
.out:	test	cl,cl	; Interim digit should be zero at the end
	ret
.tab:	db	0,3,1,7,5,9,8,6,4,2	; Table can be stored as part of the
	db	7,0,9,2,1,5,4,8,6,3	; code
	db	4,2,0,6,8,7,1,3,5,9
	db	1,7,5,0,9,8,3,4,2,6
	db	6,1,2,3,0,4,5,9,7,8
	db	3,6,7,4,2,0,9,5,8,1
	db	5,8,6,9,7,2,0,1,3,4
	db	8,9,4,5,3,6,2,0,1,7
	db	9,4,3,8,6,1,7,2,0,5
	db	2,5,8,1,4,3,6,7,9,0
	;;;	Demo: see if the argument on the MS-DOS command line is valid
demo:	xor	bh,bh	; Zero-terminate the input
	mov	bl,[80h]
	mov	[bx+81h],bh
	mov	si,82h	; Start of input skipping first space
	call	damm	; Is it valid?
	mov	dx,ok	; If so, print OK
	jz	.print
	mov	dx,no 	; Otherwise, print NOT OK
.print:	mov	ah,9
	int	21h
	ret
section	.data
no:	db	'NOT '
ok: 	db	'OK$'


currentTime: now

print to :string.format: "YYYY-MM-dd" currentTime
print to :string.format: "dddd, MMMM dd, YYYY" currentTime


FormatTime, Date1, , yyyy-MM-dd ; "2007-11-10"
FormatTime, Date2, , LongDate   ; "Sunday, November 10, 2007"
MsgBox %Date1% `n %Date2%


BYTE FUNC Damm(CHAR ARRAY a)
  BYTE ARRAY table=[
    0 3 1 7 5 9 8 6 4 2
    7 0 9 2 1 5 4 8 6 3
    4 2 0 6 8 7 1 3 5 9
    1 7 5 0 9 8 3 4 2 6
    6 1 2 3 0 4 5 9 7 8
    3 6 7 4 2 0 9 5 8 1
    5 8 6 9 7 2 0 1 3 4
    8 9 4 5 3 6 2 0 1 7
    9 4 3 8 6 1 7 2 0 5
    2 5 8 1 4 3 6 7 9 0]
  BYTE i,x,c

  x=0
  FOR i=1 TO a(0)
  DO
    c=a(i)
    IF c<'0 OR c>'9 THEN
      RETURN (0)
    FI
    c==-'0
    x=table(x*10+c)
  OD
  IF x=0 THEN
    RETURN (1)
  FI
RETURN (0)

PROC Test(CHAR ARRAY a)
  BYTE i

  Print(a) Print(" -> ")
  IF Damm(a)=1 THEN
    PrintE("valid")
  ELSE
    PrintE("invalid")
  FI
RETURN

PROC Main()
  Test("5724")
  Test("5727")
  Test("112946")
  Test("112949")
RETURN


BEGIN # show cyclops numbers - numbers with a 0 in the middle and no other 0 digits #
    INT max prime = 100 000;
    # sieve the primes to max prime #
    PR read "primes.incl.a68" PR
    []BOOL prime = PRIMESIEVE max prime;
    # returns TRUE if c is prime, FALSE otherwise #
    PROC have a prime = ( INT c )BOOL:
         IF   c < 2 THEN FALSE
         ELIF c < max prime
         THEN prime[ c ]
         ELSE # the cyclops number is too large for the sieve, use trial division #
            BOOL possibly prime := ODD c;
            FOR d FROM 3 BY 2 WHILE d * d <= c AND possibly prime DO possibly prime := c MOD d /= 0 OD;
            possibly prime
         FI # have a prime # ;
    # arrays of the cyclops numbers we must show #
    [ 1 : 50 ]INT first cyclops;                   INT cyclops count                   := 0;
    [ 1 : 50 ]INT first prime cyclops;             INT prime cyclops count             := 0;
    [ 1 : 50 ]INT first palindromic prime cyclops; INT palindromic prime cyclops count := 0;
    [ 1 : 50 ]INT first blind prime cyclops;       INT blind prime cyclops count       := 0;
    # notes c is a cyclops number, palindromic indicates whether it is palindromic or not #
    #       bc should be c c with the middle 0 removed #
    # if c is one of the first 50 of various classifications, #
    #    it is stored in the appropriate array #
    PROC have cyclops = ( INT c, BOOL palindromic, INT bc )VOID:
         BEGIN
            cyclops count +:= 1;
            IF cyclops count <= UPB first cyclops THEN first cyclops[ cyclops count ] := c FI;
            IF   prime cyclops count             < UPB first prime cyclops
            OR ( palindromic prime cyclops count < UPB first palindromic prime cyclops AND palindromic )
            OR   blind prime cyclops count       < UPB first blind prime cyclops
            THEN
                IF have a prime( c ) THEN
                    # have a prime cyclops #
                    IF prime cyclops count < UPB first prime cyclops THEN
                       first prime cyclops[ prime cyclops count +:= 1 ] := c
                    FI;
                    IF palindromic prime cyclops count < UPB first palindromic prime cyclops AND palindromic THEN
                       first palindromic prime cyclops[ palindromic prime cyclops count +:= 1 ] := c
                    FI;
                    IF blind prime cyclops count < UPB first blind prime cyclops THEN
                        IF have a prime( bc ) THEN
                            first blind prime cyclops[ blind prime cyclops count +:= 1 ] := c
                        FI
                    FI
                FI
            FI
         END # have cyclops # ;
    # prints a cyclops sequence #
    PROC print cyclops = ( []INT seq, STRING legend, INT elements per line )VOID:
         BEGIN
            print( ( "The first ", whole( ( UPB seq - LWB seq ) + 1, 0 ), " ", legend, ":", newline, "   " ) );
            FOR i FROM LWB seq TO UPB seq DO
                print( ( " ", whole( seq[ i ], -7 ) ) );
                IF i MOD elements per line = 0 THEN print( ( newline, "   " ) ) FI
            OD;
            print( ( newline ) )
         END # print cyclops # ;
    # generate the cyclops numbers #
    # 0 is the first and only cyclops number with less than three digits #
    have cyclops( 0, TRUE, 0 );
    # generate the 3 digit cyclops numbers #
    FOR f TO 9 DO
        FOR b TO 9 DO
            have cyclops( ( f * 100 ) + b
                        , f = b
                        , ( f * 10 ) + b
                        )
        OD
    OD;
    # generate the 5 digit cyclops numbers #
    FOR d1 TO 9 DO
        FOR d2 TO 9 DO
            INT d1200  = ( ( d1 * 10 ) + d2 ) * 100;
            INT d12000 = d1200 * 10;
            FOR d4 TO 9 DO
                INT d40 = d4 * 10;
                FOR d5 TO 9 DO
                    INT d45 = d40 + d5;
                    have cyclops( d12000 + d45
                                , d1 = d5 AND d2 = d4
                                , d1200 + d45
                                )
                OD
            OD
        OD
    OD;
    # generate the 7 digit cyclops numbers #
    FOR d1 TO 9 DO
        FOR d2 TO 9 DO
            FOR d3 TO 9 DO
                INT d123000  = ( ( ( ( d1 * 10 ) + d2 ) * 10 ) + d3 ) * 1000;
                INT d1230000 = d123000 * 10;
                FOR d5 TO 9 DO
                    INT d500 = d5 * 100;
                    FOR d6 TO 9 DO
                        INT d560 = d500 + ( d6 * 10 );
                        FOR d7 TO 9 DO
                            INT d567 = d560 + d7;
                            have cyclops( d1230000 + d567
                                        , d1 = d7 AND d2 = d6 AND d3 = d5
                                        , d123000 + d567
                                        )
                        OD
                    OD
                OD
            OD
        OD
    OD;
    # show parts of the sequence #
    print cyclops( first cyclops,                                     "cyclops numbers", 10 );
    print cyclops( first prime cyclops,                         "prime cyclops numbers", 10 );
    print cyclops( first blind prime cyclops,             "blind prime cyclops numbers", 10 );
    print cyclops( first palindromic prime cyclops, "palindromic prime cyclops numbers", 10 )
END


#include <Date.au3>

$iYear = 2007
$iMonth = 11
$iDay = 10

ConsoleWrite(StringFormat('%4d-%02d-%02d', $iYear, $iMonth, $iDay) & @LF)

$iWeekDay = _DateToDayOfWeekISO($iYear, $iMonth, $iDay)
ConsoleWrite(StringFormat('%s, %s %02d, %4d', _GetLongDayLocale($iWeekDay), _GetLongMonthLocale($iMonth), $iDay, $iYear) & @LF)

Func _GetLongDayLocale($_iWeekDay)  ; 1..7 Monday=1
	Local $aDayName[8] = [0, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30]
	Return GetLocaleInfo($aDayName[$_iWeekDay])
EndFunc

Func _GetLongMonthLocale($_iMonth)  ; 1..12 January=1
	Local $aMonthName[13] = [0, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43]
	Return GetLocaleInfo($aMonthName[$_iMonth])
EndFunc

Func GetLocaleInfo($_LCType)
	Local $ret, $LCID, $sBuffer, $iLen
	$ret = DllCall('kernel32', 'long', 'GetSystemDefaultLCID')
	$LCID = $ret[0]
	$ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', 0)
	$iLen = $ret[0]
	$ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', $iLen)
	Return $ret[3]
EndFunc


BEGIN
    # returns TRUE if the check digit of s is correct according to the Damm algorithm, #
    # FALSE otherwise #
    PROC has valid damm check digit = ( STRING s )BOOL:
         BEGIN
            # operation table - as per wikipedia example #
            [,]INT operation table =
                ( [,]INT( ( 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 )
                        , ( 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 )
                        , ( 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 )
                        , ( 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 )
                        , ( 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 )
                        , ( 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 )
                        , ( 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 )
                        , ( 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 )
                        , ( 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 )
                        , ( 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 )
                        )
                ) [ AT 0, AT 0 ]
                ;
            INT interim digit := 0;
            FOR s pos FROM LWB s TO UPB s DO
                INT next digit = ABS s[ s pos ] - ABS "0";
                IF next digit < 0 OR next digit > 9 THEN
                    # invalid digit #
                    print( ( "Invalid damm digit: ", s[ s pos ], newline ) );
                    stop
                ELSE
                    # have a valid digit #
                    interim digit := operation table[ interim digit, next digit ]
                FI
            OD;
            interim digit = 0
         END # has valid damm check digit # ;

    # test the damm algorithm #
    PROC test damm algorithm = ( STRING s, BOOL expected )VOID:
         BEGIN
            BOOL valid = has valid damm check digit( s );
            print( ( "check digit of ", s, " is "
                   , IF valid THEN "valid" ELSE "invalid" FI
                   , IF valid = expected THEN "" ELSE " *** NOT AS EXPECTED" FI
                   , newline
                   )
                 )
         END # test damm algorithm # ;
    # test cases - as per other language samples #
    test damm algorithm( "5724",   TRUE  );
    test damm algorithm( "5727",   FALSE );
    test damm algorithm( "112946", TRUE  )
END


cyclops?: function [n][
    digs: digits n
    all? @[
        -> odd? size digs
        -> zero? digs\[(size digs)/2]
        -> 1 = size match to :string n "0"
    ]
]

blind: function [x][
    s: to :string x
    half: (size s)/2
    to :integer (slice s 0 dec half)++(slice s inc half dec size s)
]

findFirst50: function [what, start, predicate][
    print ["First 50" what++"cyclops numbers:"]
    first50: new start
    i: 100
    while [50 > size first50][
        if do predicate -> 'first50 ++ i
        i: i + 1
    ]

    loop split.every:10 first50 'row [
        print map to [:string] row 'item -> pad item 7
    ]
    print ""
]

findFirst50 "" [0] -> cyclops? i
findFirst50 "prime " [] -> and? [prime? i][cyclops? i]
findFirst50 "blind prime " [] -> all? @[
    -> prime? i
    -> cyclops? i
    -> prime? blind i
]

candidates: map 1..999 'x ->
    to :integer (to :string x)++"0"++(reverse to :string x)

print "First 50 palindromic prime cyclops numbers:"
loop split.every:10 first.n: 50 select candidates 'x -> and? [prime? x][cyclops? x] 'row [
    print map to [:string] row 'item -> pad item 7
]


# syntax: GAWK -f CYCLOPS_NUMBERS.AWK
BEGIN {
    n = 0
    limit = 50
    while (A134808_cnt < limit || A134809_cnt < limit || A329737_cnt < limit || A136098_cnt < limit) {
      leng = length(n)
      if (leng ~ /[13579]$/) {
        middle_col = int(leng/2)+1
        if (substr(n,middle_col,1) == 0 && gsub(/0/,"&",n) == 1) {
          A134808_arr[++A134808_cnt] = n
          if (is_prime(n)) {
            A134809_arr[++A134809_cnt] = n
            tmp = n
            sub(/0/,"",tmp)
            if (is_prime(tmp)) {
              A329737_arr[++A329737_cnt] = n
            }
            if (reverse(n) == n) {
              A136098_arr[++A136098_cnt] = n
            }
          }
        }
      }
      n++
    }
    printf("Range: 0-%d\n\n",n-1)
    show_array(A134808_arr,A134808_cnt,"A134808: Cyclops numbers")
    show_array(A134809_arr,A134809_cnt,"A134809: Cyclops primes")
    show_array(A329737_arr,A329737_cnt,"A329737: Cyclops primes that remain prime after being 'blinded'")
    show_array(A136098_arr,A136098_cnt,"A136098: Prime palindromic cyclops numbers")
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}
function reverse(str,  i,rts) {
    for (i=length(str); i>=1; i--) {
      rts = rts substr(str,i,1)
    }
    return(rts)
}
function show_array(arr,cnt,desc,  count,i) {
    printf("%s  Found %d numbers within range\n",desc,cnt)
    for (i=1; i<=limit; i++) {
      printf("%7d%1s",arr[i],++count%10?"":"\n")
    }
    printf("\n")
}


$ awk 'BEGIN{t=systime();print strftime("%Y-%m-%d",t)"\n"strftime("%A, %B %d, %Y",t)}'
2009-05-15
Friday, May 15, 2009


' Date format
n = NOW
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%ld-%02ld-%02ld\n"
PRINT WEEKDAY$(n), MONTH$(n), DAY(n), YEAR(n) FORMAT "%s, %s %02ld, %ld\n"


-- Return a check digit value for the given integer value or numeric string.
-- The result is 0 if the input's last digit is already a valid check digit for it.
on damm(n)
    set digits to {n mod 10}
    set n to n div 10
    repeat until (n is 0)
        set beginning of digits to n mod 10
        set n to n div 10
    end repeat

    script o
        property table : {0, 3, 1, 7, 5, 9, 8, 6, 4, 2, ¬
            7, 0, 9, 2, 1, 5, 4, 8, 6, 3, ¬
            4, 2, 0, 6, 8, 7, 1, 3, 5, 9, ¬
            1, 7, 5, 0, 9, 8, 3, 4, 2, 6, ¬
            6, 1, 2, 3, 0, 4, 5, 9, 7, 8, ¬
            3, 6, 7, 4, 2, 0, 9, 5, 8, 1, ¬
            5, 8, 6, 9, 7, 2, 0, 1, 3, 4, ¬
            8, 9, 4, 5, 3, 6, 2, 0, 1, 7, ¬
            9, 4, 3, 8, 6, 1, 7, 2, 0, 5, ¬
            2, 5, 8, 1, 4, 3, 6, 7, 9, 0}
    end script
    set interim to 0
    repeat with d in digits
        set interim to item (interim * 10 + d + 1) of o's table -- AppleScript indices are 1-based.
    end repeat

    return interim
end damm

-- Task code:
local testNumbers, possibilities, output, n
set testNumbers to {5724, 57240, 572400, 87591, 100}
-- Include a number with a check digit actually generated by the handler.
tell (random number 1000000) to set end of testNumbers to it * 10 + (my damm(it))
set possibilities to {" is invalid", " is valid"}
set output to {}
repeat with n in testNumbers
    set end of output to (n as text) & item (((damm(n) is 0) as integer) + 1) of possibilities
end repeat
return output


// Cyclop numbers. Nigel Galloway: June 25th., 2021
let rec fG n g=seq{yield! g|>Seq.collect(fun i->g|>Seq.map(fun g->n*i+g)); yield! fG(n*10)(fN g)}
let cyclops=seq{yield 0; yield! fG 100 [1..9]}
let primeCyclops,blindCyclops=cyclops|>Seq.filter isPrime,Seq.zip(fG 100 [1..9])(fG 10 [1..9])|>Seq.filter(fun(n,g)->isPrime n && isPrime g)|>Seq.map fst
let palindromicCyclops=let fN g=let rec fN g=[yield g%10; if g>9 then yield! fN(g/10)] in let n=fN g in n=List.rev n in primeCyclops|>Seq.filter fN


USING: accessors formatting grouping io kernel lists lists.lazy
math math.functions math.primes prettyprint sequences
tools.memory.private tools.time ;

! ==========={[ Cyclops data type and operations ]}=============

TUPLE: cyclops left right n max ;

: <cyclops> ( -- cyclops ) 1 1 1 9 cyclops boa ;

: >cyclops< ( cyclops -- right left n )
    [ right>> ] [ left>> ] [ n>> ] tri ;

M: cyclops >integer >cyclops< 1 + 10^ * + ;

: >blind ( cyclops -- n ) >cyclops< 10^ * + ;

: next-zeroless ( 9199 -- 9211 )
    dup 10 mod 9 < [ 10 /i next-zeroless 10 * ] unless 1 + ;

: right++ ( cyclops -- cyclops' )
    [ next-zeroless ] change-right ; inline

: left++ ( cyclops -- cyclops' )
    [ next-zeroless ] change-left [ 9 /i ] change-right ;

: n++ ( cyclops -- cyclops' )
    [ 1 + ] change-n [ 10 * 9 + ] change-max ;

: change-both ( cyclops quot -- cyclops' )
    [ change-left ] keep change-right ; inline

: expand ( cyclops -- cyclops' )
    dup max>> 9 /i 1 + '[ _ + ] change-both n++ ;

: carry ( cyclops -- cyclops' )
    dup [ left>> ] [ max>> ] bi < [ left++ ] [ expand ] if ;

: succ ( cyclops -- next-cyclops )
    dup [ right>> ] [ max>> ] bi < [ right++ ] [ carry ] if ;

! ============{[ List definitions & operations ]}===============

: lcyclops ( -- list ) <cyclops> [ succ ] lfrom-by ;

: lcyclops-int ( -- list ) lcyclops [ >integer ] lmap-lazy ;

: lprime-cyclops ( -- list )
    lcyclops-int [ prime? ] lfilter ;

: lblind-prime-cyclops ( -- list )
    lcyclops [ >integer prime? ] lfilter
    [ >blind prime? ] lfilter ;

: reverse-digits ( 123 -- 321 )
    0 swap [ 10 /mod rot 10 * + swap ] until-zero ;

: lpalindromic-prime-cyclops ( -- list )
    lcyclops [ [ left>> ] [ right>> ] bi reverse-digits = ]
    lfilter [ >integer prime? ] lfilter ;

: first>1e7 ( list -- elt index )
    0 lfrom lzip [ first >integer 10,000,000 > ] lfilter car
    first2 [ >integer ] dip [ commas ] [email protected] ;

! ====================={[ OUTPUT ]}=============================

: first50 ( list -- )
  50 swap ltake [ >integer ] lmap list>array 10 group
  simple-table. ;

:: show ( desc list -- )
    desc desc "First 50 %s numbers:\n" printf
    list [ first50 nl ] [
        first>1e7
        "First %s number > 10,000,000: %s - at (zero based) index: %s.\n\n\n" printf
    ] bi ;

"cyclops" lcyclops-int show
"prime cyclops" lprime-cyclops show
"blind prime cyclops" lblind-prime-cyclops show
"palindromic prime cyclops" lpalindromic-prime-cyclops show

! Extra stretch?
"One billionth cyclops number:" print
999,999,999 lcyclops lnth >integer commas print


package main

import (
    "fmt"
    "rcu"
    "strconv"
    "strings"
)

func findFirst(list []int) (int, int) {
    for i, n := range list {
        if n > 1e7 {
            return n, i
        }
    }
    return -1, -1
}

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}

func main() {
    ranges := [][2]int{
        {0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111},
    }
    var cyclops []int
    for _, r := range ranges {
        numDigits := len(fmt.Sprint(r[0]))
        center := numDigits / 2
        for i := r[0]; i <= r[1]; i++ {
            digits := rcu.Digits(i, 10)
            if digits[center] == 0 {
                count := 0
                for _, d := range digits {
                    if d == 0 {
                        count++
                    }
                }
                if count == 1 {
                    cyclops = append(cyclops, i)
                }
            }
        }
    }
    fmt.Println("The first 50 cyclops numbers are:")
    for i, n := range cyclops[0:50] {
        fmt.Printf("%6s ", rcu.Commatize(n))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    n, i := findFirst(cyclops)
    ns, is := rcu.Commatize(n), rcu.Commatize(i)
    fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)

    var primes []int
    for _, n := range cyclops {
        if rcu.IsPrime(n) {
            primes = append(primes, n)
        }
    }
    fmt.Println("\n\nThe first 50 prime cyclops numbers are:")
    for i, n := range primes[0:50] {
        fmt.Printf("%6s ", rcu.Commatize(n))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    n, i = findFirst(primes)
    ns, is = rcu.Commatize(n), rcu.Commatize(i)
    fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)

    var bpcyclops []int
    var ppcyclops []int
    for _, p := range primes {
        ps := fmt.Sprint(p)
        split := strings.Split(ps, "0")
        noMiddle, _ := strconv.Atoi(split[0] + split[1])
        if rcu.IsPrime(noMiddle) {
            bpcyclops = append(bpcyclops, p)
        }
        if ps == reverse(ps) {
            ppcyclops = append(ppcyclops, p)
        }
    }

    fmt.Println("\n\nThe first 50 blind prime cyclops numbers are:")
    for i, n := range bpcyclops[0:50] {
        fmt.Printf("%6s ", rcu.Commatize(n))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    n, i = findFirst(bpcyclops)
    ns, is = rcu.Commatize(n), rcu.Commatize(i)
    fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)

    fmt.Println("\n\nThe first 50 palindromic prime cyclops numbers are:\n")
    for i, n := range ppcyclops[0:50] {
        fmt.Printf("%9s ", rcu.Commatize(n))
        if (i+1)%8 == 0 {
            fmt.Println()
        }
    }
    n, i = findFirst(ppcyclops)
    ns, is = rcu.Commatize(n), rcu.Commatize(i)
    fmt.Printf("\n\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is)
}


#include "vbcompat.bi"

DIM today As Double = Now()

PRINT Format(today, "yyyy-mm-dd")
PRINT Format(today, "dddd, mmmm d, yyyy")


@echo off
setlocal enabledelayedexpansion

:: Define arrays of days/months we'll need
set daynames=Monday Tuesday Wednesday Thursday Friday Saturday Sunday
set monthnames=January February March April May June July August September October November December

:: Separate the output of the 'date /t' command (outputs in the format of "Sun 16/04/2017") into 4 variables
for /f "tokens=1,2,3,4 delims=/ " %%i in ('date /t') do (
  set dayname=%%i
  set day=%%j
  set month=%%k
  set year=%%l
)

:: Crosscheck the first 3 letters of every word in %daynames% to the 3 letter day name found previously
for %%i in (%daynames%) do (
  set tempdayname=%%i
  set comparedayname=!tempdayname:~0,3!
  if "%dayname%"=="!comparedayname!" set fulldayname=%%i
)

:: Variables starting with "0" during the 'set /a' command are treated as octal numbers. To avoid this, if the first character of %month% is "0", it is removed
if "%month:~0,1%"=="0" set monthtemp=%month:~1,1%
set monthcount=0

:: Iterates through %monthnames% and when it reaches the amount of iterations dictated by %month%, sets %monthname% as the current month being iterated through
for %%i in (%monthnames%) do (
  set /a monthcount+=1
  if %monthtemp%==!monthcount! set monthname=%%i
)

echo %year%-%month%-%day%
echo %fulldayname%, %monthname% %day%, %year%
pause>nul


.text
.global	_start
	@@@	Check if the zero-terminated ASCII string in [r0],
	@@@	which should contain a decimal number, has a
	@@@	matching check digit. Zero flag set if true,
	@@@	check digit returned in r0.
damm:	mov	r1,#0		@ R1 = interim digit
	ldr	r2,=3f		@ R2 = table base address
1:	ldrb	r3,[r0],#1	@ Load byte
	tst	r3,r3		@ Zero yet?
	beq	2f		@ If so, stop
	sub	r3,r3,#'0	@ Subtract ASCII 0
	lsl	r1,r1,#1	@ Table lookup
	add	r1,r1,r1,lsl#2	@ R3 = R1*10 + R3
	add	r3,r1,r3
	ldrb	r1,[r2,r3]	@ R1 = new interim digit
	b	1b		@ Next value
2:	movs	r0,r1		@ Set flag according to r0.
	bx	lr
3:	.byte	0,3,1,7,5,9,8,6,4,2	@ Since the table is constant,
	.byte	7,0,9,2,1,5,4,8,6,3	@ it can be stored as part of
	.byte	4,2,0,6,8,7,1,3,5,9	@ the subroutine.
	.byte	1,7,5,0,9,8,3,4,2,6	@ This way the OS will even mark
	.byte	6,1,2,3,0,4,5,9,7,8	@ it as read-only, so we can
	.byte	3,6,7,4,2,0,9,5,8,1	@ be sure nothing changes it.
	.byte	5,8,6,9,7,2,0,1,3,4
	.byte	8,9,4,5,3,6,2,0,1,7
	.byte	9,4,3,8,6,1,7,2,0,5
	.byte	2,5,8,1,4,3,6,7,9,0
.align	4			@ Instructions must be word-aligned
	@@@	Grab the argument from the command line, and see
	@@@	if it matches.
_start:	pop	{r0}		@ Is there even an argument?
	cmp 	r0,#2
	movne	r7,#1		@ If not, exit immediately
	swine	#0
	add	sp,sp,#4	@ Discard program name
	pop	{r0}		@ Grab argument
	bl	damm		@ Check if it matches
	ldreq	r1,=pass	@ If yes, say 'pass'
	ldrne	r1,=fail	@ If not, say 'fail'
	mov	r0,#1		@ Print string to stdout
	mov	r2,#5		@ Both are 5 characters
	mov	r7,#4		@ Write syscall = 4
	swi	#0
	mov	r0,#0		@ Exit
	mov	r7,#1
	swi	#0
pass:	.ascii	"Pass\n"
fail:	.ascii	"Fail\n"


import Control.Monad (replicateM)
import Data.Numbers.Primes (isPrime)

--------------------- CYCLOPS NUMBERS --------------------

cyclops :: [Integer]
cyclops = [0 ..] >>= flankingDigits
  where
    flankingDigits 0 = [0]
    flankingDigits n =
      fmap
        (\s -> read s :: Integer)
        ( (fmap ((<>) . (<> "0")) >>= (<*>))
            (replicateM n ['1' .. '9'])
        )

blindPrime :: Integer -> Bool
blindPrime n =
  let s = show n
      m = quot (length s) 2
   in isPrime $
        (\s -> read s :: Integer)
          (take m s <> drop (succ m) s)

palindromic :: Integer -> Bool
palindromic = ((==) =<< reverse) . show

-------------------------- TESTS -------------------------
main :: IO ()
main =
  (putStrLn . unlines)
    [ "First 50 Cyclops numbers – A134808:",
      unwords (show <$> take 50 cyclops),
      "",
      "First 50 Cyclops primes – A134809:",
      unwords $ take 50 [show n | n <- cyclops, isPrime n],
      "",
      "First 50 blind prime Cyclops numbers – A329737:",
      unwords $
        take
          50
          [show n | n <- cyclops, isPrime n, blindPrime n],
      "",
      "First 50 prime palindromic cyclops numbers – A136098:",
      unwords $
        take
          50
          [show n | n <- cyclops, isPrime n, palindromic n]
    ]


## Generic helper functions

def count(s): reduce s as $x (0; .+1);

# counting from 0
def enumerate(s): foreach s as $x (-1; .+1; [., $x]);

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

## Prime numbers
def is_prime:
  if  . == 2 then true
  else
     2 < . and . % 2 == 1 and
       (. as $in
       | (($in + 1) | sqrt) as $m
       | [false, 3] | until( .[0] or .[1] > $m; [$in % .[1] == 0, .[1] + 2])
       | .[0]
       | not)
  end ;

## Cyclops numbers

def iscyclops:
  (tostring | explode) as $d
  | ($d|length) as $l
  | (($l + 1) / 2 - 1) as $m
  | ($l % 2 == 1) and $d[$m] == 48 and count($d[] | select(.== 48)) == 1 # "0"
;

# Generate a stream of cyclops numbers, in increasing numeric order, from 0
def cyclops:
  # generate a stream of cyclops numbers with $n digits on each side of the central 0
  def w:
    if . == 0 then ""
    else (.-1)|w as $left
    | $left + (range(1;10)|tostring)
    end;
  def c: w as $left | $left + "0" + w;
  range(0; infinite) | c | tonumber;

# Generate a stream of palindromic cyclops numbers, in increasing numeric order, from 0
def palindromiccyclops:
  def r: explode|reverse|implode;
  def c: . as $n
    | if $n == 0 then "0"
      elif $n == 1
      then (range(1;10)|tostring) as $base
      | $base + "0" + ($base | r)
      else (range(pow(10;$n-1); pow(10; $n))|tostring|select(test("0")|not)) as $base
      | $base + "0" + ($base | r)
      end;
  range(0; infinite) | c | tonumber;

# check that a cyclops number minus the 0 is prime
def cyclops_isblind:
  (tostring | explode) as $d
  | ($d|length) as $l
  | (($l + 1) / 2 - 1) as $m
  | ((( $d[:$m] + $d[$m+1:] ) | implode | tonumber)  | is_prime);

# check that a cyclops number is a palindrome
def cyclops_ispalindromic:
  . as $in
  | (tostring | explode) as $d
  | ($d|length) as $l
  | (($l + 1) / 2 - 1) as $m
  |  $d[:$m] == ( $d[$m+1:] | reverse) ;


      daysow$ = "Sunday    Monday    Tuesday   Wednesday Thursday  Friday    Saturday"
      months$ = "January   February  March     April     May       June      " + \
      \         "July      August    September October   November  December"

      date$ = TIME$
      dayow% = (INSTR(daysow$, MID$(date$,1,3)) + 9) DIV 10
      month% = (INSTR(months$, MID$(date$,8,3)) + 9) DIV 10

      PRINT MID$(date$,12,4) "-" RIGHT$("0"+STR$month%,2) + "-" + MID$(date$,5,2)

      PRINT FNrtrim(MID$(daysow$, dayow%*10-9, 10)) ", " ;
      PRINT FNrtrim(MID$(months$, month%*10-9, 10)) " " ;
      PRINT MID$(date$,5,2) ", " MID$(date$,12,4)
      END

      DEF FNrtrim(A$)
      WHILE RIGHT$(A$) = " " A$ = LEFT$(A$) : ENDWHILE
      = A$


//  time_to_str(format, time, city, lang)
//  format directives:
//    [sun]       - abbreviated weekday, e.g. Sun
//    [sunday]    - full weekday name, e.g. Sunday
//    [jan]       - abbrev month
//    [january]   - full month
//    [day]       - day of the month 1, 2, ..31
//    [day2]      - day of the month as two digits 01, 02, ..31
//    [hour]      - hour 00, 01, 03..23
//    [hour12]    - hour 1..12
//    [julian]    - day of the year 1..366
//    [month]     - month 1..12
//    [month2]    - month as two digits 01, 02, ..12
//    [minute]    - Minute 00, 01, 02..59
//    [am]        - AM or PM
//    [sec]       - second 00, 01, 02..61
//    [msec]      - millisecond 000...999
//    [week sun]  - week number of the year, sunday based (ranges 01-53, per ISO spec)
//    [week mon]  - week number of the year, monday based
//    [year]      - year with century 2024
//    [year2]     - year without century 00, 01, ..99
//    [date]      - default date format (e.g. Jan 14, 2015  )
//    [date time] -  (e.g. Jan 14, 2015 3:45 PM)
//    [iso date]  = [year]-[month2]-[day2], e.g. 2015-02-22
//    [iso time]  = [hour]:[minute]:[second], e.g. 18:06:05


#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_BUF 50

int main(void)
{
  char buf[MAX_BUF];
  time_t seconds = time(NULL);
  struct tm *now = localtime(&seconds);
  const char *months[] = {"January", "February", "March", "April", "May", "June",
                          "July", "August", "September", "October", "November", "December"};

  const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday"};

  (void) printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
  (void) printf("%s, %s %d, %d\n",days[now->tm_wday], months[now->tm_mon],
               now->tm_mday, now->tm_year + 1900);
  /* using the strftime (the result depends on the locale) */
  (void) strftime(buf, MAX_BUF, "%A, %B %e, %Y", now);
  (void) printf("%s\n", buf);
  return EXIT_SUCCESS;
}


print5x10(a, w = 8) = for i in 0:4, j in 1:10 print(lpad(a[10i + j], w), j == 10 ? "\n" : "") end

function iscyclops(n)
    d = digits(n)
    l = length(d)
    return isodd(l) && d[l ÷ 2 + 1] == 0 && count(x -> x == 0, d) == 1
end

function isblindprimecyclops(n)
    d = digits(n)
    l = length(d)
    m = l ÷ 2 + 1
    (n == 0 || iseven(l) || d[m] != 0 || count(x -> x == 0, d) != 1) && return false
    return isprime(evalpoly(10, [d[1:m-1]; d[m+1:end]]))
end

function ispalindromicprimecyclops(n)
    d = digits(n)
    l = length(d)
    return n > 0 && isodd(l) && d[l ÷ 2 + 1] == 0 && count(x -> x == 0, d) == 1 && d == reverse(d)
end

function findcyclops(N, iscycs, nextcandidate)
    i, list = nextcandidate(-1), Int[]
    while length(list) < N
        iscycs(i) && push!(list, i)
        i = nextcandidate(i)
    end
    return list
end

function nthcyclopsfirstafter(lowerlimit, iscycs, nextcandidate)
    i, found = 0, 0
    while true
        if iscycs(i)
            found += 1
            i >= lowerlimit && break
        end
        i = nextcandidate(i)
    end
    return i, found
end

function testcyclops()
    println("The first 50 cyclops numbers are:")
    print5x10(findcyclops(50, iscyclops, x -> x + 1))
    n, c = nthcyclopsfirstafter(10000000, iscyclops, x -> x + 1)
    println("\nThe next cyclops number after 10,000,000 is $n at position $c.")

    println("\nThe first 50 prime cyclops numbers are:")
    print5x10(findcyclops(50, iscyclops, x -> nextprime(x + 1)))
    n, c = nthcyclopsfirstafter(10000000, iscyclops, x -> nextprime(x + 1))
    println("\nThe next prime cyclops number after 10,000,000 is $n at position $c.")

    println("\nThe first 50 blind prime cyclops numbers are:")
    print5x10(findcyclops(50, isblindprimecyclops, x -> nextprime(x + 1)))
    n, c = nthcyclopsfirstafter(10000000, isblindprimecyclops, x -> nextprime(x + 1))
    println("\nThe next prime cyclops number after 10,000,000 is $n at position $c.")

    println("\nThe first 50 palindromic prime cyclops numbers are:")
    print5x10(findcyclops(50, ispalindromicprimecyclops, x -> nextprime(x + 1)))
    n, c = nthcyclopsfirstafter(10000000, ispalindromicprimecyclops, x -> nextprime(x + 1))
    println("\nThe next prime cyclops number after 10,000,000 is $n at position $c.")
end

testcyclops()


#!/bin/ksh

# Cyclops numbers (odd number of digits that has a zero in the center)
#	- first 50 cyclops numbers
#	- first 50 prime cyclops numbers
#	- first 50 blind prime cyclops numbers
#	- first 50 palindromic prime cyclops numbers

#	# Variables:
#
integer MAXN=50

#	# Functions:
#

#	# Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
	typeset _n ; integer _n=$1
	typeset _i ; integer _i

	(( _n < 2 )) && return 0
	for (( _i=2 ; _i*_i<=_n ; _i++ )); do
		(( ! ( _n % _i ) )) && return 0
	done
	return 1
}

#	# Function _iscyclops(n) - return 1 for cyclops number
#
function _iscyclops {
	typeset _n ; integer _n=$1

	(( ! ${#_n}&1 )) && return 0	# must have odd number of digits
	(( ${_n:$((${#_n}/2)):1} )) && return 0	# must have center zero
	[[ $(_blind ${_n}) == *0* ]] && return 0	# No other zeros

	return 1
}

#	# Function _blind(n) - return a "blinded" cyclops number
#
function _blind {
	typeset _n ; _n="$1"

	echo "${_n:0:$((${#_n}/2))}${_n:$((${#_n}/2+1)):$((${#_n}/2))}"
}

#	# Function _ispalindrome(n) - return 1 for palindromic number
#
function _ispalindrome {
	typeset _n ; _n="$1"
	typeset _flippedn

	_flippedn=$(_flipit ${_n:$((${#_n}/2+1)):$((${#_n}/2))})
	[[ ${_n:0:$((${#_n}/2))} != ${_flippedn} ]] && return 0
	return 1
}

#	# Function _flipit(string) - return flipped string
#
function _flipit {
	typeset _buf ; _buf="$1"
	typeset _tmp ; unset _tmp

	for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do
		_tmp="${_tmp}${_buf:${_i}:1}"
	done

	echo "${_tmp}"
}
 ######
# main #
 ######

integer cy=prcy=blprcy=palprcy=0	# counters
typeset -a cyarr prcyarr blprcyarr palprcyarr

for i in {101..909} {11011..99099} {1110111..9990999}; do
	_iscyclops ${i} ; (( ! $? )) && continue
	(( ++cy <= MAXN )) && cyarr+=( ${i} )

	_isprime ${i} ; (( ! $? )) && continue
	(( ++prcy <= MAXN )) && prcyarr+=( ${i} )

	if (( blprcy < MAXN )); then
		_isprime $(_blind ${i})
		(( $? )) && { (( blprcy++ )) ; blprcyarr+=( ${i} ) }
	fi

	if (( palprcy < MAXN )); then
		_ispalindrome ${i}
		(( $? )) && { (( palprcy++ )) ; palprcyarr+=( ${i} ) }
	fi

	(( palprcy >= MAXN && blprcy >= MAXN && prcy >= MAXN && cy >= MAXN )) && break
done

print "First $MAXN cyclops numbers:"
print ${cyarr[@]}

print "\nFirst $MAXN prime cyclops numbers:"
print ${prcyarr[@]}

print "\nFirst $MAXN blind prime cyclops numbers:"
print ${blprcyarr[@]}

print "\nFirst $MAXN palindromic prime cyclops numbers:"
print ${palprcyarr[@]}


a = Flatten[Table[FromDigits[{i, 0, j}], {i, 9}, {j, 9}], 1];
b = [email protected][[email protected]{i, j}, {i, 9}, {j, 9}];
c = [email protected][[email protected]{i, j, k}, {i, 9}, {j, 9}, {k, 9}];

blindPrimeQ[n_] :=
 Block[{digits = [email protected], m},
  m = Floor[Length[digits]/2];
  PrimeQ[[email protected][digits[[;; m]], digits[[-m ;;]]]]]

palindromeQ[n_] :=
 Block[{digits = [email protected]}, digits === Reverse[digits]]

cyclopsQ[n_] :=
 Block[{digits = [email protected], len, ctr},
  len = Length[digits];
  ctr = Ceiling[len/2];
  And @@ {Mod[len, 2] == 1, ctr > 0, digits[[ctr]] == 0,
    FreeQ[Drop[digits, {ctr}], 0]}]

cyclops = (* all Cyclops numbers with 3, 5 or 7 digits *)
  [email protected]{a,
    Outer[
     [email protected]@{[email protected]#1, 0, [email protected]#2} &, b,
     b],
    Outer[
     [email protected]@{[email protected]#1, 0, [email protected]#2} &, c,
     c]};

x = NestWhile[NextPrime, 10^8, ! ([email protected]# && [email protected]#) &];

Labeled[Partition[Flatten[{0, a}][[;; 50]], 10] //
  TableForm, "First 50 Cyclop numbers", Top]
Labeled[Partition[(primeCyclops = Cases[cyclops, _?PrimeQ])[[;; 50]],
   10] // TableForm, "First 50 prime cyclops numbers", Top]
Labeled[Partition[(blind = Cases[primeCyclops, _?blindPrimeQ])[[;;
      50]], 10] //
  TableForm, "First 50 blind prime cyclops numbers", Top]
Labeled[Partition[(p = Cases[primeCyclops, _?palindromeQ])[[;; 50]],
   10] // TableForm, "First 50 palindromic prime Cyclops Numbers", Top]
Labeled[TableForm[{{x,
    [email protected]}, {NestWhile[NextPrime,
     x + 1, ! ([email protected]# && [email protected]# && [email protected]#) &],
    [email protected]}, {NestWhile[NextPrime,
     x + 1, ! ([email protected]# && [email protected]# && [email protected]#) &],
    [email protected]}},
  TableHeadings -> {{"Prime", "Blind Prime",
     "Palindromic Prime"}, {"Value",
     "Index"}}], "First Cyclops numeber > 10,000,000", Top]


import strutils, times

const Ranges = [0..0, 101..909, 11011..99099, 1110111..9990999, 111101111..999909999]

func isCyclops(d: string): bool =
  d[d.len shr 1] == '0' and d.count('0') == 1

func isPrime(n: Natural): bool =
  if n < 2: return
  if n mod 2 == 0: return n == 2
  if n mod 3 == 0: return n == 3
  var d = 5
  while d * d <= n:
    if n mod d == 0: return false
    inc d, 2
    if n mod d == 0: return false
    inc d, 4
  return true

func isBlind(d: string): bool =
  var d = d
  let m = d.len shr 1
  result = (d[0..m-1] & d[m+1..^1]).parseInt().isPrime

func isPalindromic(d: string): bool =
  for i in 1..d.len:
    if d[i-1] != d[^i]: return
  result = true

iterator cyclops(): (int, int) =
  var count = 0
  for r in Ranges:
    for n in r:
      if ($n).isCyclops:
        inc count
        yield (count, n)

iterator primeCyclops(): (int, int) =
  var count = 0
  for (_, n) in cyclops():
    if n.isPrime:
      inc count
      yield (count, n)

iterator blindPrimeCyclops(): (int, int) =
  var count = 0
  for (_, n) in primeCyclops():
    if ($n).isBlind:
      inc count
      yield (count, n)

iterator palindromicPrimeCyclops(): (int, int) =
  var count = 0
  for r in Ranges:
    for n in r:
      let d = $n
      if d.isCyclops and d.isPalindromic and n.isPrime:
        inc count
        yield (count, n)

let t0 = cpuTime()

echo "List of first 50 cyclops numbers:"
for i, n in cyclops():
  stdout.write ($n).align(3), if i mod 10 == 0: '\n' else: ' '
  if i == 50: break

echo "\nList of first 50 prime cyclops numbers:"
for i, n in primeCyclops():
  stdout.write ($n).align(5), if i mod 10 == 0: '\n' else: ' '
  if i == 50: break

echo "\nList of first 50 blind prime cyclops numbers:"
for i, n in blindPrimeCyclops():
  stdout.write ($n).align(5), if i mod 10 == 0: '\n' else: ' '
  if i == 50: break

echo "\nList of first 50 palindromic prime cyclops numbers:"
for i, n in palindromicPrimeCyclops():
  stdout.write ($n).align(7), if i mod 10 == 0: '\n' else: ' '
  if i == 50: break

for i, n in cyclops():
  if n > 10_000_000:
    echo "\nFirst cyclops number greater than ten million is ",
         ($n).insertSep(), " at 1-based index: ", i
    break

for i, n in primeCyclops():
  if n > 10_000_000:
    echo "\nFirst prime cyclops number greater than ten million is ",
         ($n).insertSep(), " at 1-based index: ", i
    break

for i, n in blindPrimeCyclops():
  if n > 10_000_000:
    echo "\nFirst blind prime cyclops number greater than ten million is ",
         ($n).insertSep(), " at 1-based index: ", i
    break

for i, n in palindromicPrimeCyclops():
  if n > 10_000_000:
    echo "\nFirst palindromic prime cyclops number greater than ten million is ",
         ($n).insertSep(), " at 1-based index: ", i
    break

echo "\nExecution time: ", (cpuTime() - t0).formatFloat(ffDecimal, precision = 3), " seconds."


using System;

namespace RosettaCode.DateFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today = DateTime.Now.Date;
            Console.WriteLine(today.ToString("yyyy-MM-dd"));
            Console.WriteLine(today.ToString("dddd, MMMMM d, yyyy"));
        }
    }
}


// Display the current date in the formats of "2007-11-10"
// and "Sunday, November 10, 2007".

#include <vector>
#include <string>
#include <iostream>
#include <ctime>

/** Return the current date in a string, formatted as either ISO-8601
 *  or "Weekday-name, Month-name Day, Year".
 *
 *  The date is initialized when the object is created and will return
 *  the same date for the lifetime of the object.  The date returned
 *  is the date in the local timezone.
 */
class Date
{
    struct tm ltime;

public:
    /// Default constructor.
    Date()
    {
        time_t t = time(0);
        localtime_r(&t, &ltime);
    }

    /** Return the date based on a format string.  The format string is
     *  fed directly into strftime().  See the strftime() documentation
     *  for information on the proper construction of format strings.
     *
     *  @param[in] fmt is a valid strftime() format string.
     *
     *  @return a string containing the formatted date, or a blank string
     *      if the format string was invalid or resulted in a string that
     *      exceeded the internal buffer length.
     */
    std::string getDate(const char* fmt)
    {
        char out[200];
        size_t result = strftime(out, sizeof out, fmt, &ltime);
        return std::string(out, out + result);
    }

    /** Return the date in ISO-8601 date format.
     *
     *  @return a string containing the date in ISO-8601 date format.
     */
    std::string getISODate() {return getDate("%F");}

    /** Return the date formatted as "Weekday-name, Month-name Day, Year".
     *
     *  @return a string containing the date in the specified format.
     */
    std::string getTextDate() {return getDate("%A, %B %d, %Y");}
};

int main()
{
    Date d;
    std::cout << d.getISODate() << std::endl;
    std::cout << d.getTextDate() << std::endl;
    return 0;
}