Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in C++ as shown in this AWK implementation.
BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return(h[limit-1]) } function min(x,y) { return((x < y) ? x : y) }
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Can you help me rewrite this code in Java instead of AWK, keeping it the same logically?
BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return(h[limit-1]) } function min(x,y) { return((x < y) ? x : y) }
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Convert this AWK block to Python, preserving its control flow and logic.
BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return(h[limit-1]) } function min(x,y) { return((x < y) ? x : y) }
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Port the provided AWK code into VB while preserving the original functionality.
BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return(h[limit-1]) } function min(x,y) { return((x < y) ? x : y) }
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Produce a language-to-language conversion: from AWK to Go, same semantics.
BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return(h[limit-1]) } function min(x,y) { return((x < y) ? x : y) }
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Produce a language-to-language conversion: from BBC_Basic to C, same semantics.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Port the following code from BBC_Basic to C# with equivalent syntax and logic.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Convert this BBC_Basic snippet to C++ and keep its semantics consistent.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Please provide an equivalent version of this BBC_Basic code in Java.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Produce a functionally identical Python code for the snippet given in BBC_Basic.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Translate this program into VB but keep the logic exactly as in BBC_Basic.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Change the programming language of this snippet from BBC_Basic to Go without modifying what it does.
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-1)
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Rewrite this program in C while keeping its functionality equivalent to the Clojure version.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Generate an equivalent C# version of this Clojure code.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Translate this program into C++ but keep the logic exactly as in Clojure.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Write the same algorithm in Java as shown in this Clojure implementation.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Rewrite this program in Python while keeping its functionality equivalent to the Clojure version.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Write a version of this Clojure function in VB with identical behavior.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Keep all operations the same but rewrite the snippet in Go.
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)] :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) (def hamming (lazy-seq (->> (map #(*' 5 %) hamming) (smerge (map #(*' 3 %) hamming)) (smerge (map #(*' 2 %) hamming)) (cons 1))))
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Port the provided Common_Lisp code into C while preserving the original functionality.
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Rewrite the snippet below in C# so it works the same as the original Common_Lisp code.
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Rewrite this program in C++ while keeping its functionality equivalent to the Common_Lisp version.
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Rewrite the snippet below in Java so it works the same as the original Common_Lisp code.
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Write the same code in Python as shown below in Common_Lisp.
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Can you help me rewrite this code in VB instead of Common_Lisp, keeping it the same logically?
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Write the same code in Go as shown below in Common_Lisp.
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) (when add (setf (elt seqs i) (nconc s (list (* x f)))) (if (zerop (mod x f)) (setf add nil))) finally (return x)))) (loop with factors = '(2 3 5) with seqs = (loop for i in factors collect '(1)) for n from 1 to 1000001 do (let ((x (next-hamm factors seqs))) (if (or (< n 21) (= n 1691) (= n 1000000)) (format t "~d: ~d~%" n x))))
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Produce a language-to-language conversion: from D to C, same semantics.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Transform the following D implementation into C#, maintaining the same output and logic.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Write a version of this D function in C++ with identical behavior.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Produce a language-to-language conversion: from D to Java, same semantics.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Convert this D block to Python, preserving its control flow and logic.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Translate the given D code snippet into VB without altering its behavior.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Convert this D block to Go, preserving its control flow and logic.
import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in uint n) pure nothrow { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k; foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; } void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Preserve the algorithm and functionality while converting the code from Elixir to C.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Convert this Elixir block to C#, preserving its control flow and logic.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Generate a C++ translation of this Elixir snippet without changing its computational steps.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Write the same algorithm in Java as shown in this Elixir implementation.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Translate this program into Python but keep the logic exactly as in Elixir.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Produce a language-to-language conversion: from Elixir to VB, same semantics.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Maintain the same structure and functionality when rewriting this code in Go.
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end defp queue, do: {[], []} defp push({input, output}, term), do: {[term | input], output} defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Produce a functionally identical C code for the snippet given in Erlang.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Convert this Erlang snippet to C# and keep its semantics consistent.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Translate this program into C++ but keep the logic exactly as in Erlang.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Generate an equivalent Java version of this Erlang code.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Convert this Erlang block to Python, preserving its control flow and logic.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Write a version of this Erlang function in VB with identical behavior.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Rewrite the snippet below in Go so it works the same as the original Erlang code.
list(N) -> array:to_list(element(1, array(N, [2, 3, 5]))). nth(N) -> array:get(N-1, element(1, array(N, [2, 3, 5]))). array(N, Primes) -> array(array:new(), N, 1, [{P, 1, P} || P <- Primes]). array(Array, Max, Max, Candidates) -> {Array, Candidates}; array(Array, Max, I, Candidates) -> Smallest = smallest(Candidates), N_array = array:set(I, Smallest, Array), array(N_array, Max, I+1, update(Smallest, N_array, Candidates)). update(Val, Array, Candidates) -> [update_(Val, C, Array) || C <- Candidates]. update_(Val, {Val, Ind, Mul}, Array) -> {Mul*array:get(Ind, Array), Ind+1, Mul}; update_(_, X, _) -> X. smallest(L) -> lists:min([element(1, V) || V <- L]).
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Keep all operations the same but rewrite the snippet in C.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Convert the following code from F# to C#, ensuring the logic remains intact.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Generate an equivalent C++ version of this F# code.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Write a version of this F# function in Java with identical behavior.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Generate an equivalent Python version of this F# code.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Translate this program into VB but keep the logic exactly as in F#.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Convert this F# snippet to Go and keep its semantics consistent.
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_map f (Cons(x, nxf)) = Cons(f x, lazy(inf_map f nxf.Value)) Cons(1I, lazy(let x = inf_map ( 3I) hamming let z = inf_map ((*) 5I) hamming x -|- y -|- z)) [<EntryPoint>] let main args = let rec iterLazyListFor f n (Cons(v, rf)) = if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value let rec nthLazyList n ((Cons(v, rf)) as ll) = if n <= 1 then v else nthLazyList (n - 1) rf.Value printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")" printfn "%A" (hammings() |> nthLazyList 1691) printfn "%A" (hammings() |> nthLazyList 1000000) 0
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Change the programming language of this snippet from Factor to C without modifying what it does.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Factor version.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Preserve the algorithm and functionality while converting the code from Factor to C++.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Convert this Factor block to Java, preserving its control flow and logic.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Port the provided Factor code into Python while preserving the original functionality.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Rewrite the snippet below in VB so it works the same as the original Factor code.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Produce a language-to-language conversion: from Factor to Go, same semantics.
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming TUPLE: hamming-iterator 2s 3s 5s ; : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ; : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>> ] bi* push-back ] [ [ 3 * ] [ 3s>> ] bi* push-back ] [ [ 5 * ] [ 5s>> ] bi* push-back ] 2tri ; : next ( hamming-iterator -- n ) dup [ 2s>> ] [ 3s>> ] [ 5s>> ] tri 3dup [ peek-front ] tri@ min min [ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] tri@ ] [ swap enqueue ] [ ] tri ; : next-n ( hamming-iterator n -- seq ) swap '[ _ [ _ next , ] times ] { } make ; : nth-from-now ( hamming-iterator n -- m ) 1 - over '[ _ next drop ] times next ;
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Write the same code in C as shown below in Forth.
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Keep all operations the same but rewrite the snippet in C#.
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Maintain the same structure and functionality when rewriting this code in C++.
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Please provide an equivalent version of this Forth code in Java.
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Generate a Python translation of this Forth snippet without changing its computational steps.
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Can you help me rewrite this code in VB instead of Forth, keeping it the same logically?
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Generate a Go translation of this Forth snippet without changing its computational steps.
: extract2 40 rshift ; : extract3 20 rshift $fffff and ; : extract5 $fffff and ; ' + alias h* : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ; 1 62 lshift constant ldscale2 7309349404307464679 constant ldscale3 10708003330985790206 constant ldscale5 : hld { h -- ud } h extract2 ldscale2 um* h extract3 ldscale3 um* d+ h extract5 ldscale5 um* d+ ; : h<= 2dup = if 2drop true exit then hld rot hld assert du>= ; : hmin 2dup h<= if drop else nip then ; 0 value seq variable seqlast 0 seqlast ! : lastseq seq seqlast @ th @ ; : genseq create , 0 , does> dup @ lastseq { h1 l } cell+ dup @ begin seq over th @ h1 h* dup l h<= while drop 1+ repeat >r swap ! r> ; $10000000000 genseq s2 $00000100000 genseq s3 $00000000001 genseq s5 : nextseq s2 s3 hmin s5 hmin , 1 seqlast +! ; : nthseq dup seqlast @ u+do nextseq loop 1- 0 max cells seq + @ ; : .nseq dup seqlast @ u+do nextseq loop 0 u+do seq i th @ h. loop ; here to seq 0 , 20 .nseq cr 1691 nthseq h. cr 1000000 nthseq h.
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Preserve the algorithm and functionality while converting the code from Fortran to C#.
program Hamming_Test use big_integer_module implicit none call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000) contains subroutine Hamming(first, last) integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_integer), allocatable :: hnums(:) if(present(last)) then lim = last else lim = first end if if(first < 1 .or. lim > 2500000 ) then write(*,*) "Invalid input" return end if allocate(hnums(lim)) i2 = 1 ; i3 = 1 ; i5 = 1 hnums(1) = 1 n = 1 do while(n < lim) n = n + 1 hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5)) if(2*hnums(i2) == hnums(n)) i2 = i2 + 1 if(3*hnums(i3) == hnums(n)) i3 = i3 + 1 if(5*hnums(i5) == hnums(n)) i5 = i5 + 1 end do if(present(last)) then do i = first, last call print_big(hnums(i)) write(*, "(a)", advance="no") " " end do else call print_big(hnums(first)) end if deallocate(hnums) end subroutine function mini(a, b, c) type(big_integer) :: mini type(big_integer), intent(in) :: a, b, c if(a < b ) then if(a < c) then mini = a else mini = c end if else if(b < c) then mini = b else mini = c end if end function mini end program
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Convert this Fortran snippet to C++ and keep its semantics consistent.
program Hamming_Test use big_integer_module implicit none call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000) contains subroutine Hamming(first, last) integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_integer), allocatable :: hnums(:) if(present(last)) then lim = last else lim = first end if if(first < 1 .or. lim > 2500000 ) then write(*,*) "Invalid input" return end if allocate(hnums(lim)) i2 = 1 ; i3 = 1 ; i5 = 1 hnums(1) = 1 n = 1 do while(n < lim) n = n + 1 hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5)) if(2*hnums(i2) == hnums(n)) i2 = i2 + 1 if(3*hnums(i3) == hnums(n)) i3 = i3 + 1 if(5*hnums(i5) == hnums(n)) i5 = i5 + 1 end do if(present(last)) then do i = first, last call print_big(hnums(i)) write(*, "(a)", advance="no") " " end do else call print_big(hnums(first)) end if deallocate(hnums) end subroutine function mini(a, b, c) type(big_integer) :: mini type(big_integer), intent(in) :: a, b, c if(a < b ) then if(a < c) then mini = a else mini = c end if else if(b < c) then mini = b else mini = c end if end function mini end program
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Rewrite the snippet below in C so it works the same as the original Fortran code.
program Hamming_Test use big_integer_module implicit none call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000) contains subroutine Hamming(first, last) integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_integer), allocatable :: hnums(:) if(present(last)) then lim = last else lim = first end if if(first < 1 .or. lim > 2500000 ) then write(*,*) "Invalid input" return end if allocate(hnums(lim)) i2 = 1 ; i3 = 1 ; i5 = 1 hnums(1) = 1 n = 1 do while(n < lim) n = n + 1 hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5)) if(2*hnums(i2) == hnums(n)) i2 = i2 + 1 if(3*hnums(i3) == hnums(n)) i3 = i3 + 1 if(5*hnums(i5) == hnums(n)) i5 = i5 + 1 end do if(present(last)) then do i = first, last call print_big(hnums(i)) write(*, "(a)", advance="no") " " end do else call print_big(hnums(first)) end if deallocate(hnums) end subroutine function mini(a, b, c) type(big_integer) :: mini type(big_integer), intent(in) :: a, b, c if(a < b ) then if(a < c) then mini = a else mini = c end if else if(b < c) then mini = b else mini = c end if end function mini end program
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Produce a language-to-language conversion: from Fortran to Java, same semantics.
program Hamming_Test use big_integer_module implicit none call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000) contains subroutine Hamming(first, last) integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_integer), allocatable :: hnums(:) if(present(last)) then lim = last else lim = first end if if(first < 1 .or. lim > 2500000 ) then write(*,*) "Invalid input" return end if allocate(hnums(lim)) i2 = 1 ; i3 = 1 ; i5 = 1 hnums(1) = 1 n = 1 do while(n < lim) n = n + 1 hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5)) if(2*hnums(i2) == hnums(n)) i2 = i2 + 1 if(3*hnums(i3) == hnums(n)) i3 = i3 + 1 if(5*hnums(i5) == hnums(n)) i5 = i5 + 1 end do if(present(last)) then do i = first, last call print_big(hnums(i)) write(*, "(a)", advance="no") " " end do else call print_big(hnums(first)) end if deallocate(hnums) end subroutine function mini(a, b, c) type(big_integer) :: mini type(big_integer), intent(in) :: a, b, c if(a < b ) then if(a < c) then mini = a else mini = c end if else if(b < c) then mini = b else mini = c end if end function mini end program
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Transform the following Fortran implementation into Python, maintaining the same output and logic.
program Hamming_Test use big_integer_module implicit none call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000) contains subroutine Hamming(first, last) integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_integer), allocatable :: hnums(:) if(present(last)) then lim = last else lim = first end if if(first < 1 .or. lim > 2500000 ) then write(*,*) "Invalid input" return end if allocate(hnums(lim)) i2 = 1 ; i3 = 1 ; i5 = 1 hnums(1) = 1 n = 1 do while(n < lim) n = n + 1 hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5)) if(2*hnums(i2) == hnums(n)) i2 = i2 + 1 if(3*hnums(i3) == hnums(n)) i3 = i3 + 1 if(5*hnums(i5) == hnums(n)) i5 = i5 + 1 end do if(present(last)) then do i = first, last call print_big(hnums(i)) write(*, "(a)", advance="no") " " end do else call print_big(hnums(first)) end if deallocate(hnums) end subroutine function mini(a, b, c) type(big_integer) :: mini type(big_integer), intent(in) :: a, b, c if(a < b ) then if(a < c) then mini = a else mini = c end if else if(b < c) then mini = b else mini = c end if end function mini end program
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Convert the following code from Fortran to VB, ensuring the logic remains intact.
program Hamming_Test use big_integer_module implicit none call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000) contains subroutine Hamming(first, last) integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_integer), allocatable :: hnums(:) if(present(last)) then lim = last else lim = first end if if(first < 1 .or. lim > 2500000 ) then write(*,*) "Invalid input" return end if allocate(hnums(lim)) i2 = 1 ; i3 = 1 ; i5 = 1 hnums(1) = 1 n = 1 do while(n < lim) n = n + 1 hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5)) if(2*hnums(i2) == hnums(n)) i2 = i2 + 1 if(3*hnums(i3) == hnums(n)) i3 = i3 + 1 if(5*hnums(i5) == hnums(n)) i5 = i5 + 1 end do if(present(last)) then do i = first, last call print_big(hnums(i)) write(*, "(a)", advance="no") " " end do else call print_big(hnums(first)) end if deallocate(hnums) end subroutine function mini(a, b, c) type(big_integer) :: mini type(big_integer), intent(in) :: a, b, c if(a < b ) then if(a < c) then mini = a else mini = c end if else if(b < c) then mini = b else mini = c end if end function mini end program
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Generate an equivalent C version of this Groovy code.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Write the same algorithm in C# as shown in this Groovy implementation.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Please provide an equivalent version of this Groovy code in C++.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Preserve the algorithm and functionality while converting the code from Groovy to Java.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Produce a functionally identical Python code for the snippet given in Groovy.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Translate this program into VB but keep the logic exactly as in Groovy.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Port the following code from Groovy to Go with equivalent syntax and logic.
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Port the provided Haskell code into C while preserving the original functionality.
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Write the same algorithm in C# as shown in this Haskell implementation.
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Translate this program into C++ but keep the logic exactly as in Haskell.
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Produce a functionally identical Java code for the snippet given in Haskell.
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Can you help me rewrite this code in Python instead of Haskell, keeping it the same logically?
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Generate an equivalent VB version of this Haskell code.
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Can you help me rewrite this code in Go instead of Haskell, keeping it the same logically?
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Transform the following J implementation into C, maintaining the same output and logic.
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Preserve the algorithm and functionality while converting the code from J to C#.
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Produce a functionally identical Java code for the snippet given in J.
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Port the following code from J to Python with equivalent syntax and logic.
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Write the same code in VB as shown below in J.
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub
Convert this J snippet to Go and keep its semantics consistent.
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
Keep all operations the same but rewrite the snippet in C.
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) if 2ham[base2] <= x base2 += 1 end if 3ham[base3] <= x base3 += 1 end if 5ham[base5] <= x base5 += 1 end end ham end println(hammingsequence(20)) println(hammingsequence(1691)[end]) println(hammingsequence(1000000)[end])
#include <stdio.h> #include <stdlib.h> typedef unsigned long long ham; size_t alloc = 0, n = 1; ham *q = 0; void qpush(ham h) { int i, j; if (alloc <= n) { alloc = alloc ? alloc * 2 : 16; q = realloc(q, sizeof(ham) * alloc); } for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j); q[i] = h; } ham qpop() { int i, j; ham r, t; for (r = q[1]; n > 1 && r == q[1]; q[i] = t) { for (i = 1, t = q[--n]; (j = i * 2) < n;) { if (j + 1 < n && q[j] > q[j+1]) j++; if (t <= q[j]) break; q[i] = q[j], i = j; } } return r; } int main() { int i; ham h; for (qpush(i = 1); i <= 1691; i++) { h = qpop(); qpush(h * 2); qpush(h * 3); qpush(h * 5); if (i <= 20 || i == 1691) printf("%6d: %llu\n", i, h); } return 0; }
Please provide an equivalent version of this Julia code in C#.
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) if 2ham[base2] <= x base2 += 1 end if 3ham[base3] <= x base3 += 1 end if 5ham[base5] <= x base5 += 1 end end ham end println(hammingsequence(20)) println(hammingsequence(1691)[end]) println(hammingsequence(1000000)[end])
using System; using System.Numerics; using System.Linq; namespace Hamming { class MainClass { public static BigInteger Hamming(int n) { BigInteger two = 2, three = 3, five = 5; var h = new BigInteger[n]; h[0] = 1; BigInteger x2 = 2, x3 = 3, x5 = 5; int i = 0, j = 0, k = 0; for (int index = 1; index < n; index++) { h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5)); if (h[index] == x2) x2 = two * h[++i]; if (h[index] == x3) x3 = three * h[++j]; if (h[index] == x5) x5 = five * h[++k]; } return h[n - 1]; } public static void Main(string[] args) { Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x)))); Console.WriteLine(Hamming(1691)); Console.WriteLine(Hamming(1000000)); } } }
Transform the following Julia implementation into C++, maintaining the same output and logic.
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) if 2ham[base2] <= x base2 += 1 end if 3ham[base3] <= x base3 += 1 end if 5ham[base5] <= x base5 += 1 end end ham end println(hammingsequence(20)) println(hammingsequence(1691)[end]) println(hammingsequence(1000000)[end])
#include <iostream> #include <vector> class Ham { private: std::vector<unsigned int> _H, _hp, _hv, _x; public: bool operator!=(const Ham& other) const {return true;} Ham begin() const {return *this;} Ham end() const {return *this;} unsigned int operator*() const {return _x.back();} Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){} const Ham& operator++() { for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]); _x.push_back(_hv[0]); for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i]; return *this; } };
Preserve the algorithm and functionality while converting the code from Julia to Java.
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) if 2ham[base2] <= x base2 += 1 end if 3ham[base3] <= x base3 += 1 end if 5ham[base5] <= x base5 += 1 end end ham end println(hammingsequence(20)) println(hammingsequence(1691)[end]) println(hammingsequence(1000000)[end])
import java.math.BigInteger; import java.util.PriorityQueue; final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5); private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); } public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; } public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
Produce a language-to-language conversion: from Julia to Python, same semantics.
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) if 2ham[base2] <= x base2 += 1 end if 3ham[base3] <= x base3 += 1 end if 5ham[base5] <= x base5 += 1 end end ham end println(hammingsequence(20)) println(hammingsequence(1691)[end]) println(hammingsequence(1000000)[end])
from itertools import islice def hamming2(): h = 1 _h=[h] multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] yield h
Translate the given Julia code snippet into VB without altering its behavior.
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) if 2ham[base2] <= x base2 += 1 end if 3ham[base3] <= x base3 += 1 end if 5ham[base5] <= x base5 += 1 end end ham end println(hammingsequence(20)) println(hammingsequence(1691)[end]) println(hammingsequence(1000000)[end])
Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer Public hn(2) As Integer Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function log10(x As Double) As Double log10 = WorksheetFunction.log10(x) End Function Private Function pow(x As Variant, y As Variant) As Double pow = WorksheetFunction.Power(x, y) End Function Private Sub init(N As Long) Dim k As Double k = log10(2) * log10(3) * log10(5) * 6 * N k = pow(k, 1 / 3) a = k / log10(2) b = k / log10(3) c = k / log10(5) p = -b * c q = -a * c r = -a * b End Sub Private Function x_given_y_z(y As Integer, z As Integer) As Double x_given_y_z = -(q * y + r * z + a * b * c) / p End Function Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5)) End Function Private Function count(N As Long, step As Integer) As Long Dim M As Long, j As Integer, k As Integer If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1) M = 0: j = 0: k = 0 Do While -c * j - b * k + b * c > 0 Do While -c * j - b * k + b * c > 0 Select Case step Case 1: M = M + Int(x_given_y_z(j, k)) Case 2 cnt(j, k) = Int(x_given_y_z(j, k)) Case 3 If Int(x_given_y_z(j, k)) < cnt(j, k) Then If cmp(cnt(j, k), j, k, hn) Then hn(0) = cnt(j, k) hn(1) = j hn(2) = k End If End If End Select k = k + 1 Loop k = 0 j = j + 1 Loop count = M End Function Private Sub list_upto(ByVal N As Integer) Dim count As Integer count = 1 Dim hn As Integer hn = 1 Do While count < N k = hn Do While k Mod 2 = 0 k = k / 2 Loop Do While k Mod 3 = 0 k = k / 3 Loop Do While k Mod 5 = 0 k = k / 5 Loop If k = 1 Then Debug.Print hn; " "; count = count + 1 End If hn = hn + 1 Loop Debug.Print End Sub Private Function find_seed(N As Long, step As Integer) As Long Dim initial As Long, total As Long initial = N Do init initial total = count(initial, step) initial = initial + N - total Loop Until total = N find_seed = initial End Function Private Sub find_hn(N As Long) Dim fs As Long, err As Long fs = find_seed(N, 1) init fs err = count(fs, 2) init fs - 1 err = count(fs - 1, 3) Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "="; If N < 1692 Then Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2)) Else Debug.Print If N <= 1000000 Then If hn(0) - 1 < hn(2) Then Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0") Else Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0") End If End If End If End Sub Public Sub main() Dim start_time As Long, finis_time As Long start_time = GetTickCount Debug.Print "The first twenty Hamming numbers are:" list_upto 20 Debug.Print "Hamming number 1691 is: "; find_hn 1691 Debug.Print "Hamming number 1000000 is: "; find_hn 1000000 finis_time = GetTickCount Debug.Print "Execution time"; (finis_time - start_time); " milliseconds" End Sub