Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in Go as shown below in Julia. | 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])
| 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])
}
|
Maintain the same structure and functionality when rewriting this code in C. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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;
}
|
Rewrite the snippet below in C# so it works the same as the original Lua code. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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));
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Lua. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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;
}
};
|
Convert this Lua block to Java, preserving its control flow and logic. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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));
}
}
|
Translate the given Lua code snippet into Python without altering its behavior. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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
|
Transform the following Lua implementation into VB, maintaining the same output and logic. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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
|
Transform the following Lua implementation into Go, maintaining the same output and logic. | function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(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])
}
|
Rewrite this program in C while keeping its functionality equivalent to the Mathematica version. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
| #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;
}
|
Change the programming language of this snippet from Mathematica to C# without modifying what it does. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
| 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));
}
}
}
|
Port the provided Mathematica code into C++ while preserving the original functionality. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
| #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;
}
};
|
Translate the given Mathematica code snippet into Java without altering its behavior. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
| 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 Mathematica version. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
| 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 a VB translation of this Mathematica snippet without changing its computational steps. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
|
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. | HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
| 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])
}
|
Can you help me rewrite this code in C instead of MATLAB, keeping it the same logically? | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
| #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 MATLAB to C#, same semantics. | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
| 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));
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
| #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 MATLAB code. | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
| 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));
}
}
|
Keep all operations the same but rewrite the snippet in Python. | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
| 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 MATLAB, keeping it the same logically? | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
|
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 Go version of this MATLAB code. | n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
| 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 the snippet below in C so it works the same as the original Nim code. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
| #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 Nim code. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
| 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));
}
}
}
|
Port the following code from Nim to C++ with equivalent syntax and logic. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
| #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 Nim block to Java, preserving its control flow and logic. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
| 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 the given Nim code snippet into Python without altering its behavior. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
| 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 this Nim block to VB, preserving its control flow and logic. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
|
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
|
Transform the following Nim implementation into Go, maintaining the same output and logic. | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = initBigInt(1)
for n in 1 ..< limit:
h[n] = min(x2, x3, x5)
if x2 == h[n]:
inc i
x2 = h[i] * 2
if x3 == h[n]:
inc j
x3 = h[j] * 3
if x5 == h[n]:
inc k
x5 = h[k] * 5
result = h[h.high]
for i in 1 .. 20:
stdout.write hamming(i), " "
echo ""
echo hamming(1691)
echo hamming(1_000_000)
| 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 OCaml implementation into C, maintaining the same output and logic. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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;
}
|
Convert this OCaml block to C#, preserving its control flow and logic. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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));
}
}
}
|
Port the provided OCaml code into C++ while preserving the original functionality. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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;
}
};
|
Port the following code from OCaml to Java with equivalent syntax and logic. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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));
}
}
|
Translate this program into Python but keep the logic exactly as in OCaml. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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
|
Port the following code from OCaml to VB with equivalent syntax and logic. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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
|
Generate an equivalent Go version of this OCaml code. | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (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])
}
|
Preserve the algorithm and functionality while converting the code from Pascal to C. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
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;
}
|
Generate a C# translation of this Pascal snippet without changing its computational steps. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
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));
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Pascal version. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
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 Pascal to Java. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
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));
}
}
|
Ensure the translated Python code behaves exactly like the original Pascal snippet. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
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
|
Write the same algorithm in VB as shown in this Pascal implementation. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
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
|
Generate an equivalent Go version of this Pascal code. | program HammNumb;
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
while NOT(ODD(nr)) do
begin
inc(p);
nr := nr div 2;
end;
Pot[0]:= p;
p := 0;
q := nr div 3;
while q*3=nr do
Begin
inc(P);
nr := q;
q := nr div 3;
end;
Pot[1] := p;
p := 0;
q := nr div 5;
while q*5=nr do
Begin
inc(P);
nr := q;
q := nr div 5;
end;
Pot[2] := p;
until nr = 1;
result:= n;
end;
procedure Check;
var
i,n: NativeUint;
begin
n := 1;
for i := 1 to 20 do
begin
n := NextHammNumb(n);
write(n,' ');
end;
writeln;
writeln;
n := 1;
for i := 1 to 1690 do
n := NextHammNumb(n);
writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]);
end;
Begin
Check;
End.
| 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])
}
|
Ensure the translated C code behaves exactly like the original Perl snippet. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
| #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;
}
|
Translate this program into C# but keep the logic exactly as in Perl. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
| 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));
}
}
}
|
Port the following code from Perl to C++ with equivalent syntax and logic. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
| #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;
}
};
|
Port the provided Perl code into Java while preserving the original functionality. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
| 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 Perl to Python, same semantics. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
| 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
|
Ensure the translated VB code behaves exactly like the original Perl snippet. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
|
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 Perl. | use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n";
| 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])
}
|
Ensure the translated C code behaves exactly like the original R snippet. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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;
}
|
Translate the given R code snippet into C# without altering its behavior. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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));
}
}
}
|
Convert the following code from R to C++, ensuring the logic remains intact. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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;
}
};
|
Rewrite this program in Java while keeping its functionality equivalent to the R version. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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));
}
}
|
Write a version of this R function in Python with identical behavior. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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
|
Convert the following code from R to VB, ensuring the logic remains intact. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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
|
Please provide an equivalent version of this R code in Go. | hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(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])
}
|
Transform the following REXX implementation into C, maintaining the same output and logic. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
| #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 REXX to C#. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
| 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 the given REXX code snippet into C++ without altering its behavior. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
| #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 REXX function in Java with identical behavior. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
| 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 REXX. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
| 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 algorithm in VB as shown in this REXX implementation. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
|
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. |
numeric digits 100
call hamming 1, 20
call hamming 1691
call hamming 1000000
exit
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5)
if 2*@.#2 == @.n then #2= #2 + 1
if 3*@.#3 == @.n then #3= #3 + 1
if 5*@.#5 == @.n then #5= #5 + 1
end
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end
say right( 'length of last Hamming number =' length(@.y), 70); say
return
| 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 Ruby implementation into C, maintaining the same output and logic. | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
| #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 Ruby implementation into C#, maintaining the same output and logic. | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
| 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 the snippet below in C++ so it works the same as the original Ruby code. | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
| #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;
}
};
|
Maintain the same structure and functionality when rewriting this code in Java. | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
| 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));
}
}
|
Keep all operations the same but rewrite the snippet in Python. | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
| 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 Ruby, keeping it the same logically? | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
|
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 Ruby snippet to Go and keep its semantics consistent. | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h[n]
x3 = 3 * h[j += 1] if x3 == h[n]
x5 = 5 * h[k += 1] if x5 == h[n]
end
h[limit - 1]
end
start = Time.monotonic
print "Hamming Number (1..20): "; (1..20).each { |i| print "
puts
puts "Hamming Number 1691:
puts "Hamming Number 1,000,000:
puts "Elasped Time:
| 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 Scala code into C while preserving the original functionality. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
| #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 a C# translation of this Scala snippet without changing its computational steps. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
| 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));
}
}
}
|
Port the following code from Scala to C++ with equivalent syntax and logic. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
| #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 Scala snippet to Java and keep its semantics consistent. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
| 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));
}
}
|
Please provide an equivalent version of this Scala code in Python. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
| 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
|
Change the programming language of this snippet from Scala to VB without modifying what it does. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
|
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
|
Ensure the translated Go code behaves exactly like the original Scala snippet. | import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
| 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 Tcl code into C while preserving the original functionality. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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;
}
|
Produce a language-to-language conversion: from Tcl to C#, same semantics. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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));
}
}
}
|
Convert this Tcl block to C++, preserving its control flow and logic. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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;
}
};
|
Produce a language-to-language conversion: from Tcl to Java, same semantics. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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));
}
}
|
Port the provided Tcl code into Python while preserving the original functionality. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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
|
Produce a language-to-language conversion: from Tcl to VB, same semantics. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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
|
Convert this Tcl snippet to Go and keep its semantics consistent. | package require Tcl 8.6
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
if {[yield $n] == $n} {
incr i
}
}
}
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
coroutine hamming hammingCore 2 3 5
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $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])
}
|
Can you help me rewrite this code in Rust instead of C, keeping it the same logically? | #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;
}
| extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
|
Produce a functionally identical Rust code for the snippet given in Java. | 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));
}
}
| extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
|
Translate the given Go code snippet into Rust without altering its behavior. | 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])
}
| extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
|
Can you help me rewrite this code in Python instead of Rust, keeping it the same logically? | extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
| 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 Rust code. | extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
|
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
|
Preserve the algorithm and functionality while converting the code from C++ to Rust. | #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;
}
};
| extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
|
Port the provided C# code into Rust while preserving the original functionality. | 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));
}
}
}
| extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
let (cs, r1) = if y == z { (0x6, y) }
else if y < z { (2, y) } else { (4, z) };
if x == r1 { (cs | 1, x.clone()) }
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
}
let mut c = 1;
while c < n {
let (cs, e1) = { min3(&x2, &x3, &x5) };
h[c] = e1;
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
c += 1;
}
match h.pop() {
Some(v) => v,
_ => panic!("basic_hamming: arg is zero; no elements")
}
}
fn main() {
print!("[");
for (i, h) in (1..21).map(basic_hamming).enumerate() {
if i != 0 { print!(",") }
print!(" {}", h)
}
println!(" ]");
println!("{}", basic_hamming(1691));
let strt = Instant::now();
let rslt = basic_hamming(1000000);
let elpsd = strt.elapsed();
let secs = elpsd.as_secs();
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
let dur = secs * 1000 + millis;
let rs = rslt.to_str_radix(10);
let mut s = rs.as_str();
println!("{} digits:", s.len());
while s.len() > 100 {
let (f, r) = s.split_at(100);
s = r;
println!("{}", f);
}
println!("{}", s);
println!("This last took {} milliseconds", dur);
}
|
Convert this Ada snippet to C# and keep its semantics consistent. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| namespace Algorithms
{
using System;
using System.Collections.Generic;
using System.Linq;
public class TopologicalSorter<ValueType>
{
private class Relations
{
public int Dependencies = 0;
public HashSet<ValueType> Dependents = new HashSet<ValueType>();
}
private Dictionary<ValueType, Relations> _map = new Dictionary<ValueType, Relations>();
public void Add(ValueType obj)
{
if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());
}
public void Add(ValueType obj, ValueType dependency)
{
if (dependency.Equals(obj)) return;
if (!_map.ContainsKey(dependency)) _map.Add(dependency, new Relations());
var dependents = _map[dependency].Dependents;
if (!dependents.Contains(obj))
{
dependents.Add(obj);
if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());
++_map[obj].Dependencies;
}
}
public void Add(ValueType obj, IEnumerable<ValueType> dependencies)
{
foreach (var dependency in dependencies) Add(obj, dependency);
}
public void Add(ValueType obj, params ValueType[] dependencies)
{
Add(obj, dependencies as IEnumerable<ValueType>);
}
public Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>> Sort()
{
List<ValueType> sorted = new List<ValueType>(), cycled = new List<ValueType>();
var map = _map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
sorted.AddRange(map.Where(kvp => kvp.Value.Dependencies == 0).Select(kvp => kvp.Key));
for (int idx = 0; idx < sorted.Count; ++idx) sorted.AddRange(map[sorted[idx]].Dependents.Where(k => --map[k].Dependencies == 0));
cycled.AddRange(map.Where(kvp => kvp.Value.Dependencies != 0).Select(kvp => kvp.Key));
return new Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>>(sorted, cycled);
}
public void Clear()
{
_map.Clear();
}
}
}
namespace ExampleApplication
{
using Algorithms;
using System;
using System.Collections.Generic;
using System.Linq;
public class Task
{
public string Message;
}
class Program
{
static void Main(string[] args)
{
List<Task> tasks = new List<Task>
{
new Task{ Message = "A - depends on B and C" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
var result = resolver.Sort();
var sorted = result.Item1;
var cycled = result.Item2;
if (!cycled.Any())
{
foreach (var d in sorted) Console.WriteLine(d.Message);
}
else
{
Console.Write("Cycled dependencies detected: ");
foreach (var d in cycled) Console.Write($"{d.Message[0]} ");
Console.WriteLine();
}
Console.WriteLine("exiting...");
}
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the Ada version. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Port the provided Ada code into C++ while preserving the original functionality. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Please provide an equivalent version of this Ada code in Go. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Write a version of this Ada function in Java with identical behavior. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Produce a language-to-language conversion: from Ada to Python, same semantics. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| try:
from functools import reduce
except:
pass
data = {
'des_system_lib': set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),
'dw01': set('ieee dw01 dware gtech'.split()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Transform the following Ada implementation into VB, maintaining the same output and logic. | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
type Graph_Type is tagged private;
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
package Node_Vec is new Vectors(Positive, Node_Index);
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Rewrite the snippet below in C so it works the same as the original Clojure code. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.