Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in C++ as shown in this D implementation. | 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;
}
|
Produce a functionally identical Java code for the snippet given in D. | 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;
}
}
| 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]);
}
}
}
|
Translate this program into Java but keep the logic exactly as in D. | 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;
}
}
| 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]);
}
}
}
|
Preserve the algorithm and functionality while converting the code from D to Python. | 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;
}
}
| 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 D. | 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;
}
}
| 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}')
|
Write the same code in VB as shown below in D. | 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;
}
}
| 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 D snippet to VB 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;
}
}
| 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
|
Generate a Go translation of this D snippet without changing its computational steps. | 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;
}
}
| 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]))
}
}
|
Convert this D snippet to Go 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;
}
}
| 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 F# function in C with identical behavior. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| #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;
}
|
Port the provided F# code into C while preserving the original functionality. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| #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 language-to-language conversion: from F# to C#, same semantics. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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#. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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();
}
}
|
Translate this program into C++ but keep the logic exactly as in F#. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| #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 C++ so it works the same as the original F# code. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| #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 F# implementation into Java, maintaining the same output and logic. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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 Java as shown below in F#. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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]);
}
}
}
|
Can you help me rewrite this code in Python instead of F#, keeping it the same logically? |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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 F# code. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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}')
|
Please provide an equivalent version of this F# code in VB. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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 the given F# code snippet into VB without altering its behavior. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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
|
Please provide an equivalent version of this F# code in Go. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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]))
}
}
|
Preserve the algorithm and functionality while converting the code from F# to Go. |
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
| 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]))
}
}
|
Translate this program into C but keep the logic exactly as in Factor. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| #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 Factor. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| #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;
}
|
Please provide an equivalent version of this Factor code in C#. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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();
}
}
|
Translate this program into C# but keep the logic exactly as in Factor. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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 following code from Factor to C++ with equivalent syntax and logic. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| #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;
}
|
Change the programming language of this snippet from Factor to C++ without modifying what it does. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| #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 this program in Java while keeping its functionality equivalent to the Factor version. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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]);
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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 a Python translation of this Factor snippet without changing its computational steps. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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}')
|
Please provide an equivalent version of this Factor code in Python. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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}')
|
Maintain the same structure and functionality when rewriting this code in VB. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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 a version of this Factor function in VB with identical behavior. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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
|
Generate an equivalent Go version of this Factor code. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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]))
}
}
|
Convert this Factor snippet to Go and keep its semantics consistent. | USING: arrays assocs formatting io kernel make math math.parser
math.ranges namespaces prettyprint sequences
tools.memory.private ;
IN: rosetta-code.fusc
<PRIVATE
: (fusc) ( n -- seq )
[ 2 ] dip [a,b) [
0 , 1 , [
[ building get ] dip dup even?
[ 2/ swap nth ]
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
if ,
] each
] { } make ;
: increases ( seq -- assoc )
[ 0 ] dip [
[
2array 2dup first number>string length <
[ [ 1 + ] [ , ] bi* ] [ drop ] if
] each-index
] { } make nip ;
PRIVATE>
: fusc ( n -- seq )
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
: fusc-demo ( -- )
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
nl nl
"Fusc numbers with more digits than all previous ones:"
print "Value Index\n====== =======" print
1,000,000 fusc increases
[ [ commas ] bi@ "%-6s Β %-7s\n" printf ] assoc-each ;
MAIN: fusc-demo
| 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 C so it works the same as the original Forth code. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| #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;
}
|
Ensure the translated C code behaves exactly like the original Forth snippet. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| #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;
}
|
Translate the given Forth code snippet into C# without altering its behavior. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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 the following code from Forth to C#, ensuring the logic remains intact. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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();
}
}
|
Ensure the translated C++ code behaves exactly like the original Forth snippet. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| #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;
}
|
Keep all operations the same but rewrite the snippet in C++. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| #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 Forth code. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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]);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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 Forth block to Python, preserving its control flow and logic. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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 the snippet below in Python so it works the same as the original Forth code. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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}')
|
Translate this program into VB but keep the logic exactly as in Forth. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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 Forth snippet to VB and keep its semantics consistent. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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 the snippet below in Go so it works the same as the original Forth code. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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]))
}
}
|
Port the following code from Forth to Go with equivalent syntax and logic. |
: fusc
dup dup 0= swap 1 = or
if exit
else dup 2 mod 0=
if 2/ recurse
else dup 1- 2/ recurse
swap 1+ 2/ recurse +
then
then
;
: cntDigits
0 begin 1+ swap
10 /
swap over
0= until
swap drop
;
: fuscLen
cr 1 swap 0
do
i fusc cntDigits
over > if 1+
." fuscΒ : "
i fusc . cr
then
loop
;
: firstFusc
dup ." First " . ." fuscΒ : " cr
0 do I fusc . loop cr
;
61 firstFusc
20 1000 1000 * * fuscLen
bye
| 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 the same algorithm in C as shown in this Groovy implementation. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| #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 algorithm in C as shown in this Groovy implementation. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| #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;
}
|
Port the following code from Groovy to C# with equivalent syntax and logic. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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();
}
}
|
Generate an equivalent C# version of this Groovy code. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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 algorithm in C++ as shown in this Groovy implementation. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| #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;
}
|
Please provide an equivalent version of this Groovy code in C++. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| #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 this program in Java while keeping its functionality equivalent to the Groovy version. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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]);
}
}
}
|
Port the provided Groovy code into Java while preserving the original functionality. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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 language-to-language conversion: from Groovy to Python, same semantics. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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 Groovy snippet to Python and keep its semantics consistent. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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}')
|
Write a version of this Groovy function in VB with identical behavior. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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 the given Groovy code snippet into VB without altering its behavior. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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 Groovy to Go, same semantics. | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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]))
}
}
|
Can you help me rewrite this code in Go instead of Groovy, keeping it the same logically? | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
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) {
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++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
| 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 C code behaves exactly like the original Haskell snippet. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| #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;
}
|
Transform the following Haskell implementation into C, maintaining the same output and logic. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| #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 an equivalent C# version of this Haskell code. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 Haskell function in C# with identical behavior. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 Haskell. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| #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 Haskell to C++. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| #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 a version of this Haskell function in Java with identical behavior. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 Haskell to Java without modifying what it does. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 the following code from Haskell to Python, ensuring the logic remains intact. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 Haskell code. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 the snippet below in VB so it works the same as the original Haskell code. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 a version of this Haskell function in VB with identical behavior. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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 Haskell version. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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]))
}
}
|
Preserve the algorithm and functionality while converting the code from Haskell to Go. |
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
| 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]))
}
}
|
Port the following code from J to C with equivalent syntax and logic. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| #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;
}
|
Transform the following J implementation into C, maintaining the same output and logic. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| #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 J snippet without changing its computational steps. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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();
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the J version. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 J block to C++, preserving its control flow and logic. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| #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 C++ so it works the same as the original J code. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| #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 J code into Java while preserving the original functionality. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 J block to Java, preserving its control flow and logic. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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]);
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 the following code from J to Python, ensuring the logic remains intact. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 following J code into VB without altering its purpose. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 functionally identical VB code for the snippet given in J. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 a version of this J function in Go with identical behavior. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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]))
}
}
|
Translate the given J code snippet into Go without altering its behavior. | fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
βββββββ¬ββ¬βββ¬βββββ¬ββββββ
βindexβ0β37β1173β35499β
βββββββΌββΌβββΌβββββΌββββββ€
βvalueβ0β11β 108β 1076β
βββββββ΄ββ΄βββ΄βββββ΄ββββββ
| 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 Julia code into C without altering its purpose. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| #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 a version of this Julia function in C with identical behavior. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| #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;
}
|
Change the following Julia code into C# without altering its purpose. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| 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 Julia code into C# while preserving the original functionality. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| 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 the following code from Julia to C++, ensuring the logic remains intact. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| #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;
}
|
Change the programming language of this snippet from Julia to C++ without modifying what it does. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| #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 code in Java as shown below in Julia. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence numberΒ : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), "Β : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| 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]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.