Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a functionally identical PHP code for the snippet given in Julia. | using Printf
function findsolution(rng=1:7)
rst = Matrix{Int}(0, 3)
for p in rng, f in rng, s in rng
if p != s != f != p && p + s + f == 12 && iseven(p)
rst = [rst; p s f]
end
end
return rst
end
function printsolutions(sol::Matrix{Int})
println(" Pol. Fire San.")
println(" ---- ---- ----")
for row in 1:size(sol, 1)
@printf("%2i | %4i%7i%7i\n", row, sol[row, :]...)
end
end
printsolutions(findsolution())
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Translate the given Lua code snippet into PHP without altering its behavior. | print( "Fire", "Police", "Sanitation" )
sol = 0
for f = 1, 7 do
for p = 1, 7 do
for s = 1, 7 do
if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then
print( f, p, s ); sol = sol + 1
end
end
end
end
print( string.format( "\n%d solutions found", sol ) )
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Write a version of this Lua function in PHP with identical behavior. | print( "Fire", "Police", "Sanitation" )
sol = 0
for f = 1, 7 do
for p = 1, 7 do
for s = 1, 7 do
if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then
print( f, p, s ); sol = sol + 1
end
end
end
end
print( string.format( "\n%d solutions found", sol ) )
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Change the following Mathematica code into PHP without altering its purpose. | Select[Permutations[Range[7], {3}], Total[#] == 12 && EvenQ[First[#]] &]
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Ensure the translated PHP code behaves exactly like the original Mathematica snippet. | Select[Permutations[Range[7], {3}], Total[#] == 12 && EvenQ[First[#]] &]
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Port the provided Nim code into PHP while preserving the original functionality. | type Solution = tuple[p, s, f: int]
iterator solutions(max, total: Positive): Solution =
for p in countup(2, max, 2):
for s in 1..max:
if s == p: continue
let f = total - p - s
if f notin [p, s] and f in 1..max:
yield (p, s, f)
echo "P S F"
for sol in solutions(7, 12):
echo sol.p, " ", sol.s, " ", sol.f
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Convert this Nim block to PHP, preserving its control flow and logic. | type Solution = tuple[p, s, f: int]
iterator solutions(max, total: Positive): Solution =
for p in countup(2, max, 2):
for s in 1..max:
if s == p: continue
let f = total - p - s
if f notin [p, s] and f in 1..max:
yield (p, s, f)
echo "P S F"
for sol in solutions(7, 12):
echo sol.p, " ", sol.s, " ", sol.f
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Can you help me rewrite this code in PHP instead of OCaml, keeping it the same logically? |
type sfp = {s : int; f : int; p : int}
let print_sfp e =
Printf.printf "%d %d %d\n" e.s e.f e.p
let print_sfp_list l =
l |> List.iter print_sfp
let sum l = List.fold_left (+) 0 l
let element_in_list e l =
l |> List.find_map (fun x -> if x == e then Some(e) else None) <> None
let uniq l =
let rec uniq_helper acc l =
match l with
| [] -> acc
| h::t -> if element_in_list h t then uniq_helper acc t else uniq_helper (h::acc) t in
uniq_helper [] l |> List.rev
let is_uniq l = uniq l = l
let department_numbers sl fl pl =
sl |> List.fold_left (fun aa s ->
fl |> List.fold_left (fun fa f ->
pl |> List.fold_left (fun pa p ->
if
sum [s;f;p] == 12 &&
is_uniq [s;f;p] then
{s = s; f = f; p = p} :: pa
else
pa) []
|> List.append fa) []
|> List.append aa) []
let _ =
let s = [1;2;3;4;5;6;7] in
let f = [1;2;3;4;5;6;7] in
let p = [2;4;6] in
let result = department_numbers s f p in
print_endline "S F P";
print_sfp_list result;
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Change the programming language of this snippet from OCaml to PHP without modifying what it does. |
type sfp = {s : int; f : int; p : int}
let print_sfp e =
Printf.printf "%d %d %d\n" e.s e.f e.p
let print_sfp_list l =
l |> List.iter print_sfp
let sum l = List.fold_left (+) 0 l
let element_in_list e l =
l |> List.find_map (fun x -> if x == e then Some(e) else None) <> None
let uniq l =
let rec uniq_helper acc l =
match l with
| [] -> acc
| h::t -> if element_in_list h t then uniq_helper acc t else uniq_helper (h::acc) t in
uniq_helper [] l |> List.rev
let is_uniq l = uniq l = l
let department_numbers sl fl pl =
sl |> List.fold_left (fun aa s ->
fl |> List.fold_left (fun fa f ->
pl |> List.fold_left (fun pa p ->
if
sum [s;f;p] == 12 &&
is_uniq [s;f;p] then
{s = s; f = f; p = p} :: pa
else
pa) []
|> List.append fa) []
|> List.append aa) []
let _ =
let s = [1;2;3;4;5;6;7] in
let f = [1;2;3;4;5;6;7] in
let p = [2;4;6] in
let result = department_numbers s f p in
print_endline "S F P";
print_sfp_list result;
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Convert this Perl block to PHP, preserving its control flow and logic. |
my @even_numbers;
for (1..7)
{
if ( $_ % 2 == 0)
{
push @even_numbers, $_;
}
}
print "Police\tFire\tSanitation\n";
foreach my $police_number (@even_numbers)
{
for my $fire_number (1..7)
{
for my $sanitation_number (1..7)
{
if ( $police_number + $fire_number + $sanitation_number == 12 &&
$police_number != $fire_number &&
$fire_number != $sanitation_number &&
$sanitation_number != $police_number)
{
print "$police_number\t$fire_number\t$sanitation_number\n";
}
}
}
}
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Convert this Perl block to PHP, preserving its control flow and logic. |
my @even_numbers;
for (1..7)
{
if ( $_ % 2 == 0)
{
push @even_numbers, $_;
}
}
print "Police\tFire\tSanitation\n";
foreach my $police_number (@even_numbers)
{
for my $fire_number (1..7)
{
for my $sanitation_number (1..7)
{
if ( $police_number + $fire_number + $sanitation_number == 12 &&
$police_number != $fire_number &&
$fire_number != $sanitation_number &&
$sanitation_number != $police_number)
{
print "$police_number\t$fire_number\t$sanitation_number\n";
}
}
}
}
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Convert this Racket block to PHP, preserving its control flow and logic. | #lang racket
(cons '(police fire sanitation)
(filter (Ξ» (pfs) (and (not (check-duplicates pfs))
(= 12 (apply + pfs))
pfs))
(cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Change the programming language of this snippet from Racket to PHP without modifying what it does. | #lang racket
(cons '(police fire sanitation)
(filter (Ξ» (pfs) (and (not (check-duplicates pfs))
(= 12 (apply + pfs))
pfs))
(cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Maintain the same structure and functionality when rewriting this code in PHP. | IDENTIFICATION DIVISION.
PROGRAM-ID. DEPARTMENT-NUMBERS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE".
01 COMBINATION.
03 FILLER PIC X(5) VALUE SPACES.
03 POLICE PIC 9.
03 FILLER PIC X(11) VALUE SPACES.
03 SANITATION PIC 9.
03 FILLER PIC X(5) VALUE SPACES.
03 FIRE PIC 9.
01 TOTAL PIC 99.
PROCEDURE DIVISION.
BEGIN.
DISPLAY BANNER.
PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2
UNTIL POLICE IS GREATER THAN 6.
STOP RUN.
POLICE-LOOP.
PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1
UNTIL SANITATION IS GREATER THAN 7.
SANITATION-LOOP.
PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1
UNTIL FIRE IS GREATER THAN 7.
FIRE-LOOP.
ADD POLICE, SANITATION, FIRE GIVING TOTAL.
IF POLICE IS NOT EQUAL TO SANITATION
AND POLICE IS NOT EQUAL TO FIRE
AND SANITATION IS NOT EQUAL TO FIRE
AND TOTAL IS EQUAL TO 12,
DISPLAY COMBINATION.
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Change the following COBOL code into PHP without altering its purpose. | IDENTIFICATION DIVISION.
PROGRAM-ID. DEPARTMENT-NUMBERS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE".
01 COMBINATION.
03 FILLER PIC X(5) VALUE SPACES.
03 POLICE PIC 9.
03 FILLER PIC X(11) VALUE SPACES.
03 SANITATION PIC 9.
03 FILLER PIC X(5) VALUE SPACES.
03 FIRE PIC 9.
01 TOTAL PIC 99.
PROCEDURE DIVISION.
BEGIN.
DISPLAY BANNER.
PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2
UNTIL POLICE IS GREATER THAN 6.
STOP RUN.
POLICE-LOOP.
PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1
UNTIL SANITATION IS GREATER THAN 7.
SANITATION-LOOP.
PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1
UNTIL FIRE IS GREATER THAN 7.
FIRE-LOOP.
ADD POLICE, SANITATION, FIRE GIVING TOTAL.
IF POLICE IS NOT EQUAL TO SANITATION
AND POLICE IS NOT EQUAL TO FIRE
AND SANITATION IS NOT EQUAL TO FIRE
AND TOTAL IS EQUAL TO 12,
DISPLAY COMBINATION.
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Convert this REXX snippet to PHP and keep its semantics consistent. |
say 'police sanitation fire'
say 'ββββββ ββββββββββ ββββ'
#=0
do p=1 for 7; if p//2 then iterate
do s=1 for 7; if s==p then iterate
do f=1 for 7; if f==s then iterate
if p + s + f \== 12 then iterate
#= # + 1
say center(p,6) center(s,10) center(f,4)
end
end
end
say 'ββββββ ββββββββββ ββββ'
say
say # ' solutions found.'
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Generate an equivalent PHP version of this REXX code. |
say 'police sanitation fire'
say 'ββββββ ββββββββββ ββββ'
#=0
do p=1 for 7; if p//2 then iterate
do s=1 for 7; if s==p then iterate
do f=1 for 7; if f==s then iterate
if p + s + f \== 12 then iterate
#= # + 1
say center(p,6) center(s,10) center(f,4)
end
end
end
say 'ββββββ ββββββββββ ββββ'
say
say # ' solutions found.'
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Maintain the same structure and functionality when rewriting this code in PHP. | (1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Port the following code from Ruby to PHP with equivalent syntax and logic. | (1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Write the same algorithm in PHP as shown in this Scala implementation. |
fun main(args: Array<String>) {
println("Police Sanitation Fire")
println("------ ---------- ----")
var count = 0
for (i in 2..6 step 2) {
for (j in 1..7) {
if (j == i) continue
for (k in 1..7) {
if (k == i || k == j) continue
if (i + j + k != 12) continue
println(" $i $j $k")
count++
}
}
}
println("\n$count valid combinations")
}
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Please provide an equivalent version of this Scala code in PHP. |
fun main(args: Array<String>) {
println("Police Sanitation Fire")
println("------ ---------- ----")
var count = 0
for (i in 2..6 step 2) {
for (j in 1..7) {
if (j == i) continue
for (k in 1..7) {
if (k == i || k == j) continue
if (i + j + k != 12) continue
println(" $i $j $k")
count++
}
}
}
println("\n$count valid combinations")
}
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Convert this Swift snippet to PHP and keep its semantics consistent. | let res = [2, 4, 6].map({x in
return (1...7)
.filter({ $0 != x })
.map({y -> (Int, Int, Int)? in
let z = 12 - (x + y)
guard y != z && 1 <= z && z <= 7 else {
return nil
}
return (x, y, z)
}).compactMap({ $0 })
}).flatMap({ $0 })
for result in res {
print(result)
}
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Port the provided Swift code into PHP while preserving the original functionality. | let res = [2, 4, 6].map({x in
return (1...7)
.filter({ $0 != x })
.map({y -> (Int, Int, Int)? in
let z = 12 - (x + y)
guard y != z && 1 <= z && z <= 7 else {
return nil
}
return (x, y, z)
}).compactMap({ $0 })
}).flatMap({ $0 })
for result in res {
print(result)
}
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Rewrite the snippet below in PHP so it works the same as the original Tcl code. |
proc .. max {
for {set i 1} {$i <= $max} {incr i} {
lappend l $i
}
return $l
}
proc anyEqual l {
if {[llength [lsort -unique $l]] != [llength $l]} {
return 1
}
return 0
}
proc odd n {
expr $n %2 != 0
}
proc sum args {
expr [join $args +]
}
set sanitation [.. 7]
set fire $sanitation
set police [lmap e $sanitation {
if [odd $e] continue
set e
}]
set valid 0
foreach p $police {
foreach s $sanitation {
foreach f $fire {
if [anyEqual [list $p $s $f]] continue
if {[sum $p $s $f] != 12} continue
puts "$p $s $f"
incr valid
}
}
}
puts "$valid valid combinations found."
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Can you help me rewrite this code in PHP instead of Tcl, keeping it the same logically? |
proc .. max {
for {set i 1} {$i <= $max} {incr i} {
lappend l $i
}
return $l
}
proc anyEqual l {
if {[llength [lsort -unique $l]] != [llength $l]} {
return 1
}
return 0
}
proc odd n {
expr $n %2 != 0
}
proc sum args {
expr [join $args +]
}
set sanitation [.. 7]
set fire $sanitation
set police [lmap e $sanitation {
if [odd $e] continue
set e
}]
set valid 0
foreach p $police {
foreach s $sanitation {
foreach f $fire {
if [anyEqual [list $p $s $f]] continue
if {[sum $p $s $f] != 12} continue
puts "$p $s $f"
incr valid
}
}
}
puts "$valid valid combinations found."
| <?php
$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
$fire = 12 - $police - $sanitation;
if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
$valid++;
}
}
}
echo $valid, ' valid combinations found.', PHP_EOL;
|
Change the following C code into Rust without altering its purpose. | #include<stdio.h>
int main()
{
int police,sanitation,fire;
printf("Police Sanitation Fire\n");
printf("----------------------------------");
for(police=2;police<=6;police+=2){
for(sanitation=1;sanitation<=7;sanitation++){
for(fire=1;fire<=7;fire++){
if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){
printf("\n%d\t\t%d\t\t%d",police,sanitation,fire);
}
}
}
}
return 0;
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Port the following code from C++ to Rust with equivalent syntax and logic. | #include <iostream>
#include <iomanip>
int main( int argc, char* argv[] ) {
int sol = 1;
std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n";
for( int f = 1; f < 8; f++ ) {
for( int p = 1; p < 8; p++ ) {
for( int s = 1; s < 8; s++ ) {
if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {
std::cout << "SOLUTION #" << std::setw( 2 ) << sol++ << std::setw( 2 )
<< ":\t" << std::setw( 2 ) << f << "\t\t " << std::setw( 3 ) << p
<< "\t\t" << std::setw( 6 ) << s << "\n";
}
}
}
}
return 0;
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Write the same algorithm in Rust as shown in this C++ implementation. | #include <iostream>
#include <iomanip>
int main( int argc, char* argv[] ) {
int sol = 1;
std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n";
for( int f = 1; f < 8; f++ ) {
for( int p = 1; p < 8; p++ ) {
for( int s = 1; s < 8; s++ ) {
if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {
std::cout << "SOLUTION #" << std::setw( 2 ) << sol++ << std::setw( 2 )
<< ":\t" << std::setw( 2 ) << f << "\t\t " << std::setw( 3 ) << p
<< "\t\t" << std::setw( 6 ) << s << "\n";
}
}
}
}
return 0;
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Produce a language-to-language conversion: from C# to Rust, same semantics. | using System;
public class Program
{
public static void Main() {
for (int p = 2; p <= 7; p+=2) {
for (int s = 1; s <= 7; s++) {
int f = 12 - p - s;
if (s >= f) break;
if (f > 7) continue;
if (s == p || f == p) continue;
Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}");
Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}");
}
}
}
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Please provide an equivalent version of this C# code in Rust. | using System;
public class Program
{
public static void Main() {
for (int p = 2; p <= 7; p+=2) {
for (int s = 1; s <= 7; s++) {
int f = 12 - p - s;
if (s >= f) break;
if (f > 7) continue;
if (s == p || f == p) continue;
Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}");
Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}");
}
}
}
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to Rust. | public class DepartmentNumbers {
public static void main(String[] args) {
System.out.println("Police Sanitation Fire");
System.out.println("------ ---------- ----");
int count = 0;
for (int i = 2; i <= 6; i += 2) {
for (int j = 1; j <= 7; ++j) {
if (j == i) continue;
for (int k = 1; k <= 7; ++k) {
if (k == i || k == j) continue;
if (i + j + k != 12) continue;
System.out.printf(" %d %d %d\n", i, j, k);
count++;
}
}
}
System.out.printf("\n%d valid combinations", count);
}
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Write the same code in Rust as shown below in Java. | public class DepartmentNumbers {
public static void main(String[] args) {
System.out.println("Police Sanitation Fire");
System.out.println("------ ---------- ----");
int count = 0;
for (int i = 2; i <= 6; i += 2) {
for (int j = 1; j <= 7; ++j) {
if (j == i) continue;
for (int k = 1; k <= 7; ++k) {
if (k == i || k == j) continue;
if (i + j + k != 12) continue;
System.out.printf(" %d %d %d\n", i, j, k);
count++;
}
}
}
System.out.printf("\n%d valid combinations", count);
}
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Change the programming language of this snippet from Go to Rust without modifying what it does. | package main
import "fmt"
func main() {
fmt.Println("Police Sanitation Fire")
fmt.Println("------ ---------- ----")
count := 0
for i := 2; i < 7; i += 2 {
for j := 1; j < 8; j++ {
if j == i { continue }
for k := 1; k < 8; k++ {
if k == i || k == j { continue }
if i + j + k != 12 { continue }
fmt.Printf(" %d %d %d\n", i, j, k)
count++
}
}
}
fmt.Printf("\n%d valid combinations\n", count)
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Translate the given Rust code snippet into Python without altering its behavior. | extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
| from itertools import permutations
def solve():
c, p, f, s = "\\,Police,Fire,Sanitation".split(',')
print(f"{c:>3} {p:^6} {f:^4} {s:^10}")
c = 1
for p, f, s in permutations(range(1, 8), r=3):
if p + s + f == 12 and p % 2 == 0:
print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
c += 1
if __name__ == '__main__':
solve()
|
Convert this Rust block to Python, preserving its control flow and logic. | extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
| from itertools import permutations
def solve():
c, p, f, s = "\\,Police,Fire,Sanitation".split(',')
print(f"{c:>3} {p:^6} {f:^4} {s:^10}")
c = 1
for p, f, s in permutations(range(1, 8), r=3):
if p + s + f == 12 and p % 2 == 0:
print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
c += 1
if __name__ == '__main__':
solve()
|
Produce a functionally identical Rust code for the snippet given in C. | #include<stdio.h>
int main()
{
int police,sanitation,fire;
printf("Police Sanitation Fire\n");
printf("----------------------------------");
for(police=2;police<=6;police+=2){
for(sanitation=1;sanitation<=7;sanitation++){
for(fire=1;fire<=7;fire++){
if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){
printf("\n%d\t\t%d\t\t%d",police,sanitation,fire);
}
}
}
}
return 0;
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Port the following code from Go to Rust with equivalent syntax and logic. | package main
import "fmt"
func main() {
fmt.Println("Police Sanitation Fire")
fmt.Println("------ ---------- ----")
count := 0
for i := 2; i < 7; i += 2 {
for j := 1; j < 8; j++ {
if j == i { continue }
for k := 1; k < 8; k++ {
if k == i || k == j { continue }
if i + j + k != 12 { continue }
fmt.Printf(" %d %d %d\n", i, j, k)
count++
}
}
}
fmt.Printf("\n%d valid combinations\n", count)
}
| extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
|
Convert the following code from Rust to VB, ensuring the logic remains intact. | extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
| Module Module1
Sub Main()
For p = 2 To 7 Step 2
For s = 1 To 7
Dim f = 12 - p - s
If s >= f Then
Exit For
End If
If f > 7 Then
Continue For
End If
If s = p OrElse f = p Then
Continue For
End If
Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}")
Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}")
Next
Next
End Sub
End Module
|
Produce a language-to-language conversion: from Rust to VB, same semantics. | extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
println!("----------------------");
for police in num_iter::range_step(2, 7, 2) {
for sanitation in 1..8 {
for fire in 1..8 {
if police != sanitation
&& sanitation != fire
&& fire != police
&& police + fire + sanitation == 12
{
println!("{:6}{:11}{:4}", police, sanitation, fire);
}
}
}
}
}
| Module Module1
Sub Main()
For p = 2 To 7 Step 2
For s = 1 To 7
Dim f = 12 - p - s
If s >= f Then
Exit For
End If
If f > 7 Then
Continue For
End If
If s = p OrElse f = p Then
Continue For
End If
Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}")
Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}")
Next
Next
End Sub
End Module
|
Generate a C# translation of this Ada snippet without changing its computational steps. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Produce a functionally identical C# code for the snippet given in Ada. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Change the programming language of this snippet from Ada to C without modifying what it does. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Ada. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Ada code. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Port the following code from Ada to C++ with equivalent syntax and logic. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Write the same algorithm in Go as shown in this Ada implementation. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Ada version. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Ensure the translated Java code behaves exactly like the original Ada snippet. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Convert this Ada block to Java, preserving its control flow and logic. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Write the same code in Python as shown below in Ada. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Generate an equivalent Python version of this Ada code. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Rewrite this program in VB while keeping its functionality equivalent to the Ada version. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Produce a language-to-language conversion: from Ada to VB, same semantics. | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
function Fusc_Slow (N : in Natural) return Natural is
begin
if N = 0 or N = 1 then
return N;
elsif N mod 2 = 0 then
return Fusc_Slow (N / 2);
else
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
end if;
end Fusc_Slow;
function Fusc (N : in Natural) return Natural is
begin
if N <= Precalculate then
return Precalculated_Fusc (N);
elsif N mod 2 = 0 then
return Fusc (N / 2);
else
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
end if;
end Fusc;
begin
for N in Precalculated_Fusc'Range loop
Precalculated_Fusc (N) := Fusc_Slow (N);
end loop;
end Fusc_Sequences;
package Fusc_Sequence is
new Fusc_Sequences (Precalculate => 200_000);
function Fusc (N : in Natural) return Natural
renames Fusc_Sequence.Fusc;
procedure Print_Small_Fuscs is
use Ada.Text_IO;
begin
Put_Line ("First 61 numbers in the fusc sequence:");
for N in 0 .. 60 loop
Put (Fusc (N)'Image);
Put (" ");
end loop;
New_Line;
end Print_Small_Fuscs;
procedure Print_Large_Fuscs (High : in Natural) is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
subtype N_Range is Natural range Natural'First .. High;
F : Natural;
Len : Natural;
Max_Len : Natural := 0;
Placeholder : String := " n fusc(n)";
Image_N : String renames Placeholder (1 .. 8);
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
begin
New_Line;
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
Put_Line (Placeholder);
for N in N_Range loop
F := Fusc (N);
Len := F'Image'Length;
if Len > Max_Len then
Max_Len := Len;
Put (Image_N, N);
Put (Image_Fusc, F);
Put (Placeholder);
New_Line;
end if;
end loop;
end Print_Large_Fuscs;
begin
Print_Small_Fuscs;
Print_Large_Fuscs (High => 20_000_000);
end Show_Fusc;
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Port the provided Arturo code into C while preserving the original functionality. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Write the same code in C as shown below in Arturo. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Generate a C# translation of this Arturo snippet without changing its computational steps. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Convert this Arturo block to C#, preserving its control flow and logic. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Port the provided Arturo code into C++ while preserving the original functionality. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Translate the given Arturo code snippet into C++ without altering its behavior. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Arturo to Java. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Arturo code. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Arturo version. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Produce a functionally identical Python code for the snippet given in Arturo. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Generate an equivalent VB version of this Arturo code. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Write the same algorithm in VB as shown in this Arturo implementation. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Produce a functionally identical Go code for the snippet given in Arturo. | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Generate a C translation of this AutoHotKey snippet without changing its computational steps. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Generate a C translation of this AutoHotKey snippet without changing its computational steps. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Port the provided AutoHotKey code into C# while preserving the original functionality. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Write the same code in C++ as shown below in AutoHotKey. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Write the same algorithm in C++ as shown in this AutoHotKey implementation. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Rewrite the snippet below in Java so it works the same as the original AutoHotKey code. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Change the programming language of this snippet from AutoHotKey to Java without modifying what it does. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Transform the following AutoHotKey implementation into Python, maintaining the same output and logic. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Convert this AutoHotKey snippet to Python and keep its semantics consistent. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Convert this AutoHotKey block to VB, preserving its control flow and logic. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in VB. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Translate this program into Go but keep the logic exactly as in AutoHotKey. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Rewrite the snippet below in Go so it works the same as the original AutoHotKey code. | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Write a version of this AWK function in C with identical behavior. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Write the same code in C as shown below in AWK. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the AWK version. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Write a version of this AWK function in C# with identical behavior. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Convert this AWK block to C++, preserving its control flow and logic. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Transform the following AWK implementation into C++, maintaining the same output and logic. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Port the provided AWK code into Java while preserving the original functionality. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Produce a functionally identical Java code for the snippet given in AWK. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] =Β %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Generate an equivalent Python version of this AWK code. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Keep all operations the same but rewrite the snippet in Python. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Change the programming language of this snippet from AWK to VB without modifying what it does. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Convert this AWK block to VB, preserving its control flow and logic. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Rewrite this program in Go while keeping its functionality equivalent to the AWK version. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Transform the following AWK implementation into Go, maintaining the same output and logic. |
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Change the following D code into C without altering its purpose. | import std.functional, std.stdio, std.format, std.conv;
ulong fusc(ulong n) =>
memoize!fuscImp(n);
ulong fuscImp(ulong n) =>
( n < 2 ) ? n :
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
void main() {
const N_FIRST=61;
const MAX_N_DIGITS=5;
format!"First %d fusc numbers: "(N_FIRST).write;
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
writeln;
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
if( n.fusc.to!string.length > ndigits ){
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
ndigits = n.fusc.to!string.length.to!int;
}
}
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Convert this D snippet to C and keep its semantics consistent. | import std.functional, std.stdio, std.format, std.conv;
ulong fusc(ulong n) =>
memoize!fuscImp(n);
ulong fuscImp(ulong n) =>
( n < 2 ) ? n :
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
void main() {
const N_FIRST=61;
const MAX_N_DIGITS=5;
format!"First %d fusc numbers: "(N_FIRST).write;
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
writeln;
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
if( n.fusc.to!string.length > ndigits ){
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
ndigits = n.fusc.to!string.length.to!int;
}
}
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Convert the following code from D to C#, ensuring the logic remains intact. | import std.functional, std.stdio, std.format, std.conv;
ulong fusc(ulong n) =>
memoize!fuscImp(n);
ulong fuscImp(ulong n) =>
( n < 2 ) ? n :
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
void main() {
const N_FIRST=61;
const MAX_N_DIGITS=5;
format!"First %d fusc numbers: "(N_FIRST).write;
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
writeln;
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
if( n.fusc.to!string.length > ndigits ){
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
ndigits = n.fusc.to!string.length.to!int;
}
}
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import std.functional, std.stdio, std.format, std.conv;
ulong fusc(ulong n) =>
memoize!fuscImp(n);
ulong fuscImp(ulong n) =>
( n < 2 ) ? n :
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
void main() {
const N_FIRST=61;
const MAX_N_DIGITS=5;
format!"First %d fusc numbers: "(N_FIRST).write;
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
writeln;
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
if( n.fusc.to!string.length > ndigits ){
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
ndigits = n.fusc.to!string.length.to!int;
}
}
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Write a version of this D function in C++ with identical behavior. | import std.functional, std.stdio, std.format, std.conv;
ulong fusc(ulong n) =>
memoize!fuscImp(n);
ulong fuscImp(ulong n) =>
( n < 2 ) ? n :
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
void main() {
const N_FIRST=61;
const MAX_N_DIGITS=5;
format!"First %d fusc numbers: "(N_FIRST).write;
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
writeln;
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
if( n.fusc.to!string.length > ndigits ){
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
ndigits = n.fusc.to!string.length.to!int;
}
}
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.