Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided Racket code into Python while preserving the original functionality.
#lang racket (require racket/generator) (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args))))) (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))])))) (define (comma x) (string-join (reverse (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)]) (cond [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)] [else (string digit)]))) "")) (displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " ")) (newline) (define gen (in-generator (let loop ([prev 0] [i 0]) (define result (fusc i)) (define len (string-length (~a result))) (cond [(> len prev) (yield (list i result)) (loop len (add1 i))] [else (loop prev (add1 i))])))) (for ([i (in-range 5)] [x gen]) (match-define (list index result) x) (printf "~a: ~a\n" (comma index) (comma result)))
from collections import deque from itertools import islice, count def fusc(): q = deque([1]) yield 0 yield 1 while True: x = q.popleft() q.append(x) yield x x += q[0] q.append(x) yield x def longest_fusc(): sofar = 0 for i, f in zip(count(), fusc()): if f >= sofar: yield(i, f) sofar = 10 * sofar or 10 print('First 61:') print(list(islice(fusc(), 61))) print('\nLength records:') for i, f in islice(longest_fusc(), 6): print(f'fusc({i}) = {f}')
Maintain the same structure and functionality when rewriting this code in VB.
#lang racket (require racket/generator) (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args))))) (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))])))) (define (comma x) (string-join (reverse (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)]) (cond [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)] [else (string digit)]))) "")) (displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " ")) (newline) (define gen (in-generator (let loop ([prev 0] [i 0]) (define result (fusc i)) (define len (string-length (~a result))) (cond [(> len prev) (yield (list i result)) (loop len (add1 i))] [else (loop prev (add1 i))])))) (for ([i (in-range 5)] [x gen]) (match-define (list index result) x) (printf "~a: ~a\n" (comma index) (comma result)))
Module Module1 Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList Function fusc(n As Integer) As Integer If n < l.Count Then Return l(n) fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1)) l.Add(fusc) End Function Sub Main(args As String()) Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0, fs As String = "{0,11:n0} {1,-9:n0}", res As String = "" Console.WriteLine("First {0} numbers in the fusc sequence:", n) For i As Integer = 0 To Integer.MaxValue Dim f As Integer = fusc(i) If lst Then If i < 61 Then Console.Write("{0} ", f) Else lst = False Console.WriteLine() Console.WriteLine("Points in the sequence where an item has more digits than any previous items:") Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = "" End If End If Dim t As Integer = f.ToString.Length If t > w Then w = t res &= If(res = "", "", vbLf) & String.Format(fs, i, f) If Not lst Then Console.WriteLine(res) : res = "" c += 1 : If c > 5 Then Exit For End If Next : l.Clear() End Sub End Module
Change the following Racket code into VB without altering its purpose.
#lang racket (require racket/generator) (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args))))) (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))])))) (define (comma x) (string-join (reverse (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)]) (cond [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)] [else (string digit)]))) "")) (displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " ")) (newline) (define gen (in-generator (let loop ([prev 0] [i 0]) (define result (fusc i)) (define len (string-length (~a result))) (cond [(> len prev) (yield (list i result)) (loop len (add1 i))] [else (loop prev (add1 i))])))) (for ([i (in-range 5)] [x gen]) (match-define (list index result) x) (printf "~a: ~a\n" (comma index) (comma result)))
Module Module1 Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList Function fusc(n As Integer) As Integer If n < l.Count Then Return l(n) fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1)) l.Add(fusc) End Function Sub Main(args As String()) Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0, fs As String = "{0,11:n0} {1,-9:n0}", res As String = "" Console.WriteLine("First {0} numbers in the fusc sequence:", n) For i As Integer = 0 To Integer.MaxValue Dim f As Integer = fusc(i) If lst Then If i < 61 Then Console.Write("{0} ", f) Else lst = False Console.WriteLine() Console.WriteLine("Points in the sequence where an item has more digits than any previous items:") Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = "" End If End If Dim t As Integer = f.ToString.Length If t > w Then w = t res &= If(res = "", "", vbLf) & String.Format(fs, i, f) If Not lst Then Console.WriteLine(res) : res = "" c += 1 : If c > 5 Then Exit For End If Next : l.Clear() End Sub End Module
Rewrite the snippet below in Go so it works the same as the original Racket code.
#lang racket (require racket/generator) (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args))))) (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))])))) (define (comma x) (string-join (reverse (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)]) (cond [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)] [else (string digit)]))) "")) (displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " ")) (newline) (define gen (in-generator (let loop ([prev 0] [i 0]) (define result (fusc i)) (define len (string-length (~a result))) (cond [(> len prev) (yield (list i result)) (loop len (add1 i))] [else (loop prev (add1 i))])))) (for ([i (in-range 5)] [x gen]) (match-define (list index result) x) (printf "~a: ~a\n" (comma index) (comma result)))
package main import ( "fmt" "strconv" ) func fusc(n int) []int { if n <= 0 { return []int{} } if n == 1 { return []int{0} } res := make([]int, n) res[0] = 0 res[1] = 1 for i := 2; i < n; i++ { if i%2 == 0 { res[i] = res[i/2] } else { res[i] = res[(i-1)/2] + res[(i+1)/2] } } return res } func fuscMaxLen(n int) [][2]int { maxLen := -1 maxFusc := -1 f := fusc(n) var res [][2]int for i := 0; i < n; i++ { if f[i] <= maxFusc { continue } maxFusc = f[i] le := len(strconv.Itoa(f[i])) if le > maxLen { res = append(res, [2]int{i, f[i]}) maxLen = le } } return res } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { fmt.Println("The first 61 fusc numbers are:") fmt.Println(fusc(61)) fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:") res := fuscMaxLen(20000000) for i := 0; i < len(res); i++ { fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0])) } }
Preserve the algorithm and functionality while converting the code from Racket to Go.
#lang racket (require racket/generator) (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args))))) (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))])))) (define (comma x) (string-join (reverse (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)]) (cond [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)] [else (string digit)]))) "")) (displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " ")) (newline) (define gen (in-generator (let loop ([prev 0] [i 0]) (define result (fusc i)) (define len (string-length (~a result))) (cond [(> len prev) (yield (list i result)) (loop len (add1 i))] [else (loop prev (add1 i))])))) (for ([i (in-range 5)] [x gen]) (match-define (list index result) x) (printf "~a: ~a\n" (comma index) (comma result)))
package main import ( "fmt" "strconv" ) func fusc(n int) []int { if n <= 0 { return []int{} } if n == 1 { return []int{0} } res := make([]int, n) res[0] = 0 res[1] = 1 for i := 2; i < n; i++ { if i%2 == 0 { res[i] = res[i/2] } else { res[i] = res[(i-1)/2] + res[(i+1)/2] } } return res } func fuscMaxLen(n int) [][2]int { maxLen := -1 maxFusc := -1 f := fusc(n) var res [][2]int for i := 0; i < n; i++ { if f[i] <= maxFusc { continue } maxFusc = f[i] le := len(strconv.Itoa(f[i])) if le > maxLen { res = append(res, [2]int{i, f[i]}) maxLen = le } } return res } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { fmt.Println("The first 61 fusc numbers are:") fmt.Println(fusc(61)) fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:") res := fuscMaxLen(20000000) for i := 0; i < len(res); i++ { fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0])) } }
Rewrite the snippet below in C so it works the same as the original REXX code.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
#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; }
Can you help me rewrite this code in C instead of REXX, keeping it the same logically?
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
#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 REXX snippet without changing its computational steps.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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(); } }
Can you help me rewrite this code in C# instead of REXX, keeping it the same logically?
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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(); } }
Preserve the algorithm and functionality while converting the code from REXX to C++.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
#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; }
Convert the following code from REXX to C++, ensuring the logic remains intact.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
#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; }
Convert this REXX block to Java, preserving its control flow and logic.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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 Java instead of REXX, keeping it the same logically?
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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 algorithm in Python as shown in this REXX implementation.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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 REXX code.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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}')
Port the following code from REXX to VB with equivalent syntax and logic.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
Module Module1 Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList Function fusc(n As Integer) As Integer If n < l.Count Then Return l(n) fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1)) l.Add(fusc) End Function Sub Main(args As String()) Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0, fs As String = "{0,11:n0} {1,-9:n0}", res As String = "" Console.WriteLine("First {0} numbers in the fusc sequence:", n) For i As Integer = 0 To Integer.MaxValue Dim f As Integer = fusc(i) If lst Then If i < 61 Then Console.Write("{0} ", f) Else lst = False Console.WriteLine() Console.WriteLine("Points in the sequence where an item has more digits than any previous items:") Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = "" End If End If Dim t As Integer = f.ToString.Length If t > w Then w = t res &= If(res = "", "", vbLf) & String.Format(fs, i, f) If Not lst Then Console.WriteLine(res) : res = "" c += 1 : If c > 5 Then Exit For End If Next : l.Clear() End Sub End Module
Port the provided REXX code into VB while preserving the original functionality.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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 REXX code snippet into Go without altering its behavior.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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 Go as shown in this REXX implementation.
parse arg st # xw . if st=='' | st=="," then st= 0 if #=='' | #=="," then #= 61 if xw=='' | xw=="," then xw= 0 list= xw<1 @.=; @.0= 0; @.1= 1 mL= 0 $= do j=0 for # if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) else nop else do; if length(@.j)<=mL then iterate mL= length(@.j) if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave end end if $\=='' then say strip($) exit 0 commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
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])) } }
Please provide an equivalent version of this Ruby code in C.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
#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 Ruby to C, same semantics.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
#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 programming language of this snippet from Ruby to C# without modifying what it does.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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(); } }
Please provide an equivalent version of this Ruby code in C#.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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++.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
#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; }
Generate an equivalent C++ version of this Ruby code.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
#include <iomanip> #include <iostream> #include <limits> #include <sstream> #include <vector> const int n = 61; std::vector<int> l{ 0, 1 }; int fusc(int n) { if (n < l.size()) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.push_back(f); return f; } int main() { bool lst = true; int w = -1; int c = 0; int t; std::string res; std::cout << "First " << n << " numbers in the fusc sequence:\n"; for (int i = 0; i < INT32_MAX; i++) { int f = fusc(i); if (lst) { if (i < 61) { std::cout << f << ' '; } else { lst = false; std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n"; std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n"; std::cout << res << '\n'; res = ""; } } std::stringstream ss; ss << f; t = ss.str().length(); ss.str(""); ss.clear(); if (t > w) { w = t; res += (res == "" ? "" : "\n"); ss << std::setw(11) << i << " " << std::left << std::setw(9) << f; res += ss.str(); if (!lst) { std::cout << res << '\n'; res = ""; } if (++c > 5) { break; } } } return 0; }
Translate this program into Java but keep the logic exactly as in Ruby.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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 a version of this Ruby function in Java with identical behavior.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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 Ruby, keeping it the same logically?
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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 Ruby code.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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 Ruby function in VB with identical behavior.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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 Ruby function in VB with identical behavior.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
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 Ruby to Go, same semantics.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
package main import ( "fmt" "strconv" ) func fusc(n int) []int { if n <= 0 { return []int{} } if n == 1 { return []int{0} } res := make([]int, n) res[0] = 0 res[1] = 1 for i := 2; i < n; i++ { if i%2 == 0 { res[i] = res[i/2] } else { res[i] = res[(i-1)/2] + res[(i+1)/2] } } return res } func fuscMaxLen(n int) [][2]int { maxLen := -1 maxFusc := -1 f := fusc(n) var res [][2]int for i := 0; i < n; i++ { if f[i] <= maxFusc { continue } maxFusc = f[i] le := len(strconv.Itoa(f[i])) if le > maxLen { res = append(res, [2]int{i, f[i]}) maxLen = le } } return res } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { fmt.Println("The first 61 fusc numbers are:") fmt.Println(fusc(61)) fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:") res := fuscMaxLen(20000000) for i := 0; i < len(res); i++ { fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0])) } }
Transform the following Ruby implementation into Go, maintaining the same output and logic.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
package main import ( "fmt" "strconv" ) func fusc(n int) []int { if n <= 0 { return []int{} } if n == 1 { return []int{0} } res := make([]int, n) res[0] = 0 res[1] = 1 for i := 2; i < n; i++ { if i%2 == 0 { res[i] = res[i/2] } else { res[i] = res[(i-1)/2] + res[(i+1)/2] } } return res } func fuscMaxLen(n int) [][2]int { maxLen := -1 maxFusc := -1 f := fusc(n) var res [][2]int for i := 0; i < n; i++ { if f[i] <= maxFusc { continue } maxFusc = f[i] le := len(strconv.Itoa(f[i])) if le > maxLen { res = append(res, [2]int{i, f[i]}) maxLen = le } } return res } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { fmt.Println("The first 61 fusc numbers are:") fmt.Println(fusc(61)) fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:") res := fuscMaxLen(20000000) for i := 0; i < len(res); i++ { fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0])) } }
Generate a C translation of this Scala snippet without changing its computational steps.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
#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 Scala implementation into C, maintaining the same output and logic.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
#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 Scala snippet without changing its computational steps.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Scala snippet.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Scala snippet to C++ and keep its semantics consistent.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
#include <iomanip> #include <iostream> #include <limits> #include <sstream> #include <vector> const int n = 61; std::vector<int> l{ 0, 1 }; int fusc(int n) { if (n < l.size()) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.push_back(f); return f; } int main() { bool lst = true; int w = -1; int c = 0; int t; std::string res; std::cout << "First " << n << " numbers in the fusc sequence:\n"; for (int i = 0; i < INT32_MAX; i++) { int f = fusc(i); if (lst) { if (i < 61) { std::cout << f << ' '; } else { lst = false; std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n"; std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n"; std::cout << res << '\n'; res = ""; } } std::stringstream ss; ss << f; t = ss.str().length(); ss.str(""); ss.clear(); if (t > w) { w = t; res += (res == "" ? "" : "\n"); ss << std::setw(11) << i << " " << std::left << std::setw(9) << f; res += ss.str(); if (!lst) { std::cout << res << '\n'; res = ""; } if (++c > 5) { break; } } } return 0; }
Translate the given Scala code snippet into C++ without altering its behavior.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
#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; }
Generate a Java translation of this Scala snippet without changing its computational steps.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Scala snippet to Java and keep its semantics consistent.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Scala snippet without changing its computational steps.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 the given Scala code snippet into Python without altering its behavior.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
from collections import deque from itertools import islice, count def fusc(): q = deque([1]) yield 0 yield 1 while True: x = q.popleft() q.append(x) yield x x += q[0] q.append(x) yield x def longest_fusc(): sofar = 0 for i, f in zip(count(), fusc()): if f >= sofar: yield(i, f) sofar = 10 * sofar or 10 print('First 61:') print(list(islice(fusc(), 61))) print('\nLength records:') for i, f in islice(longest_fusc(), 6): print(f'fusc({i}) = {f}')
Rewrite this program in VB while keeping its functionality equivalent to the Scala version.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Scala snippet to VB and keep its semantics consistent.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Scala code.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 code in Go as shown below in Scala.
fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res } fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res } fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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 Swift to C with equivalent syntax and logic.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
#include<limits.h> #include<stdio.h> int fusc(int n){ if(n==0||n==1) return n; else if(n%2==0) return fusc(n/2); else return fusc((n-1)/2) + fusc((n+1)/2); } int numLen(int n){ int sum = 1; while(n>9){ n = n/10; sum++; } return sum; } void printLargeFuscs(int limit){ int i,f,len,maxLen = 1; printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit); for(i=0;i<=limit;i++){ f = fusc(i); len = numLen(f); if(len>maxLen){ maxLen = len; printf("\n%5d%12d",i,f); } } } int main() { int i; printf("Index-------Value"); for(i=0;i<61;i++) printf("\n%5d%12d",i,fusc(i)); printLargeFuscs(INT_MAX); return 0; }
Keep all operations the same but rewrite the snippet in C.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
#include<limits.h> #include<stdio.h> int fusc(int n){ if(n==0||n==1) return n; else if(n%2==0) return fusc(n/2); else return fusc((n-1)/2) + fusc((n+1)/2); } int numLen(int n){ int sum = 1; while(n>9){ n = n/10; sum++; } return sum; } void printLargeFuscs(int limit){ int i,f,len,maxLen = 1; printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit); for(i=0;i<=limit;i++){ f = fusc(i); len = numLen(f); if(len>maxLen){ maxLen = len; printf("\n%5d%12d",i,f); } } } int main() { int i; printf("Index-------Value"); for(i=0;i<61;i++) printf("\n%5d%12d",i,fusc(i)); printLargeFuscs(INT_MAX); return 0; }
Rewrite the snippet below in C# so it works the same as the original Swift code.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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(); } }
Transform the following Swift implementation into C#, maintaining the same output and logic.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 Swift block to C++, preserving its control flow and logic.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
#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 Swift to C++ without modifying what it does.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
#include <iomanip> #include <iostream> #include <limits> #include <sstream> #include <vector> const int n = 61; std::vector<int> l{ 0, 1 }; int fusc(int n) { if (n < l.size()) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.push_back(f); return f; } int main() { bool lst = true; int w = -1; int c = 0; int t; std::string res; std::cout << "First " << n << " numbers in the fusc sequence:\n"; for (int i = 0; i < INT32_MAX; i++) { int f = fusc(i); if (lst) { if (i < 61) { std::cout << f << ' '; } else { lst = false; std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n"; std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n"; std::cout << res << '\n'; res = ""; } } std::stringstream ss; ss << f; t = ss.str().length(); ss.str(""); ss.clear(); if (t > w) { w = t; res += (res == "" ? "" : "\n"); ss << std::setw(11) << i << " " << std::left << std::setw(9) << f; res += ss.str(); if (!lst) { std::cout << res << '\n'; res = ""; } if (++c > 5) { break; } } } return 0; }
Write the same algorithm in Java as shown in this Swift implementation.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 Swift snippet to Python and keep its semantics consistent.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 Swift code.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 Swift snippet to VB and keep its semantics consistent.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
Module Module1 Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList Function fusc(n As Integer) As Integer If n < l.Count Then Return l(n) fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1)) l.Add(fusc) End Function Sub Main(args As String()) Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0, fs As String = "{0,11:n0} {1,-9:n0}", res As String = "" Console.WriteLine("First {0} numbers in the fusc sequence:", n) For i As Integer = 0 To Integer.MaxValue Dim f As Integer = fusc(i) If lst Then If i < 61 Then Console.Write("{0} ", f) Else lst = False Console.WriteLine() Console.WriteLine("Points in the sequence where an item has more digits than any previous items:") Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = "" End If End If Dim t As Integer = f.ToString.Length If t > w Then w = t res &= If(res = "", "", vbLf) & String.Format(fs, i, f) If Not lst Then Console.WriteLine(res) : res = "" c += 1 : If c > 5 Then Exit For End If Next : l.Clear() End Sub End Module
Write the same algorithm in VB as shown in this Swift implementation.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 Swift code in Go.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 provided Swift code into Go while preserving the original functionality.
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0 mutating func next() -> Int? { defer { i += 1 } guard i > 1 else { return arr[i] } switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() } return arr.last! } } let first = FuscSeq().prefix(61) print("First 61: \(Array(first))") var max = -1 for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count if f > max { max = f print("New max: \(i): \(n)") } }
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 Tcl to C.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
#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; }
Preserve the algorithm and functionality while converting the code from Tcl to C.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
#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 Tcl snippet without changing its computational steps.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
using System; using System.Collections.Generic; static class program { static int n = 61; static List<int> l = new List<int>() { 0, 1 }; static int fusc(int n) { if (n < l.Count) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.Add(f); return f; } static void Main(string[] args) { bool lst = true; int w = -1, c = 0, t; string fs = "{0,11:n0} {1,-9:n0}", res = ""; Console.WriteLine("First {0} numbers in the fusc sequence:", n); for (int i = 0; i < int.MaxValue; i++) { int f = fusc(i); if (lst) { if (i < 61) Console.Write("{0} ", f); else { lst = false; Console.WriteLine(); Console.WriteLine("Points in the sequence where an item has more digits than any previous items:"); Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = ""; } } if ((t = f.ToString().Length) > w) { w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f); if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break; } } l.Clear(); } }
Produce a functionally identical C# code for the snippet given in Tcl.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 Tcl implementation.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
#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 Tcl implementation into C++, maintaining the same output and logic.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
#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 Java.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 Tcl to Java without modifying what it does.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 Tcl snippet to Python and keep its semantics consistent.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 Python.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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}')
Port the following code from Tcl to VB with equivalent syntax and logic.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 VB while keeping its functionality equivalent to the Tcl version.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 Tcl function in Go with identical behavior.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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])) } }
Maintain the same structure and functionality when rewriting this code in Go.
proc fusc n { if {$n < 2} { return $n } if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) } if {$n % 2} { ; set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ; set r [fusc [expr {$n/2}]] } if {$n < 999999} { set ::g_fusc($n) $r } return $r } proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] } proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" } proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
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 C to Rust with equivalent syntax and logic.
#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; }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Produce a functionally identical Rust code for the snippet given in C++.
#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; }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Convert this C++ snippet to Rust and keep its semantics consistent.
#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; }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Change the following C# code into Rust without altering its purpose.
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(); } }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Maintain the same structure and functionality when rewriting this code in Rust.
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]); } } }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Rewrite this program in Rust while keeping its functionality equivalent to the Java version.
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]); } } }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Convert this Go snippet to Rust and keep its semantics consistent.
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])) } }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Ensure the translated Python code behaves exactly like the original Rust snippet.
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
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 Rust.
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
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 Rust block to VB, preserving its control flow and logic.
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
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 Rust translation of this Go snippet without changing its computational steps.
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])) } }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Can you help me rewrite this code in Rust instead of C, keeping it the same logically?
#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; }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Change the programming language of this snippet from C# to Rust without modifying what it does.
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(); } }
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
Can you help me rewrite this code in Python instead of Rust, keeping it the same logically?
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) } fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!(); let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
from collections import deque from itertools import islice, count def fusc(): q = deque([1]) yield 0 yield 1 while True: x = q.popleft() q.append(x) yield x x += q[0] q.append(x) yield x def longest_fusc(): sofar = 0 for i, f in zip(count(), fusc()): if f >= sofar: yield(i, f) sofar = 10 * sofar or 10 print('First 61:') print(list(islice(fusc(), 61))) print('\nLength records:') for i, f in islice(longest_fusc(), 6): print(f'fusc({i}) = {f}')
Keep all operations the same but rewrite the snippet in C#.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
var current = [head of list to traverse] while(current != null) { current = current.Next; }
Port the provided Ada code into C while preserving the original functionality.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
Change the following Ada code into C++ without altering its purpose.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
Translate this program into Go but keep the logic exactly as in Ada.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
Ensure the translated Java code behaves exactly like the original Ada snippet.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
LinkedList<Type> list = new LinkedList<Type>(); for(Type i: list){ System.out.println(i); }
Port the provided Ada code into Python while preserving the original functionality.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
for node in lst: print node.value
Write the same algorithm in VB as shown in this Ada implementation.
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_List : List; begin for I in 1..10 loop The_List.Append(I); end loop; The_List.Iterate(Print'access); end traversal_example;
Private Sub Iterate(ByVal list As LinkedList(Of Integer)) Dim node = list.First Do Until node Is Nothing node = node.Next Loop End Sub
Convert the following code from AutoHotKey to C, ensuring the logic remains intact.
a = 1 a_next = b b = 2 b_next = c c = 3 traverse("a") return traverse(element) { MsgBox % element . "= " . %element% name := element . "_next" while, %name% { element := %name% msgbox % %name% . "= " . %element% name := %name% . "_next" } }
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
Please provide an equivalent version of this AutoHotKey code in C#.
a = 1 a_next = b b = 2 b_next = c c = 3 traverse("a") return traverse(element) { MsgBox % element . "= " . %element% name := element . "_next" while, %name% { element := %name% msgbox % %name% . "= " . %element% name := %name% . "_next" } }
var current = [head of list to traverse] while(current != null) { current = current.Next; }
Convert this AutoHotKey snippet to C++ and keep its semantics consistent.
a = 1 a_next = b b = 2 b_next = c c = 3 traverse("a") return traverse(element) { MsgBox % element . "= " . %element% name := element . "_next" while, %name% { element := %name% msgbox % %name% . "= " . %element% name := %name% . "_next" } }
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
Generate a Java translation of this AutoHotKey snippet without changing its computational steps.
a = 1 a_next = b b = 2 b_next = c c = 3 traverse("a") return traverse(element) { MsgBox % element . "= " . %element% name := element . "_next" while, %name% { element := %name% msgbox % %name% . "= " . %element% name := %name% . "_next" } }
LinkedList<Type> list = new LinkedList<Type>(); for(Type i: list){ System.out.println(i); }