Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following Common_Lisp code into PHP without altering its purpose.
(defun flatten (tr) (cond ((null tr) nil) ((atom tr) (list tr)) (t (append (flatten (first tr)) (flatten (rest tr))))))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write a version of this D function in PHP with identical behavior.
import std.stdio, std.algorithm, std.conv, std.range; struct TreeList(T) { union { TreeList[] arr; T data; } bool isArray = true; static TreeList opCall(A...)(A items) pure nothrow { TreeList result; foreach (i, el; items) static if (is(A[i] == T)) { TreeList item; item.isArray = false; item.data = el; result.arr ~= item; } else result.arr ~= el; return result; } string toString() const pure { return isArray ? arr.text : data.text; } } T[] flatten(T)(in TreeList!T t) pure nothrow { if (t.isArray) return t.arr.map!flatten.join; else return [t.data]; } void main() { alias TreeList!int L; static assert(L.sizeof == 12); auto l = L(L(1), 2, L(L(3,4), 5), L(L(L())), L(L(L(6))),7,8,L()); l.writeln; l.flatten.writeln; }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Change the following D code into PHP without altering its purpose.
import std.stdio, std.algorithm, std.conv, std.range; struct TreeList(T) { union { TreeList[] arr; T data; } bool isArray = true; static TreeList opCall(A...)(A items) pure nothrow { TreeList result; foreach (i, el; items) static if (is(A[i] == T)) { TreeList item; item.isArray = false; item.data = el; result.arr ~= item; } else result.arr ~= el; return result; } string toString() const pure { return isArray ? arr.text : data.text; } } T[] flatten(T)(in TreeList!T t) pure nothrow { if (t.isArray) return t.arr.map!flatten.join; else return [t.data]; } void main() { alias TreeList!int L; static assert(L.sizeof == 12); auto l = L(L(1), 2, L(L(3,4), 5), L(L(L())), L(L(L(6))),7,8,L()); l.writeln; l.flatten.writeln; }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Produce a language-to-language conversion: from Elixir to PHP, same semantics.
defmodule RC do def flatten([]), do: [] def flatten([h|t]), do: flatten(h) ++ flatten(t) def flatten(h), do: [h] end list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] IO.inspect RC.flatten(list) IO.inspect List.flatten(list)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Can you help me rewrite this code in PHP instead of Elixir, keeping it the same logically?
defmodule RC do def flatten([]), do: [] def flatten([h|t]), do: flatten(h) ++ flatten(t) def flatten(h), do: [h] end list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] IO.inspect RC.flatten(list) IO.inspect List.flatten(list)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write a version of this Erlang function in PHP with identical behavior.
flatten([]) -> []; flatten([H|T]) -> flatten(H) ++ flatten(T); flatten(H) -> [H].
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite the snippet below in PHP so it works the same as the original Erlang code.
flatten([]) -> []; flatten([H|T]) -> flatten(H) ++ flatten(T); flatten(H) -> [H].
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Change the following F# code into PHP without altering its purpose.
type 'a ll = | I of 'a | L of 'a ll list let rec flatten = function | [] -> [] | (I x)::y -> x :: (flatten y) | (L x)::y -> List.append (flatten x) (flatten y) printfn "%A" (flatten [L([I(1)]); I(2); L([L([I(3);I(4)]); I(5)]); L([L([L([])])]); L([L([L([I(6)])])]); I(7); I(8); L([])])
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Convert this F# block to PHP, preserving its control flow and logic.
type 'a ll = | I of 'a | L of 'a ll list let rec flatten = function | [] -> [] | (I x)::y -> x :: (flatten y) | (L x)::y -> List.append (flatten x) (flatten y) printfn "%A" (flatten [L([I(1)]); I(2); L([L([I(3);I(4)]); I(5)]); L([L([L([])])]); L([L([L([I(6)])])]); I(7); I(8); L([])])
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Convert this Forth snippet to PHP and keep its semantics consistent.
: then drop ) a:each drop ; : flatten [] >r r> ; [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] dup . cr flatten . cr bye
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Please provide an equivalent version of this Forth code in PHP.
: then drop ) a:each drop ; : flatten [] >r r> ; [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] dup . cr flatten . cr bye
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Change the following Fortran code into PHP without altering its purpose.
module flat implicit none type n integer :: a type(n), dimension(:), pointer :: p => null() logical :: empty = .false. end type contains recursive subroutine del(this) type(n), intent(inout) :: this integer :: i if (associated(this%p)) then do i = 1, size(this%p) call del(this%p(i)) end do end if end subroutine function join(xs) result (r) type(n), dimension(:), target :: xs type(n) :: r integer :: i if (size(xs)>0) then allocate(r%p(size(xs)), source=xs) do i = 1, size(xs) r%p(i) = xs(i) end do else r%empty = .true. end if end function recursive subroutine flatten1(x,r) integer, dimension (:), allocatable, intent(inout) :: r type(n), intent(in) :: x integer, dimension (:), allocatable :: tmp integer :: i if (associated(x%p)) then do i = 1, size(x%p) call flatten1(x%p(i), r) end do elseif (.not. x%empty) then allocate(tmp(size(r)+1)) tmp(1:size(r)) = r tmp(size(r)+1) = x%a call move_alloc(tmp, r) end if end subroutine function flatten(x) result (r) type(n), intent(in) :: x integer, dimension(:), allocatable :: r allocate(r(0)) call flatten1(x,r) end function recursive subroutine show(x) type(n) :: x integer :: i if (x%empty) then write (*, "(a)", advance="no") "[]" elseif (associated(x%p)) then write (*, "(a)", advance="no") "[" do i = 1, size(x%p) call show(x%p(i)) if (i<size(x%p)) then write (*, "(a)", advance="no") ", " end if end do write (*, "(a)", advance="no") "]" else write (*, "(g0)", advance="no") x%a end if end subroutine function fromString(line) result (r) character(len=*) :: line type (n) :: r type (n), dimension(:), allocatable :: buffer, buffer1 integer, dimension(:), allocatable :: stack, stack1 integer :: sp,i0,i,j, a, cur, start character :: c if (.not. allocated(buffer)) then allocate (buffer(5)) end if if (.not. allocated(stack)) then allocate (stack(5)) end if sp = 1; cur = 1; i = 1 do if ( i > len_trim(line) ) exit c = line(i:i) if (c=="[") then if (sp>size(stack)) then allocate(stack1(2*size(stack))) stack1(1:size(stack)) = stack call move_alloc(stack1, stack) end if stack(sp) = cur; sp = sp + 1; i = i+1 elseif (c=="]") then sp = sp - 1; start = stack(sp) r = join(buffer(start:cur-1)) do j = start, cur-1 call del(buffer(j)) end do buffer(start) = r; cur = start+1; i = i+1 elseif (index(" ,",c)>0) then i = i + 1; continue elseif (index("-123456789",c)>0) then i0 = i do if ((i>len_trim(line)).or. & index("1234567890",line(i:i))==0) then read(line(i0:i-1),*) a if (cur>size(buffer)) then allocate(buffer1(2*size(buffer))) buffer1(1:size(buffer)) = buffer call move_alloc(buffer1, buffer) end if buffer(cur) = n(a); cur = cur + 1; exit else i = i+1 end if end do else stop "input corrupted" end if end do end function end module program main use flat type (n) :: x x = fromString("[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]") write(*, "(a)", advance="no") "input  : " call show(x) print * write (*,"(a)", advance="no") "flatten : [" write (*, "(*(i0,:,:', '))", advance="no") flatten(x) print *, "]" end program
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Generate a PHP translation of this Fortran snippet without changing its computational steps.
module flat implicit none type n integer :: a type(n), dimension(:), pointer :: p => null() logical :: empty = .false. end type contains recursive subroutine del(this) type(n), intent(inout) :: this integer :: i if (associated(this%p)) then do i = 1, size(this%p) call del(this%p(i)) end do end if end subroutine function join(xs) result (r) type(n), dimension(:), target :: xs type(n) :: r integer :: i if (size(xs)>0) then allocate(r%p(size(xs)), source=xs) do i = 1, size(xs) r%p(i) = xs(i) end do else r%empty = .true. end if end function recursive subroutine flatten1(x,r) integer, dimension (:), allocatable, intent(inout) :: r type(n), intent(in) :: x integer, dimension (:), allocatable :: tmp integer :: i if (associated(x%p)) then do i = 1, size(x%p) call flatten1(x%p(i), r) end do elseif (.not. x%empty) then allocate(tmp(size(r)+1)) tmp(1:size(r)) = r tmp(size(r)+1) = x%a call move_alloc(tmp, r) end if end subroutine function flatten(x) result (r) type(n), intent(in) :: x integer, dimension(:), allocatable :: r allocate(r(0)) call flatten1(x,r) end function recursive subroutine show(x) type(n) :: x integer :: i if (x%empty) then write (*, "(a)", advance="no") "[]" elseif (associated(x%p)) then write (*, "(a)", advance="no") "[" do i = 1, size(x%p) call show(x%p(i)) if (i<size(x%p)) then write (*, "(a)", advance="no") ", " end if end do write (*, "(a)", advance="no") "]" else write (*, "(g0)", advance="no") x%a end if end subroutine function fromString(line) result (r) character(len=*) :: line type (n) :: r type (n), dimension(:), allocatable :: buffer, buffer1 integer, dimension(:), allocatable :: stack, stack1 integer :: sp,i0,i,j, a, cur, start character :: c if (.not. allocated(buffer)) then allocate (buffer(5)) end if if (.not. allocated(stack)) then allocate (stack(5)) end if sp = 1; cur = 1; i = 1 do if ( i > len_trim(line) ) exit c = line(i:i) if (c=="[") then if (sp>size(stack)) then allocate(stack1(2*size(stack))) stack1(1:size(stack)) = stack call move_alloc(stack1, stack) end if stack(sp) = cur; sp = sp + 1; i = i+1 elseif (c=="]") then sp = sp - 1; start = stack(sp) r = join(buffer(start:cur-1)) do j = start, cur-1 call del(buffer(j)) end do buffer(start) = r; cur = start+1; i = i+1 elseif (index(" ,",c)>0) then i = i + 1; continue elseif (index("-123456789",c)>0) then i0 = i do if ((i>len_trim(line)).or. & index("1234567890",line(i:i))==0) then read(line(i0:i-1),*) a if (cur>size(buffer)) then allocate(buffer1(2*size(buffer))) buffer1(1:size(buffer)) = buffer call move_alloc(buffer1, buffer) end if buffer(cur) = n(a); cur = cur + 1; exit else i = i+1 end if end do else stop "input corrupted" end if end do end function end module program main use flat type (n) :: x x = fromString("[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]") write(*, "(a)", advance="no") "input  : " call show(x) print * write (*,"(a)", advance="no") "flatten : [" write (*, "(*(i0,:,:', '))", advance="no") flatten(x) print *, "]" end program
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Maintain the same structure and functionality when rewriting this code in PHP.
assert [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten() == [1, 2, 3, 4, 5, 6, 7, 8]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Transform the following Groovy implementation into PHP, maintaining the same output and logic.
assert [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten() == [1, 2, 3, 4, 5, 6, 7, 8]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Can you help me rewrite this code in PHP instead of Haskell, keeping it the same logically?
import Graphics.Element exposing (show) type Tree a = Leaf a | Node (List (Tree a)) flatten : Tree a -> List a flatten tree = case tree of Leaf a -> [a] Node list -> List.concatMap flatten list tree : Tree Int tree = Node [ Node [Leaf 1] , Leaf 2 , Node [Node [Leaf 3, Leaf 4], Leaf 5] , Node [Node [Node []]] , Node [Node [Node [Leaf 6]]] , Leaf 7 , Leaf 8 , Node [] ] main = show (flatten tree)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write the same code in PHP as shown below in Haskell.
import Graphics.Element exposing (show) type Tree a = Leaf a | Node (List (Tree a)) flatten : Tree a -> List a flatten tree = case tree of Leaf a -> [a] Node list -> List.concatMap flatten list tree : Tree Int tree = Node [ Node [Leaf 1] , Leaf 2 , Node [Node [Leaf 3, Leaf 4], Leaf 5] , Node [Node [Node []]] , Node [Node [Node [Leaf 6]]] , Leaf 7 , Leaf 8 , Node [] ] main = show (flatten tree)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Transform the following Icon implementation into PHP, maintaining the same output and logic.
link strings procedure sflatten(s) return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',') end
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Produce a language-to-language conversion: from Icon to PHP, same semantics.
link strings procedure sflatten(s) return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',') end
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Convert the following code from J to PHP, ensuring the logic remains intact.
flatten =: [: ; <S:0
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write a version of this J function in PHP with identical behavior.
flatten =: [: ; <S:0
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Convert the following code from Julia to PHP, ensuring the logic remains intact.
isflat(x) = isempty(x) || first(x) === x function flat_mapreduce(arr) mapreduce(vcat, arr, init=[]) do x isflat(x) ? x : flat(x) end end
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Preserve the algorithm and functionality while converting the code from Julia to PHP.
isflat(x) = isempty(x) || first(x) === x function flat_mapreduce(arr) mapreduce(vcat, arr, init=[]) do x isflat(x) ? x : flat(x) end end
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Port the following code from Lua to PHP with equivalent syntax and logic.
function flatten(list) if type(list) ~= "table" then return {list} end local flat_list = {} for _, elem in ipairs(list) do for _, val in ipairs(flatten(elem)) do flat_list[#flat_list + 1] = val end end return flat_list end test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}} print(table.concat(flatten(test_list), ","))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Produce a language-to-language conversion: from Lua to PHP, same semantics.
function flatten(list) if type(list) ~= "table" then return {list} end local flat_list = {} for _, elem in ipairs(list) do for _, val in ipairs(flatten(elem)) do flat_list[#flat_list + 1] = val end end return flat_list end test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}} print(table.concat(flatten(test_list), ","))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Keep all operations the same but rewrite the snippet in PHP.
Flatten[{{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Maintain the same structure and functionality when rewriting this code in PHP.
Flatten[{{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write the same code in PHP as shown below in Nim.
type TreeList[T] = object case isLeaf: bool of true: data: T of false: list: seq[TreeList[T]] proc L[T](list: varargs[TreeList[T]]): TreeList[T] = for x in list: result.list.add x proc N[T](data: T): TreeList[T] = TreeList[T](isLeaf: true, data: data) proc flatten[T](n: TreeList[T]): seq[T] = if n.isLeaf: result = @[n.data] else: for x in n.list: result.add flatten x var x = L(L(N 1), N 2, L(L(N 3, N 4), N 5), L(L(L[int]())), L(L(L(N 6))), N 7, N 8, L[int]()) echo flatten(x)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Port the following code from Nim to PHP with equivalent syntax and logic.
type TreeList[T] = object case isLeaf: bool of true: data: T of false: list: seq[TreeList[T]] proc L[T](list: varargs[TreeList[T]]): TreeList[T] = for x in list: result.list.add x proc N[T](data: T): TreeList[T] = TreeList[T](isLeaf: true, data: data) proc flatten[T](n: TreeList[T]): seq[T] = if n.isLeaf: result = @[n.data] else: for x in n.list: result.add flatten x var x = L(L(N 1), N 2, L(L(N 3, N 4), N 5), L(L(L[int]())), L(L(L(N 6))), N 7, N 8, L[int]()) echo flatten(x)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write a version of this OCaml function in PHP with identical behavior.
# let flatten = List.concat ;; val flatten : 'a list list -> 'a list = <fun> # let li = [[1]; 2; [[3;4]; 5]; [[[]]]; [[[6]]]; 7; 8; []] ;; ^^^ Error: This expression has type int but is here used with type int list # flatten [[1]; [2; 3; 4]; []; [5; 6]; [7]; [8]] ;; - : int list = [1; 2; 3; 4; 5; 6; 7; 8]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite this program in PHP while keeping its functionality equivalent to the OCaml version.
# let flatten = List.concat ;; val flatten : 'a list list -> 'a list = <fun> # let li = [[1]; 2; [[3;4]; 5]; [[[]]]; [[[6]]]; 7; 8; []] ;; ^^^ Error: This expression has type int but is here used with type int list # flatten [[1]; [2; 3; 4]; []; [5; 6]; [7]; [8]] ;; - : int list = [1; 2; 3; 4; 5; 6; 7; 8]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Produce a functionally identical PHP code for the snippet given in Perl.
sub flatten { map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_ } my @lst = ([1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []); print flatten(@lst), "\n";
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Transform the following Perl implementation into PHP, maintaining the same output and logic.
sub flatten { map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_ } my @lst = ([1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []); print flatten(@lst), "\n";
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Maintain the same structure and functionality when rewriting this code in PHP.
function flatten($a) { if($a.Count -gt 1) { $a | foreach{ $(flatten $_)} } else {$a} } $a = @(@(1), 2, @(@(3,4), 5), @(@(@())), @(@(@(6))), 7, 8, @()) "$(flatten $a)"
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite this program in PHP while keeping its functionality equivalent to the PowerShell version.
function flatten($a) { if($a.Count -gt 1) { $a | foreach{ $(flatten $_)} } else {$a} } $a = @(@(1), 2, @(@(3,4), 5), @(@(@())), @(@(@(6))), 7, 8, @()) "$(flatten $a)"
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Translate this program into PHP but keep the logic exactly as in R.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite this program in PHP while keeping its functionality equivalent to the R version.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Keep all operations the same but rewrite the snippet in PHP.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Port the provided Racket code into PHP while preserving the original functionality.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite the snippet below in PHP so it works the same as the original REXX code.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Keep all operations the same but rewrite the snippet in PHP.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite the snippet below in PHP so it works the same as the original Ruby code.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write the same code in PHP as shown below in Ruby.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Generate a PHP translation of this Scala snippet without changing its computational steps.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Translate the given Scala code snippet into PHP without altering its behavior.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Generate a PHP translation of this Swift snippet without changing its computational steps.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Ensure the translated PHP code behaves exactly like the original Swift snippet.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Rewrite the snippet below in PHP so it works the same as the original Tcl code.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Generate a PHP translation of this Tcl snippet without changing its computational steps.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Change the following C code into Rust without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Convert this C++ snippet to Rust and keep its semantics consistent.
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Generate a Rust translation of this C# snippet without changing its computational steps.
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Translate the given Go code snippet into Rust without altering its behavior.
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Rewrite the snippet below in Python so it works the same as the original Rust code.
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Convert this Rust snippet to Python and keep its semantics consistent.
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Translate this program into VB but keep the logic exactly as in Rust.
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Rewrite the snippet below in VB so it works the same as the original Rust code.
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Maintain the same structure and functionality when rewriting this code in Rust.
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Translate the given Java code snippet into Rust without altering its behavior.
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Maintain the same structure and functionality when rewriting this code in Rust.
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Rewrite the snippet below in Rust so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Can you help me rewrite this code in Rust instead of C++, keeping it the same logically?
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Preserve the algorithm and functionality while converting the code from C# to Rust.
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
Convert this Ada block to C#, preserving its control flow and logic.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
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), ' ')); } } }
Please provide an equivalent version of this Ada code in C.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
#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); }
Maintain the same structure and functionality when rewriting this code in C++.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
#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 Ada function in Go with identical behavior.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
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 code in Java as shown below in Ada.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
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(); } } }
Preserve the algorithm and functionality while converting the code from Ada to Python.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
>>> 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
Produce a functionally identical VB code for the snippet given in Ada.
with Ada.Calendar.Formatting; package Printable_Calendar is subtype String20 is String(1 .. 20); type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; type Description is record Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; Default_Description: constant Description := (Weekday_Rep => "Mo Tu We Th Fr Sa So", Month_Rep => (" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")); type Calendar (<>) is tagged private; function Init_80(Des: Description := Default_Description) return Calendar; function Init_132(Des: Description := Default_Description) return Calendar; procedure New_Line(Cal: Calendar); procedure Put_String(Cal: Calendar; S: String); procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); procedure Print(Cal: Calendar'Class; Year: Ada.Calendar.Year_Number; Year_String: String); private type Calendar is tagged record Columns, Rows, Space_Between_Columns: Positive; Left_Space: Natural; Weekday_Rep: String20; Month_Rep: Month_Rep_Type; end record; end Printable_Calendar;
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
Can you help me rewrite this code in C instead of Arturo, keeping it the same logically?
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
#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); }
Transform the following Arturo implementation into C#, maintaining the same output and logic.
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
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 the same code in C++ as shown below in Arturo.
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
#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 this program into Java but keep the logic exactly as in Arturo.
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
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(); } } }
Preserve the algorithm and functionality while converting the code from Arturo to Python.
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
>>> 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
Please provide an equivalent version of this Arturo code in VB.
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
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
Transform the following Arturo implementation into Go, maintaining the same output and logic.
Rebol [] do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to-date rejoin [i"-"m"-"y]][ prin join either 1 = length? form i [" "][" "] i if c/weekday = 7 [print ""] ] ] ] ask "^/^/Press [ENTER] to Continue..."]
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 AutoHotKey code into C while preserving the original functionality.
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
#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); }
Write the same code in C# as shown below in AutoHotKey.
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
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), ' ')); } } }
Ensure the translated C++ code behaves exactly like the original AutoHotKey snippet.
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
#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; }
Can you help me rewrite this code in Java instead of AutoHotKey, keeping it the same logically?
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
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(); } } }
Keep all operations the same but rewrite the snippet in Python.
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
>>> 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 AutoHotKey version.
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
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 AutoHotKey function in Go with identical behavior.
Calendar(Yr){ LastDay := [], Day := [] Titles = (ltrim ______January_________________February_________________March_______ _______April____________________May____________________June________ ________July___________________August_________________September_____ ______October_________________November________________December______ ) StringSplit, title, titles, `n Res := "________________________________" Yr "`r`n" loop 4 { Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" loop , 6 { Week := A_Index, Res .= "`r`n" loop, 21 { Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 FormatTime, WD, % Day[Mon], WDay FormatTime, dd, % Day[Mon], dd if (WD>ThisWD) { Res .= "__ " continue } dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days Res .= ((wd=7) && A_Index < 21) ? "___" : "" FormatTime, dd, % Day[Mon], dd } } Res .= "`r`n" } StringReplace, Res, Res,_,%A_Space%, all Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") return res }
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() } }
Please provide an equivalent version of this AWK code in C.
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk To change the output width, change the value assigned to variable pagewide BEGIN{ wkdays = "Su Mo Tu We Th Fr Sa" pagewide = 80 blank=" " for (i=1; i<pagewide; i++) blank = blank " " month= " January February March April " month= month " May June July August " month= month " September October November December " days =" 312831303130313130313031" line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } function center(text, half) { half = (pagewide - length(text))/2 return substr(blank,1,half) text substr(blank,1,half) } function min(a,b) { if (a < b) return a else return b } function makewk (fst,lst,day, i,wstring ){ wstring="" for (i=1;i<day;i++) wstring=wstring " " for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i) return substr(wstring " ",1,20) } function dow (year, y){ y=year y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7 leap = 0 if (year % 4 == 0) leap = 1 if (year % 100 == 0) leap = 0 if (year % 400 == 0) leap = 1 y = y - leap if (y==-1) y=6 if (y==0) y=7 return (y) } function prmonth (nmonth, newdow,monsize ){ line1 = line1 " " (substr(month,10*nmonth,10)) " " line2 = line2 (wkdays) " " line3 = line3 (makewk(1,8-newdow,newdow)) " " line4 = line4 (makewk(9-newdow,15-newdow,1)) " " line5 = line5 (makewk(16-newdow,22-newdow,1)) " " line6 = line6 (makewk(23-newdow,29-newdow,1)) " " line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " " line8 = line8 (makewk(37-newdow,monsize,1)) " " if (length(line3) + 22 > pagewide) { print center(line1) print center(line2) print center(line3) print center(line4) print center(line5) print center(line6) print center(line7) print center(line8) line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } } /q/{ exit } { monsize=substr(days,2*1,2) newdow=dow($1) print center("[ picture of Snoopy goes here ]") print center(sprintf("%d",$1) ) for (i=1; i<13; i++) { prmonth(i,newdow,monsize) newdow=(monsize+newdow) %7 if (newdow == 0) newdow = 7 monsize=substr(days,2+2*i,2) if (leap == 1 && monsize == 28) monsize = 29 } }
#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 programming language of this snippet from AWK to C# without modifying what it does.
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk To change the output width, change the value assigned to variable pagewide BEGIN{ wkdays = "Su Mo Tu We Th Fr Sa" pagewide = 80 blank=" " for (i=1; i<pagewide; i++) blank = blank " " month= " January February March April " month= month " May June July August " month= month " September October November December " days =" 312831303130313130313031" line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } function center(text, half) { half = (pagewide - length(text))/2 return substr(blank,1,half) text substr(blank,1,half) } function min(a,b) { if (a < b) return a else return b } function makewk (fst,lst,day, i,wstring ){ wstring="" for (i=1;i<day;i++) wstring=wstring " " for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i) return substr(wstring " ",1,20) } function dow (year, y){ y=year y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7 leap = 0 if (year % 4 == 0) leap = 1 if (year % 100 == 0) leap = 0 if (year % 400 == 0) leap = 1 y = y - leap if (y==-1) y=6 if (y==0) y=7 return (y) } function prmonth (nmonth, newdow,monsize ){ line1 = line1 " " (substr(month,10*nmonth,10)) " " line2 = line2 (wkdays) " " line3 = line3 (makewk(1,8-newdow,newdow)) " " line4 = line4 (makewk(9-newdow,15-newdow,1)) " " line5 = line5 (makewk(16-newdow,22-newdow,1)) " " line6 = line6 (makewk(23-newdow,29-newdow,1)) " " line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " " line8 = line8 (makewk(37-newdow,monsize,1)) " " if (length(line3) + 22 > pagewide) { print center(line1) print center(line2) print center(line3) print center(line4) print center(line5) print center(line6) print center(line7) print center(line8) line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } } /q/{ exit } { monsize=substr(days,2*1,2) newdow=dow($1) print center("[ picture of Snoopy goes here ]") print center(sprintf("%d",$1) ) for (i=1; i<13; i++) { prmonth(i,newdow,monsize) newdow=(monsize+newdow) %7 if (newdow == 0) newdow = 7 monsize=substr(days,2+2*i,2) if (leap == 1 && monsize == 28) monsize = 29 } }
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), ' ')); } } }
Keep all operations the same but rewrite the snippet in C++.
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk To change the output width, change the value assigned to variable pagewide BEGIN{ wkdays = "Su Mo Tu We Th Fr Sa" pagewide = 80 blank=" " for (i=1; i<pagewide; i++) blank = blank " " month= " January February March April " month= month " May June July August " month= month " September October November December " days =" 312831303130313130313031" line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } function center(text, half) { half = (pagewide - length(text))/2 return substr(blank,1,half) text substr(blank,1,half) } function min(a,b) { if (a < b) return a else return b } function makewk (fst,lst,day, i,wstring ){ wstring="" for (i=1;i<day;i++) wstring=wstring " " for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i) return substr(wstring " ",1,20) } function dow (year, y){ y=year y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7 leap = 0 if (year % 4 == 0) leap = 1 if (year % 100 == 0) leap = 0 if (year % 400 == 0) leap = 1 y = y - leap if (y==-1) y=6 if (y==0) y=7 return (y) } function prmonth (nmonth, newdow,monsize ){ line1 = line1 " " (substr(month,10*nmonth,10)) " " line2 = line2 (wkdays) " " line3 = line3 (makewk(1,8-newdow,newdow)) " " line4 = line4 (makewk(9-newdow,15-newdow,1)) " " line5 = line5 (makewk(16-newdow,22-newdow,1)) " " line6 = line6 (makewk(23-newdow,29-newdow,1)) " " line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " " line8 = line8 (makewk(37-newdow,monsize,1)) " " if (length(line3) + 22 > pagewide) { print center(line1) print center(line2) print center(line3) print center(line4) print center(line5) print center(line6) print center(line7) print center(line8) line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } } /q/{ exit } { monsize=substr(days,2*1,2) newdow=dow($1) print center("[ picture of Snoopy goes here ]") print center(sprintf("%d",$1) ) for (i=1; i<13; i++) { prmonth(i,newdow,monsize) newdow=(monsize+newdow) %7 if (newdow == 0) newdow = 7 monsize=substr(days,2+2*i,2) if (leap == 1 && monsize == 28) monsize = 29 } }
#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 AWK function in Python with identical behavior.
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk To change the output width, change the value assigned to variable pagewide BEGIN{ wkdays = "Su Mo Tu We Th Fr Sa" pagewide = 80 blank=" " for (i=1; i<pagewide; i++) blank = blank " " month= " January February March April " month= month " May June July August " month= month " September October November December " days =" 312831303130313130313031" line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } function center(text, half) { half = (pagewide - length(text))/2 return substr(blank,1,half) text substr(blank,1,half) } function min(a,b) { if (a < b) return a else return b } function makewk (fst,lst,day, i,wstring ){ wstring="" for (i=1;i<day;i++) wstring=wstring " " for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i) return substr(wstring " ",1,20) } function dow (year, y){ y=year y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7 leap = 0 if (year % 4 == 0) leap = 1 if (year % 100 == 0) leap = 0 if (year % 400 == 0) leap = 1 y = y - leap if (y==-1) y=6 if (y==0) y=7 return (y) } function prmonth (nmonth, newdow,monsize ){ line1 = line1 " " (substr(month,10*nmonth,10)) " " line2 = line2 (wkdays) " " line3 = line3 (makewk(1,8-newdow,newdow)) " " line4 = line4 (makewk(9-newdow,15-newdow,1)) " " line5 = line5 (makewk(16-newdow,22-newdow,1)) " " line6 = line6 (makewk(23-newdow,29-newdow,1)) " " line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " " line8 = line8 (makewk(37-newdow,monsize,1)) " " if (length(line3) + 22 > pagewide) { print center(line1) print center(line2) print center(line3) print center(line4) print center(line5) print center(line6) print center(line7) print center(line8) line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } } /q/{ exit } { monsize=substr(days,2*1,2) newdow=dow($1) print center("[ picture of Snoopy goes here ]") print center(sprintf("%d",$1) ) for (i=1; i<13; i++) { prmonth(i,newdow,monsize) newdow=(monsize+newdow) %7 if (newdow == 0) newdow = 7 monsize=substr(days,2+2*i,2) if (leap == 1 && monsize == 28) monsize = 29 } }
>>> 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 AWK to VB with equivalent syntax and logic.
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk To change the output width, change the value assigned to variable pagewide BEGIN{ wkdays = "Su Mo Tu We Th Fr Sa" pagewide = 80 blank=" " for (i=1; i<pagewide; i++) blank = blank " " month= " January February March April " month= month " May June July August " month= month " September October November December " days =" 312831303130313130313031" line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } function center(text, half) { half = (pagewide - length(text))/2 return substr(blank,1,half) text substr(blank,1,half) } function min(a,b) { if (a < b) return a else return b } function makewk (fst,lst,day, i,wstring ){ wstring="" for (i=1;i<day;i++) wstring=wstring " " for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i) return substr(wstring " ",1,20) } function dow (year, y){ y=year y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7 leap = 0 if (year % 4 == 0) leap = 1 if (year % 100 == 0) leap = 0 if (year % 400 == 0) leap = 1 y = y - leap if (y==-1) y=6 if (y==0) y=7 return (y) } function prmonth (nmonth, newdow,monsize ){ line1 = line1 " " (substr(month,10*nmonth,10)) " " line2 = line2 (wkdays) " " line3 = line3 (makewk(1,8-newdow,newdow)) " " line4 = line4 (makewk(9-newdow,15-newdow,1)) " " line5 = line5 (makewk(16-newdow,22-newdow,1)) " " line6 = line6 (makewk(23-newdow,29-newdow,1)) " " line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " " line8 = line8 (makewk(37-newdow,monsize,1)) " " if (length(line3) + 22 > pagewide) { print center(line1) print center(line2) print center(line3) print center(line4) print center(line5) print center(line6) print center(line7) print center(line8) line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } } /q/{ exit } { monsize=substr(days,2*1,2) newdow=dow($1) print center("[ picture of Snoopy goes here ]") print center(sprintf("%d",$1) ) for (i=1; i<13; i++) { prmonth(i,newdow,monsize) newdow=(monsize+newdow) %7 if (newdow == 0) newdow = 7 monsize=substr(days,2+2*i,2) if (leap == 1 && monsize == 28) monsize = 29 } }
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
Translate the given AWK code snippet into Go without altering its behavior.
Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk To change the output width, change the value assigned to variable pagewide BEGIN{ wkdays = "Su Mo Tu We Th Fr Sa" pagewide = 80 blank=" " for (i=1; i<pagewide; i++) blank = blank " " month= " January February March April " month= month " May June July August " month= month " September October November December " days =" 312831303130313130313031" line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } function center(text, half) { half = (pagewide - length(text))/2 return substr(blank,1,half) text substr(blank,1,half) } function min(a,b) { if (a < b) return a else return b } function makewk (fst,lst,day, i,wstring ){ wstring="" for (i=1;i<day;i++) wstring=wstring " " for (i=fst;i<=lst;i++) wstring=wstring sprintf("%2d ",i) return substr(wstring " ",1,20) } function dow (year, y){ y=year y= (y*365+int(y/4) - int(y/100) + int(y/400) +1) %7 leap = 0 if (year % 4 == 0) leap = 1 if (year % 100 == 0) leap = 0 if (year % 400 == 0) leap = 1 y = y - leap if (y==-1) y=6 if (y==0) y=7 return (y) } function prmonth (nmonth, newdow,monsize ){ line1 = line1 " " (substr(month,10*nmonth,10)) " " line2 = line2 (wkdays) " " line3 = line3 (makewk(1,8-newdow,newdow)) " " line4 = line4 (makewk(9-newdow,15-newdow,1)) " " line5 = line5 (makewk(16-newdow,22-newdow,1)) " " line6 = line6 (makewk(23-newdow,29-newdow,1)) " " line7 = line7 (makewk(30-newdow,min(monsize,36-newdow),1)) " " line8 = line8 (makewk(37-newdow,monsize,1)) " " if (length(line3) + 22 > pagewide) { print center(line1) print center(line2) print center(line3) print center(line4) print center(line5) print center(line6) print center(line7) print center(line8) line1 = "" line2 = "" line3 = "" line4 = "" line5 = "" line6 = "" line7 = "" line8 = "" } } /q/{ exit } { monsize=substr(days,2*1,2) newdow=dow($1) print center("[ picture of Snoopy goes here ]") print center(sprintf("%d",$1) ) for (i=1; i<13; i++) { prmonth(i,newdow,monsize) newdow=(monsize+newdow) %7 if (newdow == 0) newdow = 7 monsize=substr(days,2+2*i,2) if (leap == 1 && monsize == 28) monsize = 29 } }
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 BBC_Basic.
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
#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 BBC_Basic code into C# without altering its purpose.
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
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 the given BBC_Basic code snippet into C++ without altering its behavior.
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
#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 the snippet below in Java so it works the same as the original BBC_Basic code.
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
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 BBC_Basic, keeping it the same logically?
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
>>> 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 this BBC_Basic block to VB, preserving its control flow and logic.
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
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 BBC_Basic snippet.
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128 year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2) FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT FOR month% = 1 TO 10 STEP 3 PRINT FOR col% = 0 TO 2 mjd%(col%) = FN_mjd(1, month% + col%, year%) month$ = FN_date$(mjd%(col%), "MMMM") PRINT TAB(col%*24 + 16 - LEN(month$)/2) month$; NEXT FOR col% = 0 TO 2 PRINT TAB(col%*24 + 6) days$; dim%(col%) = FN_dim(month% + col%, year%) NEXT dom%() = 1 col% = 0 REPEAT dow% = FN_dow(mjd%(col%)) IF dom%(col%)<=dim%(col%) THEN PRINT TAB(col%*24 + dow%*3 + 6); dom%(col%); dom%(col%) += 1 mjd%(col%) += 1 ENDIF IF dow%=6 OR dom%(col%)>dim%(col%) col% = (col% + 1) MOD 3 UNTIL dom%(0)>dim%(0) AND dom%(1)>dim%(1) AND dom%(2)>dim%(2) PRINT NEXT
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 Clojure to C, same semantics.
(require '[clojure.string :only [join] :refer [join]]) (def day-row "Su Mo Tu We Th Fr Sa") (def col-width (count day-row)) (defn month-to-word "Translate a month from 0 to 11 into its word representation." [month] ((vec (.getMonths (new java.text.DateFormatSymbols))) month)) (defn month [date] (.get date (java.util.Calendar/MONTH))) (defn total-days-in-month [date] (.getActualMaximum date (java.util.Calendar/DAY_OF_MONTH))) (defn first-weekday [date] (.get date (java.util.Calendar/DAY_OF_WEEK))) (defn normal-date-string "Returns a formatted list of strings of the days of the month." [date] (map #(join " " %) (partition 7 (concat (repeat (dec (first-weekday date)) " ") (map #(format "%2s" %) (range 1 (inc (total-days-in-month date)))) (repeat (- 42 (total-days-in-month date) (dec (first-weekday date)) ) " "))))) (defn oct-1582-string "Returns a formatted list of strings of the days of the month of October 1582." [date] (map #(join " " %) (partition 7 (concat (repeat (dec (first-weekday date)) " ") (map #(format "%2s" %) (concat (range 1 5) (range 15 (inc (total-days-in-month date))))) (repeat (- 42 (count (concat (range 1 5) (range 15 (inc (total-days-in-month date))))) (dec (first-weekday date)) ) " "))))) (defn center-string "Returns a string that is WIDTH long with STRING centered in it." [string width] (let [pad (- width (count string)) lpad (quot pad 2) rpad (- pad (quot pad 2))] (if (<= pad 0) string (str (apply str (repeat lpad " ")) string (apply str (repeat rpad " ")))))) (defn calc-columns "Calculates the number of columns given the width in CHARACTERS and the MARGIN SIZE." [characters margin-size] (loop [cols 0 excess characters ] (if (>= excess col-width) (recur (inc cols) (- excess (+ margin-size col-width))) cols))) (defn month-vector "Returns a vector with the month name, day-row and days formatted for printing." [date] (vec (concat (vector (center-string (month-to-word (month date)) col-width)) (vector day-row) (if (and (= 1582 (.get date (java.util.Calendar/YEAR))) (= 9 (month date))) (oct-1582-string date) (normal-date-string date))))) (defn year-vector [date] "Returns a 2d vector of all the months in the year of DATE." (loop [m [] c (month date)] (if (= c 11 ) (conj m (month-vector date)) (recur (conj m (month-vector date)) (do (.add date (java.util.Calendar/MONTH ) 1) (month date)))))) (defn print-months "Prints the months to standard output with NCOLS and MARGIN." [ v ncols margin] (doseq [r (range (Math/ceil (/ 12 ncols)))] (do (doseq [i (range 8)] (do (doseq [c (range (* r ncols) (* (+ r 1) ncols)) :while (< c 12)] (printf (str (apply str (repeat margin " ")) "%s") (get-in v [c i]))) (println))) (println)))) (defn print-cal "(print-cal [year [width [margin]]]) Prints out the calendar for a given YEAR with WIDTH characters wide and with MARGIN spaces between months." ([] (print-cal 1969 80 2)) ([year] (print-cal year 80 2)) ([year width] (print-cal year width 2)) ([year width margin] (assert (>= width (count day-row)) "Width should be more than 20.") (assert (> margin 0) "Margin needs to be more than 0.") (let [date (new java.util.GregorianCalendar year 0 1) column-count (calc-columns width margin) total-size (+ (* column-count (count day-row)) (* (dec column-count) margin))] (println (center-string "[Snoopy Picture]" total-size)) (println (center-string (str year) total-size)) (println) (print-months (year-vector date) column-count margin))))
#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 Clojure to C#.
(require '[clojure.string :only [join] :refer [join]]) (def day-row "Su Mo Tu We Th Fr Sa") (def col-width (count day-row)) (defn month-to-word "Translate a month from 0 to 11 into its word representation." [month] ((vec (.getMonths (new java.text.DateFormatSymbols))) month)) (defn month [date] (.get date (java.util.Calendar/MONTH))) (defn total-days-in-month [date] (.getActualMaximum date (java.util.Calendar/DAY_OF_MONTH))) (defn first-weekday [date] (.get date (java.util.Calendar/DAY_OF_WEEK))) (defn normal-date-string "Returns a formatted list of strings of the days of the month." [date] (map #(join " " %) (partition 7 (concat (repeat (dec (first-weekday date)) " ") (map #(format "%2s" %) (range 1 (inc (total-days-in-month date)))) (repeat (- 42 (total-days-in-month date) (dec (first-weekday date)) ) " "))))) (defn oct-1582-string "Returns a formatted list of strings of the days of the month of October 1582." [date] (map #(join " " %) (partition 7 (concat (repeat (dec (first-weekday date)) " ") (map #(format "%2s" %) (concat (range 1 5) (range 15 (inc (total-days-in-month date))))) (repeat (- 42 (count (concat (range 1 5) (range 15 (inc (total-days-in-month date))))) (dec (first-weekday date)) ) " "))))) (defn center-string "Returns a string that is WIDTH long with STRING centered in it." [string width] (let [pad (- width (count string)) lpad (quot pad 2) rpad (- pad (quot pad 2))] (if (<= pad 0) string (str (apply str (repeat lpad " ")) string (apply str (repeat rpad " ")))))) (defn calc-columns "Calculates the number of columns given the width in CHARACTERS and the MARGIN SIZE." [characters margin-size] (loop [cols 0 excess characters ] (if (>= excess col-width) (recur (inc cols) (- excess (+ margin-size col-width))) cols))) (defn month-vector "Returns a vector with the month name, day-row and days formatted for printing." [date] (vec (concat (vector (center-string (month-to-word (month date)) col-width)) (vector day-row) (if (and (= 1582 (.get date (java.util.Calendar/YEAR))) (= 9 (month date))) (oct-1582-string date) (normal-date-string date))))) (defn year-vector [date] "Returns a 2d vector of all the months in the year of DATE." (loop [m [] c (month date)] (if (= c 11 ) (conj m (month-vector date)) (recur (conj m (month-vector date)) (do (.add date (java.util.Calendar/MONTH ) 1) (month date)))))) (defn print-months "Prints the months to standard output with NCOLS and MARGIN." [ v ncols margin] (doseq [r (range (Math/ceil (/ 12 ncols)))] (do (doseq [i (range 8)] (do (doseq [c (range (* r ncols) (* (+ r 1) ncols)) :while (< c 12)] (printf (str (apply str (repeat margin " ")) "%s") (get-in v [c i]))) (println))) (println)))) (defn print-cal "(print-cal [year [width [margin]]]) Prints out the calendar for a given YEAR with WIDTH characters wide and with MARGIN spaces between months." ([] (print-cal 1969 80 2)) ([year] (print-cal year 80 2)) ([year width] (print-cal year width 2)) ([year width margin] (assert (>= width (count day-row)) "Width should be more than 20.") (assert (> margin 0) "Margin needs to be more than 0.") (let [date (new java.util.GregorianCalendar year 0 1) column-count (calc-columns width margin) total-size (+ (* column-count (count day-row)) (* (dec column-count) margin))] (println (center-string "[Snoopy Picture]" total-size)) (println (center-string (str year) total-size)) (println) (print-months (year-vector date) column-count margin))))
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), ' ')); } } }
Please provide an equivalent version of this Clojure code in C++.
(require '[clojure.string :only [join] :refer [join]]) (def day-row "Su Mo Tu We Th Fr Sa") (def col-width (count day-row)) (defn month-to-word "Translate a month from 0 to 11 into its word representation." [month] ((vec (.getMonths (new java.text.DateFormatSymbols))) month)) (defn month [date] (.get date (java.util.Calendar/MONTH))) (defn total-days-in-month [date] (.getActualMaximum date (java.util.Calendar/DAY_OF_MONTH))) (defn first-weekday [date] (.get date (java.util.Calendar/DAY_OF_WEEK))) (defn normal-date-string "Returns a formatted list of strings of the days of the month." [date] (map #(join " " %) (partition 7 (concat (repeat (dec (first-weekday date)) " ") (map #(format "%2s" %) (range 1 (inc (total-days-in-month date)))) (repeat (- 42 (total-days-in-month date) (dec (first-weekday date)) ) " "))))) (defn oct-1582-string "Returns a formatted list of strings of the days of the month of October 1582." [date] (map #(join " " %) (partition 7 (concat (repeat (dec (first-weekday date)) " ") (map #(format "%2s" %) (concat (range 1 5) (range 15 (inc (total-days-in-month date))))) (repeat (- 42 (count (concat (range 1 5) (range 15 (inc (total-days-in-month date))))) (dec (first-weekday date)) ) " "))))) (defn center-string "Returns a string that is WIDTH long with STRING centered in it." [string width] (let [pad (- width (count string)) lpad (quot pad 2) rpad (- pad (quot pad 2))] (if (<= pad 0) string (str (apply str (repeat lpad " ")) string (apply str (repeat rpad " ")))))) (defn calc-columns "Calculates the number of columns given the width in CHARACTERS and the MARGIN SIZE." [characters margin-size] (loop [cols 0 excess characters ] (if (>= excess col-width) (recur (inc cols) (- excess (+ margin-size col-width))) cols))) (defn month-vector "Returns a vector with the month name, day-row and days formatted for printing." [date] (vec (concat (vector (center-string (month-to-word (month date)) col-width)) (vector day-row) (if (and (= 1582 (.get date (java.util.Calendar/YEAR))) (= 9 (month date))) (oct-1582-string date) (normal-date-string date))))) (defn year-vector [date] "Returns a 2d vector of all the months in the year of DATE." (loop [m [] c (month date)] (if (= c 11 ) (conj m (month-vector date)) (recur (conj m (month-vector date)) (do (.add date (java.util.Calendar/MONTH ) 1) (month date)))))) (defn print-months "Prints the months to standard output with NCOLS and MARGIN." [ v ncols margin] (doseq [r (range (Math/ceil (/ 12 ncols)))] (do (doseq [i (range 8)] (do (doseq [c (range (* r ncols) (* (+ r 1) ncols)) :while (< c 12)] (printf (str (apply str (repeat margin " ")) "%s") (get-in v [c i]))) (println))) (println)))) (defn print-cal "(print-cal [year [width [margin]]]) Prints out the calendar for a given YEAR with WIDTH characters wide and with MARGIN spaces between months." ([] (print-cal 1969 80 2)) ([year] (print-cal year 80 2)) ([year width] (print-cal year width 2)) ([year width margin] (assert (>= width (count day-row)) "Width should be more than 20.") (assert (> margin 0) "Margin needs to be more than 0.") (let [date (new java.util.GregorianCalendar year 0 1) column-count (calc-columns width margin) total-size (+ (* column-count (count day-row)) (* (dec column-count) margin))] (println (center-string "[Snoopy Picture]" total-size)) (println (center-string (str year) total-size)) (println) (print-months (year-vector date) column-count margin))))
#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; }