Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from Perl to VB.
use strict; use warnings; use Time::Local; my $year = shift // 1969; my $width = shift // 80; my $columns = int +($width + 2) / 22 or die "width too short at $width"; print map { center($_, $width), "\n" } '<reserved for snoopy>', $year; my @months = qw( January February March April May June July August September October November December ); my @days = qw( 31 28 31 30 31 30 31 31 30 31 30 31 ); (gmtime 86400 + timegm 1,1,1,28,1,$year)[3] == 29 and $days[1]++; my @blocks = map { my $m = center($months[$_], 20) . "\nSu Mo Tu We Th Fr Sa\n" . "00 00 00 00 00 00 00\n" x 6; $m =~ s/00/ / for 1 .. (gmtime timegm 1,1,1,1,$_,$year )[6]; $m =~ s/00/ center($_, 2) /e for 1 .. $days[$_]; $m =~ s/00/ /g; [ split /\n/, $m ] } 0 .. 11; while( my @row = splice @blocks, 0, $columns ) { print center(join(' ', map shift @$_, @row), $width) for 1 .. @{$row[0]}; } sub center { my ($string, $w) = @_; sprintf "%${w}s", $string . ' ' x ($w - length($string) >> 1); }
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Write a version of this Perl function in Go with identical behavior.
use strict; use warnings; use Time::Local; my $year = shift // 1969; my $width = shift // 80; my $columns = int +($width + 2) / 22 or die "width too short at $width"; print map { center($_, $width), "\n" } '<reserved for snoopy>', $year; my @months = qw( January February March April May June July August September October November December ); my @days = qw( 31 28 31 30 31 30 31 31 30 31 30 31 ); (gmtime 86400 + timegm 1,1,1,28,1,$year)[3] == 29 and $days[1]++; my @blocks = map { my $m = center($months[$_], 20) . "\nSu Mo Tu We Th Fr Sa\n" . "00 00 00 00 00 00 00\n" x 6; $m =~ s/00/ / for 1 .. (gmtime timegm 1,1,1,1,$_,$year )[6]; $m =~ s/00/ center($_, 2) /e for 1 .. $days[$_]; $m =~ s/00/ /g; [ split /\n/, $m ] } 0 .. 11; while( my @row = splice @blocks, 0, $columns ) { print center(join(' ', map shift @$_, @row), $width) for 1 .. @{$row[0]}; } sub center { my ($string, $w) = @_; sprintf "%${w}s", $string . ' ' x ($w - length($string) >> 1); }
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Translate this program into C but keep the logic exactly as in PowerShell.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
Change the following PowerShell code into C# without altering its purpose.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Translate this program into C++ but keep the logic exactly as in PowerShell.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
Produce a language-to-language conversion: from PowerShell to Java, same semantics.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Rewrite the snippet below in Python so it works the same as the original PowerShell code.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Convert the following code from PowerShell to VB, ensuring the logic remains intact.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Ensure the translated Go code behaves exactly like the original PowerShell snippet.
Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9 Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') } Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Change the following Racket code into C without altering its purpose.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
Port the following code from Racket to C# with equivalent syntax and logic.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Port the provided Racket code into C++ while preserving the original functionality.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
Write a version of this Racket function in Java with identical behavior.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Generate a Python translation of this Racket snippet without changing its computational steps.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Rewrite this program in VB while keeping its functionality equivalent to the Racket version.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Convert the following code from Racket to Go, ensuring the logic remains intact.
#lang racket (require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months (for/list ([mn (in-naturals 1)] [mname '(January February March April May June July August September October November December)]) (define s (find-seconds 0 0 12 1 mn yr)) (define pfx (date-week-day (seconds->date s))) (define days (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) 60 60 24)))) (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" (map string-join (nsplit 7 `(,@(make-list pfx " ") ,@(for/list ([d days]) (~a (+ d 1) #:width 2 #:align 'right)) ,@(make-list (- 42 pfx days) " "))))))) (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] [o (open-output-string)]) (inflate (open-input-bytes (base64-decode s)) o) (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) (λ(s) (equal? "" s))))) (calendar 1969)
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Translate this program into C# but keep the logic exactly as in COBOL.
IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER PIC X(09) VALUE 'TUESDAY '. 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. 03 FILLER PIC X(09) VALUE 'THURSDAY '. 03 FILLER PIC X(09) VALUE 'FRIDAY '. 03 FILLER PIC X(09) VALUE 'SATURDAY '. 01 FILLER REDEFINES WS-DAY-NAMES-DEF. 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. 01 WS-MTH-INFO-DEF. 03 FILLER PIC X(11) VALUE 'JANUARY 31'. 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. 03 FILLER PIC X(11) VALUE 'MARCH 31'. 03 FILLER PIC X(11) VALUE 'APRIL 30'. 03 FILLER PIC X(11) VALUE 'MAY 31'. 03 FILLER PIC X(11) VALUE 'JUNE 30'. 03 FILLER PIC X(11) VALUE 'JULY 31'. 03 FILLER PIC X(11) VALUE 'AUGUST 31'. 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. 01 FILLER REDEFINES WS-MTH-INFO-DEF. 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. 05 WS-MTH-INFO-NAME PIC X(09). 05 WS-MTH-INFO-DAYS PIC 9(02). 01 WS-MTH-AREA. 03 WS-MTH-DD PIC S99. 03 WS-DAY1 PIC 9. 03 WS-DAYS PIC 99. 03 WS-DD PIC 9. 03 WS-WK PIC 9. 03 WS-MM PIC 99. 03 WS-QQ PIC 99. 03 WS-MTH-MONTH OCCURS 12 TIMES. 05 WS-MTH-WEEK OCCURS 6 TIMES. 07 WS-DAY-FLD OCCURS 7 TIMES. 09 WS-DAY PIC ZZ. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). 01 WS-PRT PIC X(132). 01 WS-COL PIC 9(03) VALUE 0. 01 WS-PP PIC 9(03) VALUE 0. 01 WS-CFGN. 03 FILLER PIC 9(03) VALUE 80. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 1. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 2. 01 WS-CFGW. 03 FILLER PIC 9(03) VALUE 120. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 2. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 3. 01 WS-CFG. 03 WS-LS PIC 9(03) VALUE 120. 03 WS-LMAR PIC 9(02) VALUE 10. 03 WS-SPBD PIC 9(01) VALUE 2. 03 WS-SPBC PIC 9(02) VALUE 10. 03 WS-DNMW PIC 9(01) VALUE 3. PROCEDURE DIVISION. MOVE '1969-01-01' TO INPDATE-RECORD MOVE WS-CFGN TO WS-CFG IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 AND FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) MOVE 29 TO WS-MTH-INFO-DAYS (02) ELSE MOVE 28 TO WS-MTH-INFO-DAYS (02) END-IF PERFORM VARYING WS-MM FROM 1 BY +1 UNTIL WS-MM > 12 MOVE WS-MM TO INPD-MONTH CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW COMPUTE WS-MTH-DD = 1 - WMS-DOW COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 COMPUTE WS-MTH-DD = WS-MTH-DD + 1 IF (WS-MTH-DD < 1) OR (WS-MTH-DD > WS-DAYS) MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) ELSE MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) END-IF END-PERFORM END-PERFORM END-PERFORM COMPUTE WS-MM = 0 PERFORM VARYING WS-QQ FROM 1 BY +1 UNTIL WS-QQ > 4 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF MOVE WS-MTH-INFO-NAME (WS-MM) TO WS-PRT(WS-PP:9) COMPUTE WS-PP = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) - 4 MOVE INPD-YEAR TO WS-PRT (WS-PP:4) COMPUTE WS-PP = WS-PP + 4 END-PERFORM DISPLAY WS-PRT (1:WS-LS) INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW END-IF MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) TO WS-PRT (WS-PP:WS-DNMW) COMPUTE WS-PP = WS-PP + WS-DNMW END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR ELSE COMPUTE WS-PP = WS-PP + WS-SPBC END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD END-IF MOVE WS-DAY (WS-MM, WS-WK, WS-DD) TO WS-PRT (WS-PP:2) COMPUTE WS-PP = WS-PP + 2 END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) END-PERFORM DISPLAY ' ' END-PERFORM GOBACK . END PROGRAM CALEND. IDENTIFICATION DIVISION. PROGRAM-ID. DATE2DOW. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WMS-WORK-AREA. 03 WMS-YEAR PIC 9(04). 03 WMS-MONTH PIC 9(02). 03 WMS-CSYS PIC 9(01) VALUE 1. 03 WMS-SUM pic 9(04). LINKAGE SECTION. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. 1010-CONVERT-DATE-TO-DOW. IF INPD-MONTH < 3 COMPUTE WMS-MONTH = INPD-MONTH + 12 COMPUTE WMS-YEAR = INPD-YEAR - 1 ELSE COMPUTE WMS-MONTH = INPD-MONTH COMPUTE WMS-YEAR = INPD-YEAR END-IF COMPUTE WMS-SUM = ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + FUNCTION INTEGER ( WMS-YEAR / 4 ) - FUNCTION INTEGER ( WMS-YEAR / 100 ) + FUNCTION INTEGER ( WMS-YEAR / 400 ) + WMS-CSYS ) COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 GOBACK . END PROGRAM DATE2DOW.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Preserve the algorithm and functionality while converting the code from COBOL to Java.
IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER PIC X(09) VALUE 'TUESDAY '. 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. 03 FILLER PIC X(09) VALUE 'THURSDAY '. 03 FILLER PIC X(09) VALUE 'FRIDAY '. 03 FILLER PIC X(09) VALUE 'SATURDAY '. 01 FILLER REDEFINES WS-DAY-NAMES-DEF. 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. 01 WS-MTH-INFO-DEF. 03 FILLER PIC X(11) VALUE 'JANUARY 31'. 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. 03 FILLER PIC X(11) VALUE 'MARCH 31'. 03 FILLER PIC X(11) VALUE 'APRIL 30'. 03 FILLER PIC X(11) VALUE 'MAY 31'. 03 FILLER PIC X(11) VALUE 'JUNE 30'. 03 FILLER PIC X(11) VALUE 'JULY 31'. 03 FILLER PIC X(11) VALUE 'AUGUST 31'. 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. 01 FILLER REDEFINES WS-MTH-INFO-DEF. 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. 05 WS-MTH-INFO-NAME PIC X(09). 05 WS-MTH-INFO-DAYS PIC 9(02). 01 WS-MTH-AREA. 03 WS-MTH-DD PIC S99. 03 WS-DAY1 PIC 9. 03 WS-DAYS PIC 99. 03 WS-DD PIC 9. 03 WS-WK PIC 9. 03 WS-MM PIC 99. 03 WS-QQ PIC 99. 03 WS-MTH-MONTH OCCURS 12 TIMES. 05 WS-MTH-WEEK OCCURS 6 TIMES. 07 WS-DAY-FLD OCCURS 7 TIMES. 09 WS-DAY PIC ZZ. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). 01 WS-PRT PIC X(132). 01 WS-COL PIC 9(03) VALUE 0. 01 WS-PP PIC 9(03) VALUE 0. 01 WS-CFGN. 03 FILLER PIC 9(03) VALUE 80. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 1. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 2. 01 WS-CFGW. 03 FILLER PIC 9(03) VALUE 120. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 2. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 3. 01 WS-CFG. 03 WS-LS PIC 9(03) VALUE 120. 03 WS-LMAR PIC 9(02) VALUE 10. 03 WS-SPBD PIC 9(01) VALUE 2. 03 WS-SPBC PIC 9(02) VALUE 10. 03 WS-DNMW PIC 9(01) VALUE 3. PROCEDURE DIVISION. MOVE '1969-01-01' TO INPDATE-RECORD MOVE WS-CFGN TO WS-CFG IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 AND FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) MOVE 29 TO WS-MTH-INFO-DAYS (02) ELSE MOVE 28 TO WS-MTH-INFO-DAYS (02) END-IF PERFORM VARYING WS-MM FROM 1 BY +1 UNTIL WS-MM > 12 MOVE WS-MM TO INPD-MONTH CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW COMPUTE WS-MTH-DD = 1 - WMS-DOW COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 COMPUTE WS-MTH-DD = WS-MTH-DD + 1 IF (WS-MTH-DD < 1) OR (WS-MTH-DD > WS-DAYS) MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) ELSE MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) END-IF END-PERFORM END-PERFORM END-PERFORM COMPUTE WS-MM = 0 PERFORM VARYING WS-QQ FROM 1 BY +1 UNTIL WS-QQ > 4 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF MOVE WS-MTH-INFO-NAME (WS-MM) TO WS-PRT(WS-PP:9) COMPUTE WS-PP = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) - 4 MOVE INPD-YEAR TO WS-PRT (WS-PP:4) COMPUTE WS-PP = WS-PP + 4 END-PERFORM DISPLAY WS-PRT (1:WS-LS) INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW END-IF MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) TO WS-PRT (WS-PP:WS-DNMW) COMPUTE WS-PP = WS-PP + WS-DNMW END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR ELSE COMPUTE WS-PP = WS-PP + WS-SPBC END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD END-IF MOVE WS-DAY (WS-MM, WS-WK, WS-DD) TO WS-PRT (WS-PP:2) COMPUTE WS-PP = WS-PP + 2 END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) END-PERFORM DISPLAY ' ' END-PERFORM GOBACK . END PROGRAM CALEND. IDENTIFICATION DIVISION. PROGRAM-ID. DATE2DOW. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WMS-WORK-AREA. 03 WMS-YEAR PIC 9(04). 03 WMS-MONTH PIC 9(02). 03 WMS-CSYS PIC 9(01) VALUE 1. 03 WMS-SUM pic 9(04). LINKAGE SECTION. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. 1010-CONVERT-DATE-TO-DOW. IF INPD-MONTH < 3 COMPUTE WMS-MONTH = INPD-MONTH + 12 COMPUTE WMS-YEAR = INPD-YEAR - 1 ELSE COMPUTE WMS-MONTH = INPD-MONTH COMPUTE WMS-YEAR = INPD-YEAR END-IF COMPUTE WMS-SUM = ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + FUNCTION INTEGER ( WMS-YEAR / 4 ) - FUNCTION INTEGER ( WMS-YEAR / 100 ) + FUNCTION INTEGER ( WMS-YEAR / 400 ) + WMS-CSYS ) COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 GOBACK . END PROGRAM DATE2DOW.
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Can you help me rewrite this code in Python instead of COBOL, keeping it the same logically?
IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER PIC X(09) VALUE 'TUESDAY '. 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. 03 FILLER PIC X(09) VALUE 'THURSDAY '. 03 FILLER PIC X(09) VALUE 'FRIDAY '. 03 FILLER PIC X(09) VALUE 'SATURDAY '. 01 FILLER REDEFINES WS-DAY-NAMES-DEF. 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. 01 WS-MTH-INFO-DEF. 03 FILLER PIC X(11) VALUE 'JANUARY 31'. 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. 03 FILLER PIC X(11) VALUE 'MARCH 31'. 03 FILLER PIC X(11) VALUE 'APRIL 30'. 03 FILLER PIC X(11) VALUE 'MAY 31'. 03 FILLER PIC X(11) VALUE 'JUNE 30'. 03 FILLER PIC X(11) VALUE 'JULY 31'. 03 FILLER PIC X(11) VALUE 'AUGUST 31'. 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. 01 FILLER REDEFINES WS-MTH-INFO-DEF. 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. 05 WS-MTH-INFO-NAME PIC X(09). 05 WS-MTH-INFO-DAYS PIC 9(02). 01 WS-MTH-AREA. 03 WS-MTH-DD PIC S99. 03 WS-DAY1 PIC 9. 03 WS-DAYS PIC 99. 03 WS-DD PIC 9. 03 WS-WK PIC 9. 03 WS-MM PIC 99. 03 WS-QQ PIC 99. 03 WS-MTH-MONTH OCCURS 12 TIMES. 05 WS-MTH-WEEK OCCURS 6 TIMES. 07 WS-DAY-FLD OCCURS 7 TIMES. 09 WS-DAY PIC ZZ. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). 01 WS-PRT PIC X(132). 01 WS-COL PIC 9(03) VALUE 0. 01 WS-PP PIC 9(03) VALUE 0. 01 WS-CFGN. 03 FILLER PIC 9(03) VALUE 80. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 1. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 2. 01 WS-CFGW. 03 FILLER PIC 9(03) VALUE 120. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 2. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 3. 01 WS-CFG. 03 WS-LS PIC 9(03) VALUE 120. 03 WS-LMAR PIC 9(02) VALUE 10. 03 WS-SPBD PIC 9(01) VALUE 2. 03 WS-SPBC PIC 9(02) VALUE 10. 03 WS-DNMW PIC 9(01) VALUE 3. PROCEDURE DIVISION. MOVE '1969-01-01' TO INPDATE-RECORD MOVE WS-CFGN TO WS-CFG IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 AND FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) MOVE 29 TO WS-MTH-INFO-DAYS (02) ELSE MOVE 28 TO WS-MTH-INFO-DAYS (02) END-IF PERFORM VARYING WS-MM FROM 1 BY +1 UNTIL WS-MM > 12 MOVE WS-MM TO INPD-MONTH CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW COMPUTE WS-MTH-DD = 1 - WMS-DOW COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 COMPUTE WS-MTH-DD = WS-MTH-DD + 1 IF (WS-MTH-DD < 1) OR (WS-MTH-DD > WS-DAYS) MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) ELSE MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) END-IF END-PERFORM END-PERFORM END-PERFORM COMPUTE WS-MM = 0 PERFORM VARYING WS-QQ FROM 1 BY +1 UNTIL WS-QQ > 4 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF MOVE WS-MTH-INFO-NAME (WS-MM) TO WS-PRT(WS-PP:9) COMPUTE WS-PP = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) - 4 MOVE INPD-YEAR TO WS-PRT (WS-PP:4) COMPUTE WS-PP = WS-PP + 4 END-PERFORM DISPLAY WS-PRT (1:WS-LS) INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW END-IF MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) TO WS-PRT (WS-PP:WS-DNMW) COMPUTE WS-PP = WS-PP + WS-DNMW END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR ELSE COMPUTE WS-PP = WS-PP + WS-SPBC END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD END-IF MOVE WS-DAY (WS-MM, WS-WK, WS-DD) TO WS-PRT (WS-PP:2) COMPUTE WS-PP = WS-PP + 2 END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) END-PERFORM DISPLAY ' ' END-PERFORM GOBACK . END PROGRAM CALEND. IDENTIFICATION DIVISION. PROGRAM-ID. DATE2DOW. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WMS-WORK-AREA. 03 WMS-YEAR PIC 9(04). 03 WMS-MONTH PIC 9(02). 03 WMS-CSYS PIC 9(01) VALUE 1. 03 WMS-SUM pic 9(04). LINKAGE SECTION. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. 1010-CONVERT-DATE-TO-DOW. IF INPD-MONTH < 3 COMPUTE WMS-MONTH = INPD-MONTH + 12 COMPUTE WMS-YEAR = INPD-YEAR - 1 ELSE COMPUTE WMS-MONTH = INPD-MONTH COMPUTE WMS-YEAR = INPD-YEAR END-IF COMPUTE WMS-SUM = ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + FUNCTION INTEGER ( WMS-YEAR / 4 ) - FUNCTION INTEGER ( WMS-YEAR / 100 ) + FUNCTION INTEGER ( WMS-YEAR / 400 ) + WMS-CSYS ) COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 GOBACK . END PROGRAM DATE2DOW.
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Port the following code from COBOL to VB with equivalent syntax and logic.
IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER PIC X(09) VALUE 'TUESDAY '. 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. 03 FILLER PIC X(09) VALUE 'THURSDAY '. 03 FILLER PIC X(09) VALUE 'FRIDAY '. 03 FILLER PIC X(09) VALUE 'SATURDAY '. 01 FILLER REDEFINES WS-DAY-NAMES-DEF. 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. 01 WS-MTH-INFO-DEF. 03 FILLER PIC X(11) VALUE 'JANUARY 31'. 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. 03 FILLER PIC X(11) VALUE 'MARCH 31'. 03 FILLER PIC X(11) VALUE 'APRIL 30'. 03 FILLER PIC X(11) VALUE 'MAY 31'. 03 FILLER PIC X(11) VALUE 'JUNE 30'. 03 FILLER PIC X(11) VALUE 'JULY 31'. 03 FILLER PIC X(11) VALUE 'AUGUST 31'. 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. 01 FILLER REDEFINES WS-MTH-INFO-DEF. 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. 05 WS-MTH-INFO-NAME PIC X(09). 05 WS-MTH-INFO-DAYS PIC 9(02). 01 WS-MTH-AREA. 03 WS-MTH-DD PIC S99. 03 WS-DAY1 PIC 9. 03 WS-DAYS PIC 99. 03 WS-DD PIC 9. 03 WS-WK PIC 9. 03 WS-MM PIC 99. 03 WS-QQ PIC 99. 03 WS-MTH-MONTH OCCURS 12 TIMES. 05 WS-MTH-WEEK OCCURS 6 TIMES. 07 WS-DAY-FLD OCCURS 7 TIMES. 09 WS-DAY PIC ZZ. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). 01 WS-PRT PIC X(132). 01 WS-COL PIC 9(03) VALUE 0. 01 WS-PP PIC 9(03) VALUE 0. 01 WS-CFGN. 03 FILLER PIC 9(03) VALUE 80. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 1. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 2. 01 WS-CFGW. 03 FILLER PIC 9(03) VALUE 120. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 2. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 3. 01 WS-CFG. 03 WS-LS PIC 9(03) VALUE 120. 03 WS-LMAR PIC 9(02) VALUE 10. 03 WS-SPBD PIC 9(01) VALUE 2. 03 WS-SPBC PIC 9(02) VALUE 10. 03 WS-DNMW PIC 9(01) VALUE 3. PROCEDURE DIVISION. MOVE '1969-01-01' TO INPDATE-RECORD MOVE WS-CFGN TO WS-CFG IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 AND FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) MOVE 29 TO WS-MTH-INFO-DAYS (02) ELSE MOVE 28 TO WS-MTH-INFO-DAYS (02) END-IF PERFORM VARYING WS-MM FROM 1 BY +1 UNTIL WS-MM > 12 MOVE WS-MM TO INPD-MONTH CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW COMPUTE WS-MTH-DD = 1 - WMS-DOW COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 COMPUTE WS-MTH-DD = WS-MTH-DD + 1 IF (WS-MTH-DD < 1) OR (WS-MTH-DD > WS-DAYS) MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) ELSE MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) END-IF END-PERFORM END-PERFORM END-PERFORM COMPUTE WS-MM = 0 PERFORM VARYING WS-QQ FROM 1 BY +1 UNTIL WS-QQ > 4 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF MOVE WS-MTH-INFO-NAME (WS-MM) TO WS-PRT(WS-PP:9) COMPUTE WS-PP = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) - 4 MOVE INPD-YEAR TO WS-PRT (WS-PP:4) COMPUTE WS-PP = WS-PP + 4 END-PERFORM DISPLAY WS-PRT (1:WS-LS) INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW END-IF MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) TO WS-PRT (WS-PP:WS-DNMW) COMPUTE WS-PP = WS-PP + WS-DNMW END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR ELSE COMPUTE WS-PP = WS-PP + WS-SPBC END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD END-IF MOVE WS-DAY (WS-MM, WS-WK, WS-DD) TO WS-PRT (WS-PP:2) COMPUTE WS-PP = WS-PP + 2 END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) END-PERFORM DISPLAY ' ' END-PERFORM GOBACK . END PROGRAM CALEND. IDENTIFICATION DIVISION. PROGRAM-ID. DATE2DOW. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WMS-WORK-AREA. 03 WMS-YEAR PIC 9(04). 03 WMS-MONTH PIC 9(02). 03 WMS-CSYS PIC 9(01) VALUE 1. 03 WMS-SUM pic 9(04). LINKAGE SECTION. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. 1010-CONVERT-DATE-TO-DOW. IF INPD-MONTH < 3 COMPUTE WMS-MONTH = INPD-MONTH + 12 COMPUTE WMS-YEAR = INPD-YEAR - 1 ELSE COMPUTE WMS-MONTH = INPD-MONTH COMPUTE WMS-YEAR = INPD-YEAR END-IF COMPUTE WMS-SUM = ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + FUNCTION INTEGER ( WMS-YEAR / 4 ) - FUNCTION INTEGER ( WMS-YEAR / 100 ) + FUNCTION INTEGER ( WMS-YEAR / 400 ) + WMS-CSYS ) COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 GOBACK . END PROGRAM DATE2DOW.
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Rewrite this program in Go while keeping its functionality equivalent to the COBOL version.
IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER PIC X(09) VALUE 'TUESDAY '. 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. 03 FILLER PIC X(09) VALUE 'THURSDAY '. 03 FILLER PIC X(09) VALUE 'FRIDAY '. 03 FILLER PIC X(09) VALUE 'SATURDAY '. 01 FILLER REDEFINES WS-DAY-NAMES-DEF. 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. 01 WS-MTH-INFO-DEF. 03 FILLER PIC X(11) VALUE 'JANUARY 31'. 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. 03 FILLER PIC X(11) VALUE 'MARCH 31'. 03 FILLER PIC X(11) VALUE 'APRIL 30'. 03 FILLER PIC X(11) VALUE 'MAY 31'. 03 FILLER PIC X(11) VALUE 'JUNE 30'. 03 FILLER PIC X(11) VALUE 'JULY 31'. 03 FILLER PIC X(11) VALUE 'AUGUST 31'. 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. 01 FILLER REDEFINES WS-MTH-INFO-DEF. 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. 05 WS-MTH-INFO-NAME PIC X(09). 05 WS-MTH-INFO-DAYS PIC 9(02). 01 WS-MTH-AREA. 03 WS-MTH-DD PIC S99. 03 WS-DAY1 PIC 9. 03 WS-DAYS PIC 99. 03 WS-DD PIC 9. 03 WS-WK PIC 9. 03 WS-MM PIC 99. 03 WS-QQ PIC 99. 03 WS-MTH-MONTH OCCURS 12 TIMES. 05 WS-MTH-WEEK OCCURS 6 TIMES. 07 WS-DAY-FLD OCCURS 7 TIMES. 09 WS-DAY PIC ZZ. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). 01 WS-PRT PIC X(132). 01 WS-COL PIC 9(03) VALUE 0. 01 WS-PP PIC 9(03) VALUE 0. 01 WS-CFGN. 03 FILLER PIC 9(03) VALUE 80. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 1. 03 FILLER PIC 9(02) VALUE 5. 03 FILLER PIC 9(01) VALUE 2. 01 WS-CFGW. 03 FILLER PIC 9(03) VALUE 120. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 2. 03 FILLER PIC 9(02) VALUE 10. 03 FILLER PIC 9(01) VALUE 3. 01 WS-CFG. 03 WS-LS PIC 9(03) VALUE 120. 03 WS-LMAR PIC 9(02) VALUE 10. 03 WS-SPBD PIC 9(01) VALUE 2. 03 WS-SPBC PIC 9(02) VALUE 10. 03 WS-DNMW PIC 9(01) VALUE 3. PROCEDURE DIVISION. MOVE '1969-01-01' TO INPDATE-RECORD MOVE WS-CFGN TO WS-CFG IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 AND FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) MOVE 29 TO WS-MTH-INFO-DAYS (02) ELSE MOVE 28 TO WS-MTH-INFO-DAYS (02) END-IF PERFORM VARYING WS-MM FROM 1 BY +1 UNTIL WS-MM > 12 MOVE WS-MM TO INPD-MONTH CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW COMPUTE WS-MTH-DD = 1 - WMS-DOW COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 COMPUTE WS-MTH-DD = WS-MTH-DD + 1 IF (WS-MTH-DD < 1) OR (WS-MTH-DD > WS-DAYS) MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) ELSE MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) END-IF END-PERFORM END-PERFORM END-PERFORM COMPUTE WS-MM = 0 PERFORM VARYING WS-QQ FROM 1 BY +1 UNTIL WS-QQ > 4 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF MOVE WS-MTH-INFO-NAME (WS-MM) TO WS-PRT(WS-PP:9) COMPUTE WS-PP = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) - 4 MOVE INPD-YEAR TO WS-PRT (WS-PP:4) COMPUTE WS-PP = WS-PP + 4 END-PERFORM DISPLAY WS-PRT (1:WS-LS) INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW ELSE COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW END-IF MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) TO WS-PRT (WS-PP:WS-DNMW) COMPUTE WS-PP = WS-PP + WS-DNMW END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) PERFORM VARYING WS-WK FROM 1 BY +1 UNTIL WS-WK > 6 INITIALIZE WS-PRT COMPUTE WS-PP = 1 PERFORM VARYING WS-COL FROM 1 BY +1 UNTIL WS-COL > 3 COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL IF WS-COL = 1 COMPUTE WS-PP = WS-PP + WS-LMAR ELSE COMPUTE WS-PP = WS-PP + WS-SPBC END-IF PERFORM VARYING WS-DD FROM 1 BY +1 UNTIL WS-DD > 7 IF WS-DD > 1 COMPUTE WS-PP = WS-PP + WS-SPBD END-IF MOVE WS-DAY (WS-MM, WS-WK, WS-DD) TO WS-PRT (WS-PP:2) COMPUTE WS-PP = WS-PP + 2 END-PERFORM END-PERFORM DISPLAY WS-PRT (1:WS-LS) END-PERFORM DISPLAY ' ' END-PERFORM GOBACK . END PROGRAM CALEND. IDENTIFICATION DIVISION. PROGRAM-ID. DATE2DOW. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WMS-WORK-AREA. 03 WMS-YEAR PIC 9(04). 03 WMS-MONTH PIC 9(02). 03 WMS-CSYS PIC 9(01) VALUE 1. 03 WMS-SUM pic 9(04). LINKAGE SECTION. 01 INPDATE-RECORD. 05 INPD-YEAR PIC 9(04). 05 FILLER PIC X(01). 05 INPD-MONTH PIC 9(02). 05 FILLER PIC X(01). 05 INPD-DAY PIC 9(02). 01 WMS-DOW PIC 9(01). PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. 1010-CONVERT-DATE-TO-DOW. IF INPD-MONTH < 3 COMPUTE WMS-MONTH = INPD-MONTH + 12 COMPUTE WMS-YEAR = INPD-YEAR - 1 ELSE COMPUTE WMS-MONTH = INPD-MONTH COMPUTE WMS-YEAR = INPD-YEAR END-IF COMPUTE WMS-SUM = ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + FUNCTION INTEGER ( WMS-YEAR / 4 ) - FUNCTION INTEGER ( WMS-YEAR / 100 ) + FUNCTION INTEGER ( WMS-YEAR / 400 ) + WMS-CSYS ) COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 GOBACK . END PROGRAM DATE2DOW.
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Produce a language-to-language conversion: from REXX to C#, same semantics.
@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU calfill=' '; mc=12; _='1 3 1234567890' "fb"x parse var _ grid calspaces # chk . cv_ days.1 days.2 days.3 daysn sd sw _=0; parse var _ cols 1 jd 1 lowerCase 1 maxKalPuts 1 narrow 1, narrower 1 narrowest 1 short 1 shorter 1 shortest 1, small 1 smaller 1 smallest 1 upperCase parse arg mm '/' dd "/" yyyy _ '(' ops; uops=ops if _\=='' | \is#(mm) | \is#(dd) | \is#(yyyy) then call erx 86 do while ops\==''; ops=strip(ops,'L'); parse var ops _1 2 1 _ . 1 _o ops upper _ select when abb('CALSPaces') then calspaces=nai() when abb('DEPth') then sd=nai() when abbn('GRIDs') then grid=no() when abbn('LOWercase') then lowerCase=no() when abb('CALMONths') then mc=nai() when abbn('NARrow') then narrow=no() when abbn('NARROWER') then narrower=no() when abbn('NARROWESt') then narrowest=no() when abbn('SHORt') then short=no() when abbn('SHORTER') then shorter=no() when abbn('SHORTESt') then shortest=no() when abbn('SMALl') then small=no() when abbn('SMALLER') then smaller=no() when abbn('SMALLESt') then smallest=no() when abbn('UPPercase') then upperCase=no() when abb('WIDth') then sw=nai() otherwise nop end end mc=int(mc,'monthscalender'); if mc>0 then cal=1 days='Sunday Monday Tuesday Wednesday Thursday Friday Saturday' months='January February March April May June July August September October November December' days=' 'days; months=' 'months cyyyy=right(date(),4); hyy=left(cyyyy,2); lyy=right(cyyyy,2) dy.=31; _=30; parse var _ dy.4 1 dy.6 1 dy.9 1 dy.11; dy.2=28+ly(yyyy) yy=right(yyyy,2); sd=p(sd 43); sw=p(sw 80); cw=10; cindent=1; calwidth=76 if small then do; narrow=1 ; short=1 ; end if smaller then do; narrower=1 ; shorter=1 ; end if smallest then do; narrowest=1; shortest=1; end if shortest then shorter=1 if shorter then short =1 if narrow then do; cw=9; cindent=3; calwidth=69; end if narrower then do; cw=4; cindent=1; calwidth=34; end if narrowest then do; cw=2; cindent=1; calwidth=20; end cv_=calwidth+calspaces+2 calfill=left(copies(calfill,cw),cw) do j=1 for 7; _=word(days,j) do jw=1 for 3; _d=strip(substr(_,cw*jw-cw+1,cw)) if jw=1 then _d=centre(_d,cw+1) else _d=left(_d,cw+1) days.jw=days.jw||_d end __=daysn if narrower then daysn=__||centre(left(_,3),5) if narrowest then daysn=__||center(left(_,2),3) end _yyyy=yyyy; calPuts=0; cv=1; _mm=mm+0; month=word(months,mm) dy.2=28+ly(_yyyy); dim=dy._mm; _dd=01; dow=dow(_mm,_dd,_yyyy); $dd=dd+0 call calGen do _j=2 to mc if cv_\=='' then do cv=cv+cv_ if cv+cv_>=sw then do; cv=1; call calPut call fcalPuts;call calPb end else calPuts=0 end else do;call calPb;call calPut;call fcalPuts;end _mm=_mm+1; if _mm==13 then do; _mm=1; _yyyy=_yyyy+1; end month=word(months,_mm); dy.2=28+ly(_yyyy); dim=dy._mm dow=dow(_mm,_dd,_yyyy); $dd=0; call calGen end call fcalPuts return _ calGen: cellX=;cellJ=;cellM=;calCells=0;calline=0 call calPut call calPutl copies('─',calwidth),"┌┐"; call calHd call calPutl month ' ' _yyyy ; call calHd if narrowest | narrower then call calPutl daysn else do jw=1 for 3 if space(days.jw)\=='' then call calPutl days.jw end calft=1; calfb=0 do jf=1 for dow-1; call cellDraw calFill,calFill; end do jy=1 for dim; call cellDraw jy; end calfb=1 do 7; call cellDraw calFill,calFill; end if sd>32 & \shorter then call calPut return cellDraw: parse arg zz,cdDOY;zz=right(zz,2);calCells=calCells+1 if calCells>7 then do calLine=calLine+1 cellX=substr(cellX,2) cellJ=substr(cellJ,2) cellM=substr(cellM,2) cellB=translate(cellX,,")(─-"#) if calLine==1 then call cx call calCsm; call calPutl cellX; call calCsj; call cx cellX=; cellJ=; cellM=; calCells=1 end cdDOY=right(cdDOY,cw); cellM=cellM'│'center('',cw) cellX=cellX'│'centre(zz,cw); cellJ=cellJ'│'center('',cw) return abb:arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) abbl:return verify(arg(1)'a',@abc,'M')-1 abbn:parse arg abbn;return abb(abbn)|abb('NO'abbn) calCsj:if sd>49&\shorter then call calPutl cellB;if sd>24&\short then call calPutl cellJ; return calCsm:if sd>24&\short then call calPutl cellM;if sd>49&\shorter then call calPutl cellB;return calHd:if sd>24&\shorter then call calPutl;if sd>32&\shortest then call calPutl;return calPb:if \grid&shortest then call put chk;return calPut:calPuts=calPuts+1;maxKalPuts=max(maxKalPuts,calPuts);if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=;ct.calPuts=overlay(arg(1),ct.calPuts,cv);return calPutl:call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return cx:cx_='├┤';cx=copies(copies('─',cw)'┼',7);if calft then do;cx=translate(cx,'┬',"┼");calft=0;end;if calfb then do;cx=translate(cx,'┴',"┼");cx_='└┘';calfb=0;end;call calPutl cx,cx_;return dow:procedure;arg m,d,y;if m<3 then do;m=m+12;y=y-1;end;yl=left(y,2);yr=right(y,2);w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7;if w==0 then w=7;return w er:parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result err:call er '-'arg(1),arg(2);return '' erx:call er '-'arg(1),arg(2);exit '' fcalPuts: do j=1 for maxKalPuts;call put ct.j;end;ct.=;maxKalPuts=0;calPuts=0;return int:int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2);return int/1 is#:return verify(arg(1),#)==0 isint:return datatype(arg(1),'W') lower:return translate(arg(1),@abc,@abcU) ly:arg _;if length(_)==2 then _=hyy||_;ly=_//4==0;if ly==0 then return 0;ly=((_//100\==0)|_//400==0);return ly na:if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na nai:return int(na(),_o) nan:return numx(na(),_o) no:if arg(1)\=='' then call erx 01,arg(2);return left(_,2)\=='NO' num:procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() numnot:if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f numx:return num(arg(1),arg(2),1) p:return word(arg(1),1) put:_=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return tell:say arg(1);return ungrid:return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣")
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Write a version of this REXX function in Java with identical behavior.
@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU calfill=' '; mc=12; _='1 3 1234567890' "fb"x parse var _ grid calspaces # chk . cv_ days.1 days.2 days.3 daysn sd sw _=0; parse var _ cols 1 jd 1 lowerCase 1 maxKalPuts 1 narrow 1, narrower 1 narrowest 1 short 1 shorter 1 shortest 1, small 1 smaller 1 smallest 1 upperCase parse arg mm '/' dd "/" yyyy _ '(' ops; uops=ops if _\=='' | \is#(mm) | \is#(dd) | \is#(yyyy) then call erx 86 do while ops\==''; ops=strip(ops,'L'); parse var ops _1 2 1 _ . 1 _o ops upper _ select when abb('CALSPaces') then calspaces=nai() when abb('DEPth') then sd=nai() when abbn('GRIDs') then grid=no() when abbn('LOWercase') then lowerCase=no() when abb('CALMONths') then mc=nai() when abbn('NARrow') then narrow=no() when abbn('NARROWER') then narrower=no() when abbn('NARROWESt') then narrowest=no() when abbn('SHORt') then short=no() when abbn('SHORTER') then shorter=no() when abbn('SHORTESt') then shortest=no() when abbn('SMALl') then small=no() when abbn('SMALLER') then smaller=no() when abbn('SMALLESt') then smallest=no() when abbn('UPPercase') then upperCase=no() when abb('WIDth') then sw=nai() otherwise nop end end mc=int(mc,'monthscalender'); if mc>0 then cal=1 days='Sunday Monday Tuesday Wednesday Thursday Friday Saturday' months='January February March April May June July August September October November December' days=' 'days; months=' 'months cyyyy=right(date(),4); hyy=left(cyyyy,2); lyy=right(cyyyy,2) dy.=31; _=30; parse var _ dy.4 1 dy.6 1 dy.9 1 dy.11; dy.2=28+ly(yyyy) yy=right(yyyy,2); sd=p(sd 43); sw=p(sw 80); cw=10; cindent=1; calwidth=76 if small then do; narrow=1 ; short=1 ; end if smaller then do; narrower=1 ; shorter=1 ; end if smallest then do; narrowest=1; shortest=1; end if shortest then shorter=1 if shorter then short =1 if narrow then do; cw=9; cindent=3; calwidth=69; end if narrower then do; cw=4; cindent=1; calwidth=34; end if narrowest then do; cw=2; cindent=1; calwidth=20; end cv_=calwidth+calspaces+2 calfill=left(copies(calfill,cw),cw) do j=1 for 7; _=word(days,j) do jw=1 for 3; _d=strip(substr(_,cw*jw-cw+1,cw)) if jw=1 then _d=centre(_d,cw+1) else _d=left(_d,cw+1) days.jw=days.jw||_d end __=daysn if narrower then daysn=__||centre(left(_,3),5) if narrowest then daysn=__||center(left(_,2),3) end _yyyy=yyyy; calPuts=0; cv=1; _mm=mm+0; month=word(months,mm) dy.2=28+ly(_yyyy); dim=dy._mm; _dd=01; dow=dow(_mm,_dd,_yyyy); $dd=dd+0 call calGen do _j=2 to mc if cv_\=='' then do cv=cv+cv_ if cv+cv_>=sw then do; cv=1; call calPut call fcalPuts;call calPb end else calPuts=0 end else do;call calPb;call calPut;call fcalPuts;end _mm=_mm+1; if _mm==13 then do; _mm=1; _yyyy=_yyyy+1; end month=word(months,_mm); dy.2=28+ly(_yyyy); dim=dy._mm dow=dow(_mm,_dd,_yyyy); $dd=0; call calGen end call fcalPuts return _ calGen: cellX=;cellJ=;cellM=;calCells=0;calline=0 call calPut call calPutl copies('─',calwidth),"┌┐"; call calHd call calPutl month ' ' _yyyy ; call calHd if narrowest | narrower then call calPutl daysn else do jw=1 for 3 if space(days.jw)\=='' then call calPutl days.jw end calft=1; calfb=0 do jf=1 for dow-1; call cellDraw calFill,calFill; end do jy=1 for dim; call cellDraw jy; end calfb=1 do 7; call cellDraw calFill,calFill; end if sd>32 & \shorter then call calPut return cellDraw: parse arg zz,cdDOY;zz=right(zz,2);calCells=calCells+1 if calCells>7 then do calLine=calLine+1 cellX=substr(cellX,2) cellJ=substr(cellJ,2) cellM=substr(cellM,2) cellB=translate(cellX,,")(─-"#) if calLine==1 then call cx call calCsm; call calPutl cellX; call calCsj; call cx cellX=; cellJ=; cellM=; calCells=1 end cdDOY=right(cdDOY,cw); cellM=cellM'│'center('',cw) cellX=cellX'│'centre(zz,cw); cellJ=cellJ'│'center('',cw) return abb:arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) abbl:return verify(arg(1)'a',@abc,'M')-1 abbn:parse arg abbn;return abb(abbn)|abb('NO'abbn) calCsj:if sd>49&\shorter then call calPutl cellB;if sd>24&\short then call calPutl cellJ; return calCsm:if sd>24&\short then call calPutl cellM;if sd>49&\shorter then call calPutl cellB;return calHd:if sd>24&\shorter then call calPutl;if sd>32&\shortest then call calPutl;return calPb:if \grid&shortest then call put chk;return calPut:calPuts=calPuts+1;maxKalPuts=max(maxKalPuts,calPuts);if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=;ct.calPuts=overlay(arg(1),ct.calPuts,cv);return calPutl:call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return cx:cx_='├┤';cx=copies(copies('─',cw)'┼',7);if calft then do;cx=translate(cx,'┬',"┼");calft=0;end;if calfb then do;cx=translate(cx,'┴',"┼");cx_='└┘';calfb=0;end;call calPutl cx,cx_;return dow:procedure;arg m,d,y;if m<3 then do;m=m+12;y=y-1;end;yl=left(y,2);yr=right(y,2);w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7;if w==0 then w=7;return w er:parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result err:call er '-'arg(1),arg(2);return '' erx:call er '-'arg(1),arg(2);exit '' fcalPuts: do j=1 for maxKalPuts;call put ct.j;end;ct.=;maxKalPuts=0;calPuts=0;return int:int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2);return int/1 is#:return verify(arg(1),#)==0 isint:return datatype(arg(1),'W') lower:return translate(arg(1),@abc,@abcU) ly:arg _;if length(_)==2 then _=hyy||_;ly=_//4==0;if ly==0 then return 0;ly=((_//100\==0)|_//400==0);return ly na:if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na nai:return int(na(),_o) nan:return numx(na(),_o) no:if arg(1)\=='' then call erx 01,arg(2);return left(_,2)\=='NO' num:procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() numnot:if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f numx:return num(arg(1),arg(2),1) p:return word(arg(1),1) put:_=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return tell:say arg(1);return ungrid:return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣")
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Rewrite the snippet below in Python so it works the same as the original REXX code.
@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU calfill=' '; mc=12; _='1 3 1234567890' "fb"x parse var _ grid calspaces # chk . cv_ days.1 days.2 days.3 daysn sd sw _=0; parse var _ cols 1 jd 1 lowerCase 1 maxKalPuts 1 narrow 1, narrower 1 narrowest 1 short 1 shorter 1 shortest 1, small 1 smaller 1 smallest 1 upperCase parse arg mm '/' dd "/" yyyy _ '(' ops; uops=ops if _\=='' | \is#(mm) | \is#(dd) | \is#(yyyy) then call erx 86 do while ops\==''; ops=strip(ops,'L'); parse var ops _1 2 1 _ . 1 _o ops upper _ select when abb('CALSPaces') then calspaces=nai() when abb('DEPth') then sd=nai() when abbn('GRIDs') then grid=no() when abbn('LOWercase') then lowerCase=no() when abb('CALMONths') then mc=nai() when abbn('NARrow') then narrow=no() when abbn('NARROWER') then narrower=no() when abbn('NARROWESt') then narrowest=no() when abbn('SHORt') then short=no() when abbn('SHORTER') then shorter=no() when abbn('SHORTESt') then shortest=no() when abbn('SMALl') then small=no() when abbn('SMALLER') then smaller=no() when abbn('SMALLESt') then smallest=no() when abbn('UPPercase') then upperCase=no() when abb('WIDth') then sw=nai() otherwise nop end end mc=int(mc,'monthscalender'); if mc>0 then cal=1 days='Sunday Monday Tuesday Wednesday Thursday Friday Saturday' months='January February March April May June July August September October November December' days=' 'days; months=' 'months cyyyy=right(date(),4); hyy=left(cyyyy,2); lyy=right(cyyyy,2) dy.=31; _=30; parse var _ dy.4 1 dy.6 1 dy.9 1 dy.11; dy.2=28+ly(yyyy) yy=right(yyyy,2); sd=p(sd 43); sw=p(sw 80); cw=10; cindent=1; calwidth=76 if small then do; narrow=1 ; short=1 ; end if smaller then do; narrower=1 ; shorter=1 ; end if smallest then do; narrowest=1; shortest=1; end if shortest then shorter=1 if shorter then short =1 if narrow then do; cw=9; cindent=3; calwidth=69; end if narrower then do; cw=4; cindent=1; calwidth=34; end if narrowest then do; cw=2; cindent=1; calwidth=20; end cv_=calwidth+calspaces+2 calfill=left(copies(calfill,cw),cw) do j=1 for 7; _=word(days,j) do jw=1 for 3; _d=strip(substr(_,cw*jw-cw+1,cw)) if jw=1 then _d=centre(_d,cw+1) else _d=left(_d,cw+1) days.jw=days.jw||_d end __=daysn if narrower then daysn=__||centre(left(_,3),5) if narrowest then daysn=__||center(left(_,2),3) end _yyyy=yyyy; calPuts=0; cv=1; _mm=mm+0; month=word(months,mm) dy.2=28+ly(_yyyy); dim=dy._mm; _dd=01; dow=dow(_mm,_dd,_yyyy); $dd=dd+0 call calGen do _j=2 to mc if cv_\=='' then do cv=cv+cv_ if cv+cv_>=sw then do; cv=1; call calPut call fcalPuts;call calPb end else calPuts=0 end else do;call calPb;call calPut;call fcalPuts;end _mm=_mm+1; if _mm==13 then do; _mm=1; _yyyy=_yyyy+1; end month=word(months,_mm); dy.2=28+ly(_yyyy); dim=dy._mm dow=dow(_mm,_dd,_yyyy); $dd=0; call calGen end call fcalPuts return _ calGen: cellX=;cellJ=;cellM=;calCells=0;calline=0 call calPut call calPutl copies('─',calwidth),"┌┐"; call calHd call calPutl month ' ' _yyyy ; call calHd if narrowest | narrower then call calPutl daysn else do jw=1 for 3 if space(days.jw)\=='' then call calPutl days.jw end calft=1; calfb=0 do jf=1 for dow-1; call cellDraw calFill,calFill; end do jy=1 for dim; call cellDraw jy; end calfb=1 do 7; call cellDraw calFill,calFill; end if sd>32 & \shorter then call calPut return cellDraw: parse arg zz,cdDOY;zz=right(zz,2);calCells=calCells+1 if calCells>7 then do calLine=calLine+1 cellX=substr(cellX,2) cellJ=substr(cellJ,2) cellM=substr(cellM,2) cellB=translate(cellX,,")(─-"#) if calLine==1 then call cx call calCsm; call calPutl cellX; call calCsj; call cx cellX=; cellJ=; cellM=; calCells=1 end cdDOY=right(cdDOY,cw); cellM=cellM'│'center('',cw) cellX=cellX'│'centre(zz,cw); cellJ=cellJ'│'center('',cw) return abb:arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) abbl:return verify(arg(1)'a',@abc,'M')-1 abbn:parse arg abbn;return abb(abbn)|abb('NO'abbn) calCsj:if sd>49&\shorter then call calPutl cellB;if sd>24&\short then call calPutl cellJ; return calCsm:if sd>24&\short then call calPutl cellM;if sd>49&\shorter then call calPutl cellB;return calHd:if sd>24&\shorter then call calPutl;if sd>32&\shortest then call calPutl;return calPb:if \grid&shortest then call put chk;return calPut:calPuts=calPuts+1;maxKalPuts=max(maxKalPuts,calPuts);if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=;ct.calPuts=overlay(arg(1),ct.calPuts,cv);return calPutl:call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return cx:cx_='├┤';cx=copies(copies('─',cw)'┼',7);if calft then do;cx=translate(cx,'┬',"┼");calft=0;end;if calfb then do;cx=translate(cx,'┴',"┼");cx_='└┘';calfb=0;end;call calPutl cx,cx_;return dow:procedure;arg m,d,y;if m<3 then do;m=m+12;y=y-1;end;yl=left(y,2);yr=right(y,2);w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7;if w==0 then w=7;return w er:parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result err:call er '-'arg(1),arg(2);return '' erx:call er '-'arg(1),arg(2);exit '' fcalPuts: do j=1 for maxKalPuts;call put ct.j;end;ct.=;maxKalPuts=0;calPuts=0;return int:int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2);return int/1 is#:return verify(arg(1),#)==0 isint:return datatype(arg(1),'W') lower:return translate(arg(1),@abc,@abcU) ly:arg _;if length(_)==2 then _=hyy||_;ly=_//4==0;if ly==0 then return 0;ly=((_//100\==0)|_//400==0);return ly na:if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na nai:return int(na(),_o) nan:return numx(na(),_o) no:if arg(1)\=='' then call erx 01,arg(2);return left(_,2)\=='NO' num:procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() numnot:if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f numx:return num(arg(1),arg(2),1) p:return word(arg(1),1) put:_=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return tell:say arg(1);return ungrid:return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣")
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Translate the given REXX code snippet into VB without altering its behavior.
@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU calfill=' '; mc=12; _='1 3 1234567890' "fb"x parse var _ grid calspaces # chk . cv_ days.1 days.2 days.3 daysn sd sw _=0; parse var _ cols 1 jd 1 lowerCase 1 maxKalPuts 1 narrow 1, narrower 1 narrowest 1 short 1 shorter 1 shortest 1, small 1 smaller 1 smallest 1 upperCase parse arg mm '/' dd "/" yyyy _ '(' ops; uops=ops if _\=='' | \is#(mm) | \is#(dd) | \is#(yyyy) then call erx 86 do while ops\==''; ops=strip(ops,'L'); parse var ops _1 2 1 _ . 1 _o ops upper _ select when abb('CALSPaces') then calspaces=nai() when abb('DEPth') then sd=nai() when abbn('GRIDs') then grid=no() when abbn('LOWercase') then lowerCase=no() when abb('CALMONths') then mc=nai() when abbn('NARrow') then narrow=no() when abbn('NARROWER') then narrower=no() when abbn('NARROWESt') then narrowest=no() when abbn('SHORt') then short=no() when abbn('SHORTER') then shorter=no() when abbn('SHORTESt') then shortest=no() when abbn('SMALl') then small=no() when abbn('SMALLER') then smaller=no() when abbn('SMALLESt') then smallest=no() when abbn('UPPercase') then upperCase=no() when abb('WIDth') then sw=nai() otherwise nop end end mc=int(mc,'monthscalender'); if mc>0 then cal=1 days='Sunday Monday Tuesday Wednesday Thursday Friday Saturday' months='January February March April May June July August September October November December' days=' 'days; months=' 'months cyyyy=right(date(),4); hyy=left(cyyyy,2); lyy=right(cyyyy,2) dy.=31; _=30; parse var _ dy.4 1 dy.6 1 dy.9 1 dy.11; dy.2=28+ly(yyyy) yy=right(yyyy,2); sd=p(sd 43); sw=p(sw 80); cw=10; cindent=1; calwidth=76 if small then do; narrow=1 ; short=1 ; end if smaller then do; narrower=1 ; shorter=1 ; end if smallest then do; narrowest=1; shortest=1; end if shortest then shorter=1 if shorter then short =1 if narrow then do; cw=9; cindent=3; calwidth=69; end if narrower then do; cw=4; cindent=1; calwidth=34; end if narrowest then do; cw=2; cindent=1; calwidth=20; end cv_=calwidth+calspaces+2 calfill=left(copies(calfill,cw),cw) do j=1 for 7; _=word(days,j) do jw=1 for 3; _d=strip(substr(_,cw*jw-cw+1,cw)) if jw=1 then _d=centre(_d,cw+1) else _d=left(_d,cw+1) days.jw=days.jw||_d end __=daysn if narrower then daysn=__||centre(left(_,3),5) if narrowest then daysn=__||center(left(_,2),3) end _yyyy=yyyy; calPuts=0; cv=1; _mm=mm+0; month=word(months,mm) dy.2=28+ly(_yyyy); dim=dy._mm; _dd=01; dow=dow(_mm,_dd,_yyyy); $dd=dd+0 call calGen do _j=2 to mc if cv_\=='' then do cv=cv+cv_ if cv+cv_>=sw then do; cv=1; call calPut call fcalPuts;call calPb end else calPuts=0 end else do;call calPb;call calPut;call fcalPuts;end _mm=_mm+1; if _mm==13 then do; _mm=1; _yyyy=_yyyy+1; end month=word(months,_mm); dy.2=28+ly(_yyyy); dim=dy._mm dow=dow(_mm,_dd,_yyyy); $dd=0; call calGen end call fcalPuts return _ calGen: cellX=;cellJ=;cellM=;calCells=0;calline=0 call calPut call calPutl copies('─',calwidth),"┌┐"; call calHd call calPutl month ' ' _yyyy ; call calHd if narrowest | narrower then call calPutl daysn else do jw=1 for 3 if space(days.jw)\=='' then call calPutl days.jw end calft=1; calfb=0 do jf=1 for dow-1; call cellDraw calFill,calFill; end do jy=1 for dim; call cellDraw jy; end calfb=1 do 7; call cellDraw calFill,calFill; end if sd>32 & \shorter then call calPut return cellDraw: parse arg zz,cdDOY;zz=right(zz,2);calCells=calCells+1 if calCells>7 then do calLine=calLine+1 cellX=substr(cellX,2) cellJ=substr(cellJ,2) cellM=substr(cellM,2) cellB=translate(cellX,,")(─-"#) if calLine==1 then call cx call calCsm; call calPutl cellX; call calCsj; call cx cellX=; cellJ=; cellM=; calCells=1 end cdDOY=right(cdDOY,cw); cellM=cellM'│'center('',cw) cellX=cellX'│'centre(zz,cw); cellJ=cellJ'│'center('',cw) return abb:arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) abbl:return verify(arg(1)'a',@abc,'M')-1 abbn:parse arg abbn;return abb(abbn)|abb('NO'abbn) calCsj:if sd>49&\shorter then call calPutl cellB;if sd>24&\short then call calPutl cellJ; return calCsm:if sd>24&\short then call calPutl cellM;if sd>49&\shorter then call calPutl cellB;return calHd:if sd>24&\shorter then call calPutl;if sd>32&\shortest then call calPutl;return calPb:if \grid&shortest then call put chk;return calPut:calPuts=calPuts+1;maxKalPuts=max(maxKalPuts,calPuts);if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=;ct.calPuts=overlay(arg(1),ct.calPuts,cv);return calPutl:call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return cx:cx_='├┤';cx=copies(copies('─',cw)'┼',7);if calft then do;cx=translate(cx,'┬',"┼");calft=0;end;if calfb then do;cx=translate(cx,'┴',"┼");cx_='└┘';calfb=0;end;call calPutl cx,cx_;return dow:procedure;arg m,d,y;if m<3 then do;m=m+12;y=y-1;end;yl=left(y,2);yr=right(y,2);w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7;if w==0 then w=7;return w er:parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result err:call er '-'arg(1),arg(2);return '' erx:call er '-'arg(1),arg(2);exit '' fcalPuts: do j=1 for maxKalPuts;call put ct.j;end;ct.=;maxKalPuts=0;calPuts=0;return int:int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2);return int/1 is#:return verify(arg(1),#)==0 isint:return datatype(arg(1),'W') lower:return translate(arg(1),@abc,@abcU) ly:arg _;if length(_)==2 then _=hyy||_;ly=_//4==0;if ly==0 then return 0;ly=((_//100\==0)|_//400==0);return ly na:if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na nai:return int(na(),_o) nan:return numx(na(),_o) no:if arg(1)\=='' then call erx 01,arg(2);return left(_,2)\=='NO' num:procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() numnot:if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f numx:return num(arg(1),arg(2),1) p:return word(arg(1),1) put:_=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return tell:say arg(1);return ungrid:return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣")
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Rewrite this program in Go while keeping its functionality equivalent to the REXX version.
@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU calfill=' '; mc=12; _='1 3 1234567890' "fb"x parse var _ grid calspaces # chk . cv_ days.1 days.2 days.3 daysn sd sw _=0; parse var _ cols 1 jd 1 lowerCase 1 maxKalPuts 1 narrow 1, narrower 1 narrowest 1 short 1 shorter 1 shortest 1, small 1 smaller 1 smallest 1 upperCase parse arg mm '/' dd "/" yyyy _ '(' ops; uops=ops if _\=='' | \is#(mm) | \is#(dd) | \is#(yyyy) then call erx 86 do while ops\==''; ops=strip(ops,'L'); parse var ops _1 2 1 _ . 1 _o ops upper _ select when abb('CALSPaces') then calspaces=nai() when abb('DEPth') then sd=nai() when abbn('GRIDs') then grid=no() when abbn('LOWercase') then lowerCase=no() when abb('CALMONths') then mc=nai() when abbn('NARrow') then narrow=no() when abbn('NARROWER') then narrower=no() when abbn('NARROWESt') then narrowest=no() when abbn('SHORt') then short=no() when abbn('SHORTER') then shorter=no() when abbn('SHORTESt') then shortest=no() when abbn('SMALl') then small=no() when abbn('SMALLER') then smaller=no() when abbn('SMALLESt') then smallest=no() when abbn('UPPercase') then upperCase=no() when abb('WIDth') then sw=nai() otherwise nop end end mc=int(mc,'monthscalender'); if mc>0 then cal=1 days='Sunday Monday Tuesday Wednesday Thursday Friday Saturday' months='January February March April May June July August September October November December' days=' 'days; months=' 'months cyyyy=right(date(),4); hyy=left(cyyyy,2); lyy=right(cyyyy,2) dy.=31; _=30; parse var _ dy.4 1 dy.6 1 dy.9 1 dy.11; dy.2=28+ly(yyyy) yy=right(yyyy,2); sd=p(sd 43); sw=p(sw 80); cw=10; cindent=1; calwidth=76 if small then do; narrow=1 ; short=1 ; end if smaller then do; narrower=1 ; shorter=1 ; end if smallest then do; narrowest=1; shortest=1; end if shortest then shorter=1 if shorter then short =1 if narrow then do; cw=9; cindent=3; calwidth=69; end if narrower then do; cw=4; cindent=1; calwidth=34; end if narrowest then do; cw=2; cindent=1; calwidth=20; end cv_=calwidth+calspaces+2 calfill=left(copies(calfill,cw),cw) do j=1 for 7; _=word(days,j) do jw=1 for 3; _d=strip(substr(_,cw*jw-cw+1,cw)) if jw=1 then _d=centre(_d,cw+1) else _d=left(_d,cw+1) days.jw=days.jw||_d end __=daysn if narrower then daysn=__||centre(left(_,3),5) if narrowest then daysn=__||center(left(_,2),3) end _yyyy=yyyy; calPuts=0; cv=1; _mm=mm+0; month=word(months,mm) dy.2=28+ly(_yyyy); dim=dy._mm; _dd=01; dow=dow(_mm,_dd,_yyyy); $dd=dd+0 call calGen do _j=2 to mc if cv_\=='' then do cv=cv+cv_ if cv+cv_>=sw then do; cv=1; call calPut call fcalPuts;call calPb end else calPuts=0 end else do;call calPb;call calPut;call fcalPuts;end _mm=_mm+1; if _mm==13 then do; _mm=1; _yyyy=_yyyy+1; end month=word(months,_mm); dy.2=28+ly(_yyyy); dim=dy._mm dow=dow(_mm,_dd,_yyyy); $dd=0; call calGen end call fcalPuts return _ calGen: cellX=;cellJ=;cellM=;calCells=0;calline=0 call calPut call calPutl copies('─',calwidth),"┌┐"; call calHd call calPutl month ' ' _yyyy ; call calHd if narrowest | narrower then call calPutl daysn else do jw=1 for 3 if space(days.jw)\=='' then call calPutl days.jw end calft=1; calfb=0 do jf=1 for dow-1; call cellDraw calFill,calFill; end do jy=1 for dim; call cellDraw jy; end calfb=1 do 7; call cellDraw calFill,calFill; end if sd>32 & \shorter then call calPut return cellDraw: parse arg zz,cdDOY;zz=right(zz,2);calCells=calCells+1 if calCells>7 then do calLine=calLine+1 cellX=substr(cellX,2) cellJ=substr(cellJ,2) cellM=substr(cellM,2) cellB=translate(cellX,,")(─-"#) if calLine==1 then call cx call calCsm; call calPutl cellX; call calCsj; call cx cellX=; cellJ=; cellM=; calCells=1 end cdDOY=right(cdDOY,cw); cellM=cellM'│'center('',cw) cellX=cellX'│'centre(zz,cw); cellJ=cellJ'│'center('',cw) return abb:arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) abbl:return verify(arg(1)'a',@abc,'M')-1 abbn:parse arg abbn;return abb(abbn)|abb('NO'abbn) calCsj:if sd>49&\shorter then call calPutl cellB;if sd>24&\short then call calPutl cellJ; return calCsm:if sd>24&\short then call calPutl cellM;if sd>49&\shorter then call calPutl cellB;return calHd:if sd>24&\shorter then call calPutl;if sd>32&\shortest then call calPutl;return calPb:if \grid&shortest then call put chk;return calPut:calPuts=calPuts+1;maxKalPuts=max(maxKalPuts,calPuts);if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=;ct.calPuts=overlay(arg(1),ct.calPuts,cv);return calPutl:call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return cx:cx_='├┤';cx=copies(copies('─',cw)'┼',7);if calft then do;cx=translate(cx,'┬',"┼");calft=0;end;if calfb then do;cx=translate(cx,'┴',"┼");cx_='└┘';calfb=0;end;call calPutl cx,cx_;return dow:procedure;arg m,d,y;if m<3 then do;m=m+12;y=y-1;end;yl=left(y,2);yr=right(y,2);w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7;if w==0 then w=7;return w er:parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result err:call er '-'arg(1),arg(2);return '' erx:call er '-'arg(1),arg(2);exit '' fcalPuts: do j=1 for maxKalPuts;call put ct.j;end;ct.=;maxKalPuts=0;calPuts=0;return int:int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2);return int/1 is#:return verify(arg(1),#)==0 isint:return datatype(arg(1),'W') lower:return translate(arg(1),@abc,@abcU) ly:arg _;if length(_)==2 then _=hyy||_;ly=_//4==0;if ly==0 then return 0;ly=((_//100\==0)|_//400==0);return ly na:if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na nai:return int(na(),_o) nan:return numx(na(),_o) no:if arg(1)\=='' then call erx 01,arg(2);return left(_,2)\=='NO' num:procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() numnot:if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f numx:return num(arg(1),arg(2),1) p:return word(arg(1),1) put:_=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return tell:say arg(1);return ungrid:return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣")
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Keep all operations the same but rewrite the snippet in C.
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
Translate this program into C# but keep the logic exactly as in Ruby.
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Convert this Ruby block to C++, preserving its control flow and logic.
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
Rewrite this program in Java while keeping its functionality equivalent to the Ruby version.
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Can you help me rewrite this code in Python instead of Ruby, keeping it the same logically?
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Translate the given Ruby code snippet into VB without altering its behavior.
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Generate a Go translation of this Ruby snippet without changing its computational steps.
require 'date' def cal(year, columns) date = Date.new(year, 1, 1, Date::ENGLAND) months = (1..12).collect do |month| rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"] days = [] date.wday.times { days.push " " } while date.month == month days.push("%2d" % date.mday) date += 1 end (42 - days.length).times { days.push " " } days.each_slice(7) { |week| rows.push(week.join " ") } next rows end mpr = (columns + 2).div 22 mpr = 12.div((12 + mpr - 1).div mpr) width = mpr * 22 - 2 rows = ["[Snoopy]".center(width), " months.each_slice(mpr) do |slice| slice[0].each_index do |i| rows.push(slice.map {|a| a[i]}.join " ") end end return rows.join("\n") end ARGV.length == 1 or abort "usage: columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError begin Integer(`tput cols`) rescue 80; end; end; end puts cal(Integer(ARGV[0]), columns)
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Rewrite this program in C while keeping its functionality equivalent to the Scala version.
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
Please provide an equivalent version of this Scala code in C#.
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Change the programming language of this snippet from Scala to C++ without modifying what it does.
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
Translate the given Scala code snippet into Java without altering its behavior.
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Convert this Scala block to Python, preserving its control flow and logic.
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Can you help me rewrite this code in VB instead of Scala, keeping it the same logically?
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Generate a Go translation of this Scala snippet without changing its computational steps.
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgumentException("Illegal column width.") val w = nCols * 24 val nRows = Math.ceil(12.0 / nCols).toInt() val date = GregorianCalendar(year, 0, 1) var offs = date.get(Calendar.DAY_OF_WEEK) - 1 val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") val mons = Array(12) { Array(8) { "" } } DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name -> val len = 11 + name.length / 2 val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len) mons[m][0] = String.format(format, name, "") mons[m][1] = days val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH) for (d in 1..42) { val isDay = d > offs && d <= offs + dim val entry = if (isDay) String.format(" %2s", d - offs) else " " if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry else mons[m][2 + (d - 1) / 7] += entry } offs = (offs + dim) % 7 date.add(Calendar.MONTH, 1) } printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { printf(" %s", mons[c][i]) c++ } println() } println() } } fun main(args: Array<String>) { System.out.printCalendar(1969, 3, Locale.US) }
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Port the following code from Swift to C with equivalent syntax and logic.
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
Can you help me rewrite this code in C# instead of Swift, keeping it the same logically?
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Rewrite the snippet below in C++ so it works the same as the original Swift code.
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
Write the same algorithm in Java as shown in this Swift implementation.
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Write the same algorithm in Python as shown in this Swift implementation.
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Rewrite this program in VB while keeping its functionality equivalent to the Swift version.
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Port the provided Swift code into Go while preserving the original functionality.
import Foundation let monthWidth = 20 let monthGap = 2 let dayNames = "Su Mo Tu We Th Fr Sa" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" func rpad(string: String, width: Int) -> String { return string.count >= width ? string : String(repeating: " ", count: width - string.count) + string } func lpad(string: String, width: Int) -> String { return string.count >= width ? string : string + String(repeating: " ", count: width - string.count) } func centre(string: String, width: Int) -> String { if string.count >= width { return string } let c = (width - string.count)/2 return String(repeating: " ", count: c) + string + String(repeating: " ", count: width - string.count - c) } func formatMonth(year: Int, month: Int) -> [String] { let calendar = Calendar.current let dc = DateComponents(year: year, month: month, day: 1) let date = calendar.date(from: dc)! let firstDay = calendar.component(.weekday, from: date) - 1 let range = calendar.range(of: .day, in: .month, for: date)! let daysInMonth = range.count var lines: [String] = [] lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth)) lines.append(dayNames) var padWidth = 2 var line = String(repeating: " ", count: 3 * firstDay) for day in 1...daysInMonth { line += rpad(string: String(day), width: padWidth) padWidth = 3 if (firstDay + day) % 7 == 0 { lines.append(line) line = "" padWidth = 2 } } if line.count > 0 { lines.append(lpad(string: line, width: monthWidth)) } return lines } func printCentred(string: String, width: Int) { print(rpad(string: string, width: (width + string.count)/2)) } public func printCalendar(year: Int, width: Int) { let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap))) let lineWidth = monthWidth * months + monthGap * (months - 1) printCentred(string: "[Snoopy]", width: lineWidth) printCentred(string: String(year), width: lineWidth) var firstMonth = 1 while firstMonth <= 12 { if firstMonth > 1 { print() } let lastMonth = min(12, firstMonth + months - 1) let monthCount = lastMonth - firstMonth + 1 var lines: [[String]] = [] var lineCount = 0 for month in firstMonth...lastMonth { let monthLines = formatMonth(year: year, month: month) lineCount = max(lineCount, monthLines.count) lines.append(monthLines) } for i in 0..<lineCount { var line = "" for month in 0..<monthCount { if month > 0 { line.append(String(repeating: " ", count: monthGap)) } line.append(i < lines[month].count ? lines[month][i] : String(repeating: " ", count: monthWidth)) } print(line) } firstMonth = lastMonth + 1 } } printCalendar(year: 1969, width: 80)
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Write the same algorithm in C as shown in this Tcl implementation.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
Preserve the algorithm and functionality while converting the code from Tcl to C#.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
Generate an equivalent C++ version of this Tcl code.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
Convert this Tcl snippet to Java and keep its semantics consistent.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
Produce a functionally identical Python code for the snippet given in Tcl.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Translate the given Tcl code snippet into VB without altering its behavior.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Generate an equivalent Go version of this Tcl code.
package require Tcl 8.5 proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"] while 1 { set moment [clock add $moment 1 day] lassign [clock format $moment -timezone $timezone -locale $locale \ -format "%m %d %u"] m d dow if {[scan $m %d] != $month} { return $days } lappend days $moment [scan $d %d] $dow } } proc calMonth {year month timezone locale} { set dow 0 set line "" set lines {} foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] { if {![llength $lines]} {lappend lines $t} if {$dow > $dayofweek} { lappend lines [string trimright $line] set line "" set dow 0 } while {$dow < $dayofweek-1} { append line " " incr dow } append line [format "%2d " $day] set dow $dayofweek } lappend lines [string trimright $line] } proc cal3Month {year month timezone locale} { set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month set d3 [lassign [calMonth $year $month $timezone $locale] t3] foreach t [list $t1 $t2 $t3] { set m [clock format $t -timezone $timezone -locale $locale -format "%B"] set l [expr {10 + [string length $m]/2}] puts -nonewline [format "%-25s" [format "%*s" $l $m]] } puts "" foreach l1 $d1 l2 $d2 l3 $d3 { puts [format "%-25s%-25s%s" $l1 $l2 $l3] } } proc cal {{year ""} {timezone :localtime} {locale en}} { if {$year eq ""} { set year [clock format [clock seconds] -format %Y] } puts [format "%40s" "-- $year --"] foreach m {1 4 7 10} { puts "" cal3Month $year $m $timezone $locale } } proc snoopy {} { puts [format "%43s\n" {[Snoopy Picture]}] } snoopy cal
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
Port the provided C code into Rust while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <string.h> int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, { "June", 30, 0, 0 }, { "July", 31, 0, 0 }, { "August", 31, 0, 0 }, { "September", 30, 0, 0 }, { "October", 31, 0, 0 }, { "November", 30, 0, 0 }, { "December", 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf("%s", months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf("%s%s", wdays[i], i == 6 ? "" : " "); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf("%2d", ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, "%d", year); space((width - strlen(buf)) / 2); printf("%s\n\n", buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], "-w")) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], "%d", &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, "bad args\nUsage: %s year [-w width (>= 20)]\n", v[0]); exit(1); }
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
Write the same algorithm in Rust as shown in this C++ implementation.
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
Transform the following C# implementation into Rust, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CalendarStuff { class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console.Read(); } private static string buildMonths(DateTime date) { StringBuilder sb = new StringBuilder(); sb.AppendLine(center("[Snoop]", 24 * 3)); sb.AppendLine(); sb.AppendLine(center(date.Year.ToString(), 24 * 3)); List<DateTime> dts = new List<DateTime>(); while (true) { dts.Add(date); if (date.Year != ((date = date.AddMonths(1)).Year)) { break; } } var jd = dts.Select(a => buildMonth(a).GetEnumerator()).ToArray(); int sCur=0; while (sCur<dts.Count) { sb.AppendLine(); int curMonth=0; var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1 < sCur + 3).ToArray(); sCur += j.Length; bool breakOut = false; while (!breakOut) { int inj = 1; foreach (var cd in j) { if (cd.MoveNext()) { sb.Append((cd.Current.Length == 21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " "); } else { sb.Append("".PadRight(21, ' ') + " "); breakOut = true; } if (inj++ % 3 == 0) sb.AppendLine(); } } } return sb.ToString(); } private static IEnumerable<string> buildMonth(DateTime date) { yield return center(date.ToString("MMMM"),7*3); var j = DateTime.DaysInMonth(date.Year, date.Month); yield return Enum.GetNames(typeof(DayOfWeek)).Aggregate("", (current, result) => current + (result.Substring(0, 2).ToUpper() + " ")); string cur = ""; int total = 0; foreach (var day in Enumerable.Range(-((int)date.DayOfWeek),j + (int)date.DayOfWeek)) { cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day + 1))) +" "; if (total++ > 0 && (total ) % 7 == 0) { yield return cur; cur = ""; } } yield return cur; } private static string center(string s, int len) { return (s.PadLeft((len - s.Length) / 2 + s.Length, ' ').PadRight((len), ' ')); } } }
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
Transform the following Go implementation into Rust, maintaining the same output and logic.
package main import ( "fmt" "time" ) const pageWidth = 80 func main() { printCal(1969) } func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int month, lastMonth time.Month weekInMonth, dayInMonth int ) for thisDate.Year() == year { if month = thisDate.Month(); month != lastMonth { weekInMonth = 0 dayInMonth = 1 } weekday := thisDate.Weekday() if weekday == 0 && dayInMonth > 1 { weekInMonth++ } dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() lastMonth = month dayInMonth++ thisDate = thisDate.Add(time.Hour * 24) } centre := fmt.Sprintf("%d", pageWidth/2) fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") centre = fmt.Sprintf("%d", pageWidth/2-2) fmt.Printf("%"+centre+"d\n\n", year) months := [12]string{ " January ", " February", " March ", " April ", " May ", " June ", " July ", " August ", "September", " October ", " November", " December"} days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} for qtr := 0; qtr < 4; qtr++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { fmt.Printf(" %s ", months[qtr*3+monthInQtr]) } fmt.Println() for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { fmt.Printf(" %s", days[day]) } fmt.Printf(" ") } fmt.Println() for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { for day := 0; day < 7; day++ { if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { fmt.Printf(" ") } else { fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) } } fmt.Printf(" ") } fmt.Println() } fmt.Println() } }
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
Convert the following code from Rust to Python, ensuring the logic remains intact.
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
>>> import calendar >>> help(calendar.prcal) Help on method pryear in module calendar: pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a years calendar. >>> calendar.prcal(1969) 1969 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Port the following code from Java to Rust with equivalent syntax and logic.
import java.text.*; import java.util.*; public class CalendarTask { public static void main(String[] args) { printCalendar(1969, 3); } static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); Calendar date = new GregorianCalendar(year, 0, 1); int nRows = (int) Math.ceil(12.0 / nCols); int offs = date.get(Calendar.DAY_OF_WEEK) - 1; int w = nCols * 24; String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); String[][] mons = new String[12][8]; for (int m = 0; m < 12; m++) { String name = monthNames[m]; int len = 11 + name.length() / 2; String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); mons[m][0] = String.format(format, name, ""); mons[m][1] = " Su Mo Tu We Th Fr Sa"; int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); for (int d = 1; d < 43; d++) { boolean isDay = d > offs && d <= offs + dim; String entry = isDay ? String.format(" %2s", d - offs) : " "; if (d % 7 == 1) mons[m][2 + (d - 1) / 7] = entry; else mons[m][2 + (d - 1) / 7] += entry; } offs = (offs + dim) % 7; date.add(Calendar.MONTH, 1); } System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); for (int r = 0; r < nRows; r++) { for (int i = 0; i < 8; i++) { for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) System.out.printf(" %s", mons[c][i]); System.out.println(); } System.out.println(); } } }
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
Port the following code from Rust to VB with equivalent syntax and logic.
extern crate chrono; use std::{env, cmp}; use chrono::{NaiveDate, Datelike}; const MONTH_WIDTH: usize = 22; fn print_header(months: &[&str]) { const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA "; println!(); for m in months { print!("{:^20} ", m); } println!("\n{}", DAYS_OF_WEEK.repeat(months.len())); } fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> { let start = week_num * 7 - start_day_of_week + 1; let end = (week_num + 1) * 7 - start_day_of_week; let mut ret = String::with_capacity(MONTH_WIDTH); if start > days { None } else { for i in start..(end + 1) { if i <= 0 || i > days { ret.push_str(" "); } else { if i < 10 { ret.push_str(" "); } ret.push_str(&i.to_string()); } ret.push_str(" "); } ret.push_str(" "); Some(ret) } } fn main() { const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]; const DEFAULT_TEXT_WIDTH: usize = 100; let args: Vec<String> = env::args().collect(); let year: i32 = args[1].parse().expect("The first argument must be a year"); let width: usize = if args.len() > 2 { cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width")) } else { DEFAULT_TEXT_WIDTH }; let months_in_row = width / MONTH_WIDTH; let month_rows = if MONTH_NAMES.len() % months_in_row == 0 { MONTH_NAMES.len() / months_in_row } else { MONTH_NAMES.len() / months_in_row + 1 }; let start_days_of_week: Vec<i32> = (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect(); let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() { [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] } else { [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; println!("{year:^w$}", w=width, year=year.to_string()); for i in 0..month_rows { let start = i * months_in_row; let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len()); print_header(&MONTH_NAMES[start..end]); let mut count = 0; let mut row_num = 0; while count < months_in_row { let mut row_str = String::with_capacity(width); for j in start..end { match get_week_str(month_days[j], row_num, start_days_of_week[j]) { None => { count += 1; row_str.push_str(&" ".repeat(MONTH_WIDTH)); }, Some(week_str) => row_str.push_str(&week_str) } } if count < months_in_row { println!("{}", row_str); } row_num += 1; } } }
docal 1969,6,"" function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function sub print(x) wscript.stdout.writeline x : end sub function iif(a,b,c) :if a then iif=b else iif =c end if : end function sub docal (yr,nmonth,sloc) dim ld(6) dim d(6) if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can if sloc<>"" then Setlocale sloc wday="" for i=1 to 7 wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) next ncols=nmonth*21+(nmonth-1)*1 print center("[Snoopy]",ncols) print center(yr,ncols) print string(ncols,"=") for i=1 to 12\nmonth s="": s1="":esp="" for j=1 to nmonth s=s & esp & center(monthname(m+j),21) s1=s1 & esp & wday d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 ld(j)=day(dateserial(yr,m+j+1,0)) esp=" " next print s: print s1 while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))or (d(5)<ld(5)) or (d(6)<ld(6)) s="" for j=1 to nmonth for k=1 to 7 s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3) d(j)=d(j)+1 next s=s&" " next print s wend m=m+nmonth if i<>12\nmonth then print "" next print string(ncols,"=") end sub
Maintain the same structure and functionality when rewriting this code in C#.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Convert the following code from Ada to C#, ensuring the logic remains intact.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Write a version of this Ada function in C with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Write a version of this Ada function in C with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Write the same code in Go as shown below in Ada.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }
Write a version of this Ada function in Go with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }
Produce a language-to-language conversion: from Ada to Java, same semantics.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Translate the given Ada code snippet into Java without altering its behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Rewrite this program in Python while keeping its functionality equivalent to the Ada version.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Ensure the translated Python code behaves exactly like the original Ada snippet.
with Ada.Text_IO; use Ada.Text_IO; procedure DePermute is type U64 is mod 2**64; type Num is range 0 .. 20; type NumList is array (Natural range <>) of Num; type PtNumList is access all NumList; package IO is new Ada.Text_IO.Integer_IO (Num); package UIO is new Ada.Text_IO.Modular_IO (U64); function deranged (depth : Natural; list : PtNumList; show : Boolean) return U64 is tmp : Num; count : U64 := 0; begin if depth = list'Length then if show then for i in list'Range loop IO.Put (list (i), 2); end loop; New_Line; end if; return 1; end if; for i in reverse depth .. list'Last loop if Num (i + 1) /= list (depth) then tmp := list (i); list (i) := list (depth); list (depth) := tmp; count := count + deranged (depth + 1, list, show); tmp := list (i); list (i) := list (depth); list (depth) := tmp; end if; end loop; return count; end deranged; function gen_n (len : Natural; show : Boolean) return U64 is list : PtNumList; begin list := new NumList (0 .. len - 1); for i in list'Range loop list (i) := Num (i + 1); end loop; return deranged (0, list, show); end gen_n; function sub_fact (n : Natural) return U64 is begin if n < 2 then return U64 (1 - n); else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1); end if; end sub_fact; count : U64; begin Put_Line ("Deranged 4:"); count := gen_n (4, True); Put_Line ("List vs. calc:"); for i in Natural range 0 .. 9 loop IO.Put (Num (i), 1); UIO.Put (gen_n (i, False), 7); UIO.Put (sub_fact (i), 7); New_Line; end loop; Put_Line ("!20 = " & U64'Image (sub_fact (20))); end DePermute;
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Ensure the translated C code behaves exactly like the original Arturo snippet.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Rewrite the snippet below in C so it works the same as the original Arturo code.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Port the provided Arturo code into C# while preserving the original functionality.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Write the same code in C# as shown below in Arturo.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Port the provided Arturo code into Java while preserving the original functionality.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Write the same algorithm in Java as shown in this Arturo implementation.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Port the provided Arturo code into Python while preserving the original functionality.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Preserve the algorithm and functionality while converting the code from Arturo to Python.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Write the same code in Go as shown below in Arturo.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }
Generate an equivalent Go version of this Arturo code.
isClean?: function [s,o][ loop.with:'i s 'a [ if a = o\[i] -> return false ] return true ] derangements: function [n][ original: 1..n select permutate original 'x -> isClean? x original ] subfactorial: function [n].memoize[ (n =< 1)? -> 1 - n -> (n-1) * (add subfactorial n-1 subfactorial n-2) ] print "Derangements of 1 2 3 4:" loop derangements 4 'x [ print x ] print "\nNumber of derangements:" print [pad "n" 5 pad "counted" 15 pad "calculated" 15] print repeat "-" 39 loop 0..9 'z [ counted: size derangements z calculated: subfactorial z print [pad to :string z 5 pad to :string counted 15 pad to :string calculated 15] ] print ~"\n!20 = |subfactorial 20|"
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }
Maintain the same structure and functionality when rewriting this code in C.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Port the provided Clojure code into C while preserving the original functionality.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Port the provided Clojure code into C# while preserving the original functionality.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Port the following code from Clojure to C# with equivalent syntax and logic.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Convert this Clojure block to Java, preserving its control flow and logic.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Generate an equivalent Java version of this Clojure code.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Convert this Clojure snippet to Python and keep its semantics consistent.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Maintain the same structure and functionality when rewriting this code in Python.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Ensure the translated Go code behaves exactly like the original Clojure snippet.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }
Ensure the translated Go code behaves exactly like the original Clojure snippet.
(ns derangements.core (:require [clojure.set :as s])) (defn subfactorial [n] (case n 0 1 1 0 (* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2)))))) (defn no-fixed-point "f : A -> B must be a biyective function written as a hash-map, returns all g : A -> B such that (f(a) = b) => not(g(a) = b)" [f] (case (count f) 0 [{}] 1 [] (let [g (s/map-invert f) a (first (keys f)) a' (f a)] (mapcat (fn [b'] (let [b (g b') f' (dissoc f a b)] (concat (map #(reduce conj % [[a b'] [b a']]) (no-fixed-point f')) (map #(conj % [a b']) (no-fixed-point (assoc f' b a')))))) (filter #(not= a' %) (keys g)))))) (defn derangements [xs] {:pre [(= (count xs) (count (set xs)))]} (map (fn [f] (mapv f xs)) (no-fixed-point (into {} (map vector xs xs))))) (defn -main [] (do (doall (map println (derangements [0,1,2,3]))) (doall (map #(println (str (subfactorial %) " " (count (derangements (range %))))) (range 10))) (println (subfactorial 20))))
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }
Convert this D snippet to C and keep its semantics consistent.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Can you help me rewrite this code in C instead of D, keeping it the same logically?
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
#include <stdio.h> typedef unsigned long long LONG; LONG deranged(int depth, int len, int *d, int show) { int i; char tmp; LONG count = 0; if (depth == len) { if (show) { for (i = 0; i < len; i++) putchar(d[i] + 'a'); putchar('\n'); } return 1; } for (i = len - 1; i >= depth; i--) { if (i == d[depth]) continue; tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; count += deranged(depth + 1, len, d, show); tmp = d[i]; d[i] = d[depth]; d[depth] = tmp; } return count; } LONG gen_n(int n, int show) { LONG i; int a[1024]; for (i = 0; i < n; i++) a[i] = i; return deranged(0, n, a, show); } LONG sub_fact(int n) { return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1); } int main() { int i; printf("Deranged Four:\n"); gen_n(4, 1); printf("\nCompare list vs calc:\n"); for (i = 0; i < 10; i++) printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i)); printf("\nfurther calc:\n"); for (i = 10; i <= 20; i++) printf("%d: %llu\n", i, sub_fact(i)); return 0; }
Write the same algorithm in C# as shown in this D implementation.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Change the programming language of this snippet from D to C# without modifying what it does.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
using System; class Derangements { static int n = 4; static int [] buf = new int [n]; static bool [] used = new bool [n]; static void Main() { for (int i = 0; i < n; i++) used [i] = false; rec(0); } static void rec(int ind) { for (int i = 0; i < n; i++) { if (!used [i] && i != ind) { used [i] = true; buf [ind] = i; if (ind + 1 < n) rec(ind + 1); else Console.WriteLine(string.Join(",", buf)); used [i] = false; } } } }
Rewrite the snippet below in Java so it works the same as the original D code.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Change the following D code into Java without altering its purpose.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Derangement { public static void main(String[] args) { System.out.println("derangements for n = 4\n"); for (Object d : (ArrayList)(derangements(4, false)[0])) { System.out.println(Arrays.toString((int[])d)); } System.out.println("\ntable of n vs counted vs calculated derangements\n"); for (int i = 0; i < 10; i++) { int d = ((Integer)derangements(i, true)[1]).intValue(); System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i)); } System.out.printf ("\n!20 = %20d\n", subfact(20L)); } static Object[] derangements(int n, boolean countOnly) { int[] seq = iota(n); int[] ori = Arrays.copyOf(seq, n); long tot = fact(n); List<int[]> all = new ArrayList<int[]>(); int cnt = n == 0 ? 1 : 0; while (--tot > 0) { int j = n - 2; while (seq[j] > seq[j + 1]) { j--; } int k = n - 1; while (seq[j] > seq[k]) { k--; } swap(seq, k, j); int r = n - 1; int s = j + 1; while (r > s) { swap(seq, s, r); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) { j++; } if (j == n) { if (countOnly) { cnt++; } else { all.add(Arrays.copyOf(seq, n)); } } } return new Object[]{all, cnt}; } static long fact(long n) { long result = 1; for (long i = 2; i <= n; i++) { result *= i; } return result; } static long subfact(long n) { if (0 <= n && n <= 2) { return n != 1 ? 1 : 0; } return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } static void swap(int[] arr, int lhs, int rhs) { int tmp = arr[lhs]; arr[lhs] = arr[rhs]; arr[rhs] = tmp; } static int[] iota(int n) { if (n < 0) { throw new IllegalArgumentException("iota cannot accept < 0"); } int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = i; } return r; } }
Produce a functionally identical Python code for the snippet given in D.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Convert this D block to Python, preserving its control flow and logic.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
from itertools import permutations import math def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) ) def subfact(n): if n == 2 or n == 0: return 1 elif n == 1: return 0 elif 1 <= n <=18: return round(math.factorial(n) / math.e) elif n.imag == 0 and n.real == int(n.real) and n > 0: return (n-1) * ( subfact(n - 1) + subfact(n - 2) ) else: raise ValueError() def _iterlen(iter): 'length of an iterator without taking much memory' l = 0 for x in iter: l += 1 return l if __name__ == '__main__': n = 4 print("Derangements of %s" % (tuple(range(n)),)) for d in derangements(n): print(" %s" % (d,)) print("\nTable of n vs counted vs calculated derangements") for n in range(10): print("%2i %-5i %-5i" % (n, _iterlen(derangements(n)), subfact(n))) n = 20 print("\n!%i = %i" % (n, subfact(n)))
Translate the given D code snippet into Go without altering its behavior.
import std.stdio, std.algorithm, std.typecons, std.conv, std.range, std.traits; T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) pure nothrow @safe { size_t[] seq = n.iota.array; auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { seq[s].swap(seq[r]); r--; s++; } j = 0; while (j < n && seq[j] != ori[j]) j++; if (j == n) { if (countOnly) cnt++; else all ~= seq.dup; } } return tuple(all, cnt); } void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; "\nTable of n vs counted vs calculated derangements:".writeln; foreach (immutable i; 0 .. 10) writefln("%s  %-7s%-7s", i, derangements(i, 1)[1], i.subfact); writefln("\n!20 = %s", 20L.subfact); }
package main import ( "fmt" "math/big" ) func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } var recurse func(last int) recurse = func(last int) { if last == 0 { for j, v := range a { if j == v { return } } r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } fmt.Println("\n!20 =", subFact(20)) }