Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the provided VB code into C while preserving the original functionality. | Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
Debug.Print "=====AND=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print "======OR=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If Not a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print
End Sub
| #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
}
|
Change the programming language of this snippet from VB to C without modifying what it does. | Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
Debug.Print "=====AND=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print "======OR=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If Not a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print
End Sub
| #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
}
|
Change the programming language of this snippet from VB to C without modifying what it does. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
|
Convert this VB snippet to C and keep its semantics consistent. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. |
function isarit_compo(i)
cnt=0
sum=0
for j=1 to sqr(i)
if (i mod j)=0 then
k=i\j
if k=j then
cnt=cnt+1:sum=sum+j
else
cnt=cnt+2:sum=sum+j+k
end if
end if
next
avg= sum/cnt
isarit_compo= array((fix(avg)=avg),-(cnt>2))
end function
function rpad(a,n) rpad=right(space(n)&a,n) :end function
dim s1
sub print(s)
s1=s1& rpad(s,4)
if len(s1)=40 then wscript.stdout.writeline s1:s1=""
end sub
cntr=0
cntcompo=0
i=1
wscript.stdout.writeline "the first 100 arithmetic numbers are:"
do
a=isarit_compo(i)
if a(0) then
cntcompo=cntcompo+a(1)
cntr=cntr+1
if cntr<=100 then print i
if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do
end if
i=i+1
loop
| #include <stdio.h>
void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
unsigned int* psum) {
unsigned int divisor_count = 1;
unsigned int divisor_sum = 1;
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
++divisor_count;
divisor_sum += power;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1, sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
++count;
sum += power;
}
divisor_count *= count;
divisor_sum *= sum;
}
if (n > 1) {
divisor_count *= 2;
divisor_sum *= n + 1;
}
*pcount = divisor_count;
*psum = divisor_sum;
}
int main() {
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, &divisor_count, &divisor_sum);
if (divisor_sum % divisor_count != 0)
continue;
++arithmetic_count;
if (divisor_count > 2)
++composite_count;
if (arithmetic_count <= 100) {
printf("%3u ", n);
if (arithmetic_count % 10 == 0)
printf("\n");
}
if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
arithmetic_count == 100000 || arithmetic_count == 1000000) {
printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
printf("Number of composite arithmetic numbers <= %u: %u\n", n,
composite_count);
}
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. |
function isarit_compo(i)
cnt=0
sum=0
for j=1 to sqr(i)
if (i mod j)=0 then
k=i\j
if k=j then
cnt=cnt+1:sum=sum+j
else
cnt=cnt+2:sum=sum+j+k
end if
end if
next
avg= sum/cnt
isarit_compo= array((fix(avg)=avg),-(cnt>2))
end function
function rpad(a,n) rpad=right(space(n)&a,n) :end function
dim s1
sub print(s)
s1=s1& rpad(s,4)
if len(s1)=40 then wscript.stdout.writeline s1:s1=""
end sub
cntr=0
cntcompo=0
i=1
wscript.stdout.writeline "the first 100 arithmetic numbers are:"
do
a=isarit_compo(i)
if a(0) then
cntcompo=cntcompo+a(1)
cntr=cntr+1
if cntr<=100 then print i
if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do
end if
i=i+1
loop
| #include <stdio.h>
void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
unsigned int* psum) {
unsigned int divisor_count = 1;
unsigned int divisor_sum = 1;
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
++divisor_count;
divisor_sum += power;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1, sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
++count;
sum += power;
}
divisor_count *= count;
divisor_sum *= sum;
}
if (n > 1) {
divisor_count *= 2;
divisor_sum *= n + 1;
}
*pcount = divisor_count;
*psum = divisor_sum;
}
int main() {
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, &divisor_count, &divisor_sum);
if (divisor_sum % divisor_count != 0)
continue;
++arithmetic_count;
if (divisor_count > 2)
++composite_count;
if (arithmetic_count <= 100) {
printf("%3u ", n);
if (arithmetic_count % 10 == 0)
printf("\n");
}
if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
arithmetic_count == 100000 || arithmetic_count == 1000000) {
printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
printf("Number of composite arithmetic numbers <= %u: %u\n", n,
composite_count);
}
}
return 0;
}
|
Can you help me rewrite this code in C instead of VB, keeping it the same logically? |
function isarit_compo(i)
cnt=0
sum=0
for j=1 to sqr(i)
if (i mod j)=0 then
k=i\j
if k=j then
cnt=cnt+1:sum=sum+j
else
cnt=cnt+2:sum=sum+j+k
end if
end if
next
avg= sum/cnt
isarit_compo= array((fix(avg)=avg),-(cnt>2))
end function
function rpad(a,n) rpad=right(space(n)&a,n) :end function
dim s1
sub print(s)
s1=s1& rpad(s,4)
if len(s1)=40 then wscript.stdout.writeline s1:s1=""
end sub
cntr=0
cntcompo=0
i=1
wscript.stdout.writeline "the first 100 arithmetic numbers are:"
do
a=isarit_compo(i)
if a(0) then
cntcompo=cntcompo+a(1)
cntr=cntr+1
if cntr<=100 then print i
if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do
end if
i=i+1
loop
| #include <stdio.h>
void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
unsigned int* psum) {
unsigned int divisor_count = 1;
unsigned int divisor_sum = 1;
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
++divisor_count;
divisor_sum += power;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1, sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
++count;
sum += power;
}
divisor_count *= count;
divisor_sum *= sum;
}
if (n > 1) {
divisor_count *= 2;
divisor_sum *= n + 1;
}
*pcount = divisor_count;
*psum = divisor_sum;
}
int main() {
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, &divisor_count, &divisor_sum);
if (divisor_sum % divisor_count != 0)
continue;
++arithmetic_count;
if (divisor_count > 2)
++composite_count;
if (arithmetic_count <= 100) {
printf("%3u ", n);
if (arithmetic_count % 10 == 0)
printf("\n");
}
if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
arithmetic_count == 100000 || arithmetic_count == 1000000) {
printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
printf("Number of composite arithmetic numbers <= %u: %u\n", n,
composite_count);
}
}
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the VB version. | Imports System.Drawing.Imaging
Public Class frmSnowExercise
Dim bRunning As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
Show()
Activate()
Application.DoEvents()
RenderLoop()
Close()
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub RenderLoop()
Const cfPadding As Single = 5.0F
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
g.Clear(Color.Black)
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
Do
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
iLoops += 1
If fElapsed >= 1.0F Then
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F
iLoops = 0
End If
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
oPixels.Length)
b.UnlockBits(oBMPData)
g.FillRectangle(Brushes.Black, oFPSBG)
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
BackgroundImage = b
Invalidate(ClientRectangle)
Application.DoEvents()
Loop While bRunning
End Sub
End Class
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL/SDL.h>
unsigned int frames = 0;
unsigned int t_acc = 0;
void print_fps ()
{
static Uint32 last_t = 0;
Uint32 t = SDL_GetTicks();
Uint32 dt = t - last_t;
t_acc += dt;
if (t_acc > 1000)
{
unsigned int el_time = t_acc / 1000;
printf("- fps: %g\n",
(float) frames / (float) el_time);
t_acc = 0;
frames = 0;
}
last_t = t;
}
void blit_noise(SDL_Surface *surf)
{
unsigned int i;
long dim = surf->w * surf->h;
while (1)
{
SDL_LockSurface(surf);
for (i=0; i < dim; ++i) {
((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);
}
SDL_UnlockSurface(surf);
SDL_Flip(surf);
++frames;
print_fps();
}
}
int main(void)
{
SDL_Surface *surf = NULL;
srand((unsigned int)time(NULL));
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}
|
Change the programming language of this snippet from VB to C without modifying what it does. | Imports System.Drawing.Imaging
Public Class frmSnowExercise
Dim bRunning As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
Show()
Activate()
Application.DoEvents()
RenderLoop()
Close()
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub RenderLoop()
Const cfPadding As Single = 5.0F
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
g.Clear(Color.Black)
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
Do
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
iLoops += 1
If fElapsed >= 1.0F Then
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F
iLoops = 0
End If
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
oPixels.Length)
b.UnlockBits(oBMPData)
g.FillRectangle(Brushes.Black, oFPSBG)
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
BackgroundImage = b
Invalidate(ClientRectangle)
Application.DoEvents()
Loop While bRunning
End Sub
End Class
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL/SDL.h>
unsigned int frames = 0;
unsigned int t_acc = 0;
void print_fps ()
{
static Uint32 last_t = 0;
Uint32 t = SDL_GetTicks();
Uint32 dt = t - last_t;
t_acc += dt;
if (t_acc > 1000)
{
unsigned int el_time = t_acc / 1000;
printf("- fps: %g\n",
(float) frames / (float) el_time);
t_acc = 0;
frames = 0;
}
last_t = t;
}
void blit_noise(SDL_Surface *surf)
{
unsigned int i;
long dim = surf->w * surf->h;
while (1)
{
SDL_LockSurface(surf);
for (i=0; i < dim; ++i) {
((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);
}
SDL_UnlockSurface(surf);
SDL_Flip(surf);
++frames;
print_fps();
}
}
int main(void)
{
SDL_Surface *surf = NULL;
srand((unsigned int)time(NULL));
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}
|
Rewrite the snippet below in C so it works the same as the original VB code. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
| #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0));
printf("Prompt again [Y/N]? ");
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf("\n");
continue;
}
if (c == 'N' || c == 'n') {
printf("\nDone\n");
break;
}
printf("\nYes or no?\n");
}
return 0;
}
|
Produce a language-to-language conversion: from VB to C, same semantics. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
| #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0));
printf("Prompt again [Y/N]? ");
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf("\n");
continue;
}
if (c == 'N' || c == 'n') {
printf("\nDone\n");
break;
}
printf("\nYes or no?\n");
}
return 0;
}
|
Convert this VB block to C, preserving its control flow and logic. | Private Function Factors(x As Long) As String
Application.Volatile
Dim i As Long
Dim cooresponding_factors As String
Factors = 1
corresponding_factors = x
For i = 2 To Sqr(x)
If x Mod i = 0 Then
Factors = Factors & ", " & i
If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors
End If
Next i
If x <> 1 Then Factors = Factors & ", " & corresponding_factors
End Function
Private Function is_perfect(n As Long)
fs = Split(Factors(n), ", ")
Dim f() As Long
ReDim f(UBound(fs))
For i = 0 To UBound(fs)
f(i) = Val(fs(i))
Next i
is_perfect = WorksheetFunction.Sum(f) - n = n
End Function
Public Sub main()
Dim i As Long
For i = 2 To 100000
If is_perfect(i) Then Debug.Print i
Next i
End Sub
| #include "stdio.h"
#include "math.h"
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;
}
int main() {
int n;
for (n = 2; n < 33550337; n++)
if (perfect(n))
printf("%d\n", n);
return 0;
}
|
Produce a language-to-language conversion: from VB to C, same semantics. | Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
ReDim poles(WorksheetFunction.Max(a))
For i = 1 To UBound(a)
For j = 1 To a(i)
poles(j) = poles(j) + 1
Next j
Next i
For j = 1 To UBound(a)
a(j) = 0
Next j
For i = 1 To UBound(poles)
For j = 1 To poles(i)
a(j) = a(j) + 1
Next j
Next i
beadsort = a
End Function
Public Sub main()
Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub
| #include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
for (i = 0; i < len; i++)
for (j = 0; j < a[i]; j++)
BEAD(i, j) = 1;
for (j = 0; j < max; j++) {
for (sum = i = 0; i < len; i++) {
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
for (i = len - sum; i < len; i++) BEAD(i, j) = 1;
}
for (i = 0; i < len; i++) {
for (j = 0; j < max && BEAD(i, j); j++);
a[i] = j;
}
free(beads);
}
int main()
{
int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(x)/sizeof(x[0]);
bead_sort(x, len);
for (i = 0; i < len; i++)
printf("%d\n", x[i]);
return 0;
}
|
Ensure the translated C code behaves exactly like the original VB snippet. | Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
ReDim poles(WorksheetFunction.Max(a))
For i = 1 To UBound(a)
For j = 1 To a(i)
poles(j) = poles(j) + 1
Next j
Next i
For j = 1 To UBound(a)
a(j) = 0
Next j
For i = 1 To UBound(poles)
For j = 1 To poles(i)
a(j) = a(j) + 1
Next j
Next i
beadsort = a
End Function
Public Sub main()
Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub
| #include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
for (i = 0; i < len; i++)
for (j = 0; j < a[i]; j++)
BEAD(i, j) = 1;
for (j = 0; j < max; j++) {
for (sum = i = 0; i < len; i++) {
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
for (i = len - sum; i < len; i++) BEAD(i, j) = 1;
}
for (i = 0; i < len; i++) {
for (j = 0; j < max && BEAD(i, j); j++);
a[i] = j;
}
free(beads);
}
int main()
{
int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(x)/sizeof(x[0]);
bead_sort(x, len);
for (i = 0; i < len; i++)
printf("%d\n", x[i]);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from VB to C. | Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim Implems() As String = {"Built-In", "Recursive", "Iterative"},
powers() As Integer = {5, 4, 3, 2}
Function intPowR(val As BI, exp As BI) As BI
If exp = 0 Then Return 1
Dim ne As BI, vs As BI = val * val
If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)
ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val
End Function
Function intPowI(val As BI, exp As BI) As BI
intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val
val *= val : exp >>= 1 : End While
End Function
Sub DoOne(title As String, p() As Integer)
Dim st As DateTime = DateTime.Now, res As BI, resStr As String
Select Case (Array.IndexOf(Implems, title))
Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))
Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))
Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))
End Select : resStr = res.ToString()
Dim et As TimeSpan = DateTime.Now - st
Debug.Assert(resStr.Length = 183231)
Debug.Assert(resStr.StartsWith("62060698786608744707"))
Debug.Assert(resStr.EndsWith("92256259918212890625"))
WriteLine("n = {0}", String.Join("^", powers))
WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20))
WriteLine("n digits = {0}", resStr.Length)
WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds)
End Sub
Sub Main()
For Each itm As String in Implems : DoOne(itm, powers) : Next
If Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module
| #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18);
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from VB to C. | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
}
|
Convert this VB snippet to C and keep its semantics consistent. | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the VB version. | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Generate a C translation of this VB snippet without changing its computational steps. | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Produce a language-to-language conversion: from VB to C, same semantics. | Public Sub LoopsBreak()
Dim value As Integer
Randomize
Do While True
value = Int(20 * Rnd)
Debug.Print value
If value = 10 Then Exit Do
Debug.Print Int(20 * Rnd)
Loop
End Sub
| int main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
}
|
Produce a language-to-language conversion: from VB to C, same semantics. |
Module Module1
Sub Main(Args() As String)
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1
Dim wta As Integer()() = {
New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
Dim blk As String,
lf As String = vbLf,
tb = "██", wr = "≈≈", mt = " "
For i As Integer = 0 To wta.Length - 1
Dim bpf As Integer
blk = ""
Do
bpf = 0 : Dim floor As String = ""
For j As Integer = 0 To wta(i).Length - 1
If wta(i)(j) > 0 Then
floor &= tb : wta(i)(j) -= 1 : bpf += 1
Else
floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)
End If
Next
If bpf > 0 Then blk = floor & lf & blk
Loop Until bpf = 0
While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While
While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While
If shoTow Then Console.Write("{0}{1}", lf, blk)
Console.Write("Block {0} retains {1,2} water units.{2}", i + 1,
(blk.Length - blk.Replace(wr, "").Length) \ 2, lf)
Next
End Sub
End Module
| #include<stdlib.h>
#include<stdio.h>
int getWater(int* arr,int start,int end,int cutoff){
int i, sum = 0;
for(i=start;i<=end;i++)
sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);
return sum;
}
int netWater(int* arr,int size){
int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;
if(size<3)
return 0;
for(i=0;i<size-1;i++){
start:if(i!=size-2 && arr[i]>arr[i+1]){
ref1 = i;
for(j=ref1+1;j<size;j++){
if(arr[j]>=arr[ref1]){
ref2 = j;
sum += getWater(arr,ref1+1,ref2-1,ref1);
i = ref2;
goto start;
}
else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){
marker = j+1;
markerSet = 1;
}
}
if(markerSet==1){
sum += getWater(arr,ref1+1,marker-1,marker);
i = marker;
markerSet = 0;
goto start;
}
}
}
return sum;
}
int main(int argC,char* argV[])
{
int *arr,i;
if(argC==1)
printf("Usage : %s <followed by space separated series of integers>");
else{
arr = (int*)malloc((argC-1)*sizeof(int));
for(i=1;i<argC;i++)
arr[i-1] = atoi(argV[i]);
printf("Water collected : %d",netWater(arr,argC-1));
}
return 0;
}
|
Convert this VB block to C, preserving its control flow and logic. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
typedef unsigned char bool;
typedef unsigned long long uint64;
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool));
primes[0] = 2;
count = 1;
p = 3;
for (;;) {
p2 = p * p;
if (p2 > limit) break;
for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;
for (;;) {
p += 2;
if (!c[p]) break;
}
}
for (i = 3; i <= limit; i += 2) {
if (!c[i]) primes[count++] = i;
}
*length = count;
free(c);
}
void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
uint64 *primes = malloc((limit + 1) * sizeof(uint64));
bool add;
sieve(limit, primes, &np);
for (i = from; i <= to; ++i) {
add = TRUE;
for (j = 0; j < np; ++j) {
p = primes[j];
p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) {
add = FALSE;
break;
}
}
if (add) results[count++] = i;
}
*len = count;
free(primes);
}
int main() {
uint64 i, *sf, len;
sf = malloc(1000000 * sizeof(uint64));
printf("Square-free integers from 1 to 145:\n");
squareFree(1, 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 20 == 0) {
printf("\n");
}
printf("%4lld", sf[i]);
}
printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145);
squareFree(TRILLION, TRILLION + 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 5 == 0) {
printf("\n");
}
printf("%14lld", sf[i]);
}
printf("\n\nNumber of square-free integers:\n");
int a[5] = {100, 1000, 10000, 100000, 1000000};
for (i = 0; i < 5; ++i) {
squareFree(1, a[i], sf, &len);
printf(" from %d to %d = %lld\n", 1, a[i], len);
}
free(sf);
return 0;
}
|
Convert the following code from VB to C, ensuring the logic remains intact. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
typedef unsigned char bool;
typedef unsigned long long uint64;
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool));
primes[0] = 2;
count = 1;
p = 3;
for (;;) {
p2 = p * p;
if (p2 > limit) break;
for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;
for (;;) {
p += 2;
if (!c[p]) break;
}
}
for (i = 3; i <= limit; i += 2) {
if (!c[i]) primes[count++] = i;
}
*length = count;
free(c);
}
void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
uint64 *primes = malloc((limit + 1) * sizeof(uint64));
bool add;
sieve(limit, primes, &np);
for (i = from; i <= to; ++i) {
add = TRUE;
for (j = 0; j < np; ++j) {
p = primes[j];
p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) {
add = FALSE;
break;
}
}
if (add) results[count++] = i;
}
*len = count;
free(primes);
}
int main() {
uint64 i, *sf, len;
sf = malloc(1000000 * sizeof(uint64));
printf("Square-free integers from 1 to 145:\n");
squareFree(1, 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 20 == 0) {
printf("\n");
}
printf("%4lld", sf[i]);
}
printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145);
squareFree(TRILLION, TRILLION + 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 5 == 0) {
printf("\n");
}
printf("%14lld", sf[i]);
}
printf("\n\nNumber of square-free integers:\n");
int a[5] = {100, 1000, 10000, 100000, 1000000};
for (i = 0; i < 5; ++i) {
squareFree(1, a[i], sf, &len);
printf(" from %d to %d = %lld\n", 1, a[i], len);
}
free(sf);
return 0;
}
|
Write the same algorithm in C as shown in this VB implementation. | Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(text1)
s2 = Len(text2)
limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)
match1 = String(s1, dummyChar)
match2 = String(s2, dummyChar)
For l = 1 To WorksheetFunction.Min(4, s1, s2)
If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For
Next l
l = l - 1
For i = 1 To s1
f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)
t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)
j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)
If j > 0 Then
m = m + 1
text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)
match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)
match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)
End If
Next i
match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare)
match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare)
t = 0
For i = 1 To m
If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1
Next i
JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3
JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)
End Function
| #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
double jaro(const char *str1, const char *str2) {
int str1_len = strlen(str1);
int str2_len = strlen(str2);
if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;
int match_distance = (int) max(str1_len, str2_len)/2 - 1;
int *str1_matches = calloc(str1_len, sizeof(int));
int *str2_matches = calloc(str2_len, sizeof(int));
double matches = 0.0;
double transpositions = 0.0;
for (int i = 0; i < str1_len; i++) {
int start = max(0, i - match_distance);
int end = min(i + match_distance + 1, str2_len);
for (int k = start; k < end; k++) {
if (str2_matches[k]) continue;
if (str1[i] != str2[k]) continue;
str1_matches[i] = TRUE;
str2_matches[k] = TRUE;
matches++;
break;
}
}
if (matches == 0) {
free(str1_matches);
free(str2_matches);
return 0.0;
}
int k = 0;
for (int i = 0; i < str1_len; i++) {
if (!str1_matches[i]) continue;
while (!str2_matches[k]) k++;
if (str1[i] != str2[k]) transpositions++;
k++;
}
transpositions /= 2.0;
free(str1_matches);
free(str2_matches);
return ((matches / str1_len) +
(matches / str2_len) +
((matches - transpositions) / matches)) / 3.0;
}
int main() {
printf("%f\n", jaro("MARTHA", "MARHTA"));
printf("%f\n", jaro("DIXON", "DICKSONX"));
printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"));
}
|
Write a version of this VB function in C with identical behavior. | Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(text1)
s2 = Len(text2)
limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)
match1 = String(s1, dummyChar)
match2 = String(s2, dummyChar)
For l = 1 To WorksheetFunction.Min(4, s1, s2)
If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For
Next l
l = l - 1
For i = 1 To s1
f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)
t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)
j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)
If j > 0 Then
m = m + 1
text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)
match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)
match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)
End If
Next i
match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare)
match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare)
t = 0
For i = 1 To m
If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1
Next i
JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3
JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)
End Function
| #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
double jaro(const char *str1, const char *str2) {
int str1_len = strlen(str1);
int str2_len = strlen(str2);
if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;
int match_distance = (int) max(str1_len, str2_len)/2 - 1;
int *str1_matches = calloc(str1_len, sizeof(int));
int *str2_matches = calloc(str2_len, sizeof(int));
double matches = 0.0;
double transpositions = 0.0;
for (int i = 0; i < str1_len; i++) {
int start = max(0, i - match_distance);
int end = min(i + match_distance + 1, str2_len);
for (int k = start; k < end; k++) {
if (str2_matches[k]) continue;
if (str1[i] != str2[k]) continue;
str1_matches[i] = TRUE;
str2_matches[k] = TRUE;
matches++;
break;
}
}
if (matches == 0) {
free(str1_matches);
free(str2_matches);
return 0.0;
}
int k = 0;
for (int i = 0; i < str1_len; i++) {
if (!str1_matches[i]) continue;
while (!str2_matches[k]) k++;
if (str1[i] != str2[k]) transpositions++;
k++;
}
transpositions /= 2.0;
free(str1_matches);
free(str2_matches);
return ((matches / str1_len) +
(matches / str2_len) +
((matches - transpositions) / matches)) / 3.0;
}
int main() {
printf("%f\n", jaro("MARTHA", "MARHTA"));
printf("%f\n", jaro("DIXON", "DICKSONX"));
printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"));
}
|
Change the following VB code into C without altering its purpose. | Module Module1
Function Turn(base As Integer, n As Integer) As Integer
Dim sum = 0
While n <> 0
Dim re = n Mod base
n \= base
sum += re
End While
Return sum Mod base
End Function
Sub Fairshare(base As Integer, count As Integer)
Console.Write("Base {0,2}:", base)
For i = 1 To count
Dim t = Turn(base, i - 1)
Console.Write(" {0,2}", t)
Next
Console.WriteLine()
End Sub
Sub TurnCount(base As Integer, count As Integer)
Dim cnt(base) As Integer
For i = 1 To base
cnt(i - 1) = 0
Next
For i = 1 To count
Dim t = Turn(base, i - 1)
cnt(t) += 1
Next
Dim minTurn = Integer.MaxValue
Dim maxTurn = Integer.MinValue
Dim portion = 0
For i = 1 To base
Dim num = cnt(i - 1)
If num > 0 Then
portion += 1
End If
If num < minTurn Then
minTurn = num
End If
If num > maxTurn Then
maxTurn = num
End If
Next
Console.Write(" With {0} people: ", base)
If 0 = minTurn Then
Console.WriteLine("Only {0} have a turn", portion)
ElseIf minTurn = maxTurn Then
Console.WriteLine(minTurn)
Else
Console.WriteLine("{0} or {1}", minTurn, maxTurn)
End If
End Sub
Sub Main()
Fairshare(2, 25)
Fairshare(3, 25)
Fairshare(5, 25)
Fairshare(11, 25)
Console.WriteLine("How many times does each get a turn in 50000 iterations?")
TurnCount(191, 50000)
TurnCount(1377, 50000)
TurnCount(49999, 50000)
TurnCount(50000, 50000)
TurnCount(50001, 50000)
End Sub
End Module
| #include <stdio.h>
#include <stdlib.h>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
int i;
printf("Base %2d:", base);
for (i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
int *cnt = calloc(base, sizeof(int));
int i, minTurn, maxTurn, portion;
if (NULL == cnt) {
printf("Failed to allocate space to determine the spread of turns.\n");
return;
}
for (i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
minTurn = INT_MAX;
maxTurn = INT_MIN;
portion = 0;
for (i = 0; i < base; i++) {
if (cnt[i] > 0) {
portion++;
}
if (cnt[i] < minTurn) {
minTurn = cnt[i];
}
if (cnt[i] > maxTurn) {
maxTurn = cnt[i];
}
}
printf(" With %d people: ", base);
if (0 == minTurn) {
printf("Only %d have a turn\n", portion);
} else if (minTurn == maxTurn) {
printf("%d\n", minTurn);
} else {
printf("%d or %d\n", minTurn, maxTurn);
}
free(cnt);
}
int main() {
fairshare(2, 25);
fairshare(3, 25);
fairshare(5, 25);
fairshare(11, 25);
printf("How many times does each get a turn in 50000 iterations?\n");
turnCount(191, 50000);
turnCount(1377, 50000);
turnCount(49999, 50000);
turnCount(50000, 50000);
turnCount(50001, 50000);
return 0;
}
|
Produce a language-to-language conversion: from VB to C, same semantics. | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.precedence = precedence
Me.rightAssociative = rightAssociative
End Sub
End Class
ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
{
{"^", New SymbolType("^", 4, True)},
{"*", New SymbolType("*", 3, False)},
{"/", New SymbolType("/", 3, False)},
{"+", New SymbolType("+", 2, False)},
{"-", New SymbolType("-", 2, False)}
}
Function ToPostfix(infix As String) As String
Dim tokens = infix.Split(" ")
Dim stack As New Stack(Of String)
Dim output As New List(Of String)
Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")
For Each token In tokens
Dim iv As Integer
Dim op1 As SymbolType
Dim op2 As SymbolType
If Integer.TryParse(token, iv) Then
output.Add(token)
Print(token)
ElseIf Operators.TryGetValue(token, op1) Then
While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
Dim c = op1.precedence.CompareTo(op2.precedence)
If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
output.Add(stack.Pop())
Else
Exit While
End If
End While
stack.Push(token)
Print(token)
ElseIf token = "(" Then
stack.Push(token)
Print(token)
ElseIf token = ")" Then
Dim top = ""
While stack.Count > 0
top = stack.Pop()
If top <> "(" Then
output.Add(top)
Else
Exit While
End If
End While
If top <> "(" Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Print(token)
End If
Next
While stack.Count > 0
Dim top = stack.Pop()
If Not Operators.ContainsKey(top) Then
Throw New ArgumentException("No matching right parenthesis.")
End If
output.Add(top)
End While
Print("pop")
Return String.Join(" ", output)
End Function
Sub Main()
Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
Console.WriteLine(ToPostfix(infix))
End Sub
End Module
| #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
{"^\\*\\*", A_R, 3},
{"^\\^", A_R, 3},
{"^\\*", A_L, 2},
{"^/", A_L, 2},
{"^\\+", A_L, 1},
{"^-", A_L, 1},
{0}
};
pat_t pat_arg[] = {
{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
{"^[a-zA-Z_][a-zA-Z_0-9]*"},
{"^\\(", A_L, -1},
{0}
};
str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop() stack[--l_stack]
void display(const char *s)
{
int i;
printf("\033[1;1H\033[JText | %s", s);
printf("\nStack| ");
for (i = 0; i < l_stack; i++)
printf("%.*s ", stack[i].len, stack[i].s);
printf("\nQueue| ");
for (i = 0; i < l_queue; i++)
printf("%.*s ", queue[i].len, queue[i].s);
puts("\n\n<press enter>");
getchar();
}
int prec_booster;
#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail("parse arg", s);
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail("parse op", s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail("unmatched )", s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail("unmatched (", s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail("unexpected eol", s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"123",
"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",
"(((((((1+2+3**(4 + 5))))))",
"a^(b + c/d * .1e5)!",
"(1**2)**3",
"2 + 2 *",
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf("Testing string `%s' <enter>\n", tests[i]);
getchar();
printf("string `%s': %s\n\n", tests[i],
parse(tests[i]) ? "Ok" : "Error");
}
return 0;
}
|
Transform the following VB implementation into C, maintaining the same output and logic. | Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Const maxNumber As Integer = 20
Dim prime(2 * maxNumber) As Boolean
Public Function countArrangements(ByVal n As Integer) As Integer
If n < 2 Then
Return 0
ElseIf n < 4 Then
For i As Integer = 1 To n
Console.Out.Write(i.ToString.PadLeft(3))
Next i
Console.Out.WriteLine()
Return 1
Else
Dim printSolution As Boolean = true
Dim used(n) As Boolean
Dim number(n) As Integer
For i As Integer = 0 To n - 1
number(i) = i Mod 2
Next i
used(1) = True
number(n) = n
used(n) = True
Dim count As Integer = 0
Dim p As Integer = 2
Do While p > 0
Dim p1 As Integer = number(p - 1)
Dim current As Integer = number(p)
Dim [next] As Integer = current + 2
Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))
[next] += 2
Loop
If [next] >= n Then
[next] = 0
End If
If p = n - 1 Then
If [next] <> 0 Then
If prime([next] + n) Then
count += 1
If printSolution Then
For i As Integer = 1 To n - 2
Console.Out.Write(number(i).ToString.PadLeft(3))
Next i
Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))
printSolution = False
End If
End If
[next] = 0
End If
p -= 1
End If
If [next] <> 0 Then
used(current) = False
used([next]) = True
number(p) = [next]
p += 1
ElseIf p <= 2 Then
p = 0
Else
used(number(p)) = False
number(p) = p Mod 2
p -= 1
End If
Loop
Return count
End If
End Function
Public Sub Main
prime(2) = True
For i As Integer = 3 To UBound(prime) Step 2
prime(i) = True
Next i
For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2
If prime(i) Then
For s As Integer = i * i To Ubound(prime) Step i + i
prime(s) = False
Next s
End If
Next i
Dim arrangements(maxNumber) As Integer
For n As Integer = 2 To UBound(arrangements)
arrangements(n) = countArrangements(n)
Next n
For n As Integer = 2 To UBound(arrangements)
Console.Out.Write(" " & arrangements(n))
Next n
Console.Out.WriteLine()
End Sub
End Module
| #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool is_prime(unsigned int n) {
assert(n < 64);
static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};
return isprime[n];
}
void swap(unsigned int* a, size_t i, size_t j) {
unsigned int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
bool prime_triangle_row(unsigned int* a, size_t length) {
if (length == 2)
return is_prime(a[0] + a[1]);
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
if (prime_triangle_row(a + 1, length - 1))
return true;
swap(a, i, 1);
}
}
return false;
}
int prime_triangle_count(unsigned int* a, size_t length) {
int count = 0;
if (length == 2) {
if (is_prime(a[0] + a[1]))
++count;
} else {
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
count += prime_triangle_count(a + 1, length - 1);
swap(a, i, 1);
}
}
}
return count;
}
void print(unsigned int* a, size_t length) {
if (length == 0)
return;
printf("%2u", a[0]);
for (size_t i = 1; i < length; ++i)
printf(" %2u", a[i]);
printf("\n");
}
int main() {
clock_t start = clock();
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (prime_triangle_row(a, n))
print(a, n);
}
printf("\n");
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (n > 2)
printf(" ");
printf("%d", prime_triangle_count(a, n));
}
printf("\n");
clock_t end = clock();
double duration = (end - start + 0.0) / CLOCKS_PER_SEC;
printf("\nElapsed time: %f seconds\n", duration);
return 0;
}
|
Ensure the translated C code behaves exactly like the original VB snippet. | Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Const maxNumber As Integer = 20
Dim prime(2 * maxNumber) As Boolean
Public Function countArrangements(ByVal n As Integer) As Integer
If n < 2 Then
Return 0
ElseIf n < 4 Then
For i As Integer = 1 To n
Console.Out.Write(i.ToString.PadLeft(3))
Next i
Console.Out.WriteLine()
Return 1
Else
Dim printSolution As Boolean = true
Dim used(n) As Boolean
Dim number(n) As Integer
For i As Integer = 0 To n - 1
number(i) = i Mod 2
Next i
used(1) = True
number(n) = n
used(n) = True
Dim count As Integer = 0
Dim p As Integer = 2
Do While p > 0
Dim p1 As Integer = number(p - 1)
Dim current As Integer = number(p)
Dim [next] As Integer = current + 2
Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))
[next] += 2
Loop
If [next] >= n Then
[next] = 0
End If
If p = n - 1 Then
If [next] <> 0 Then
If prime([next] + n) Then
count += 1
If printSolution Then
For i As Integer = 1 To n - 2
Console.Out.Write(number(i).ToString.PadLeft(3))
Next i
Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))
printSolution = False
End If
End If
[next] = 0
End If
p -= 1
End If
If [next] <> 0 Then
used(current) = False
used([next]) = True
number(p) = [next]
p += 1
ElseIf p <= 2 Then
p = 0
Else
used(number(p)) = False
number(p) = p Mod 2
p -= 1
End If
Loop
Return count
End If
End Function
Public Sub Main
prime(2) = True
For i As Integer = 3 To UBound(prime) Step 2
prime(i) = True
Next i
For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2
If prime(i) Then
For s As Integer = i * i To Ubound(prime) Step i + i
prime(s) = False
Next s
End If
Next i
Dim arrangements(maxNumber) As Integer
For n As Integer = 2 To UBound(arrangements)
arrangements(n) = countArrangements(n)
Next n
For n As Integer = 2 To UBound(arrangements)
Console.Out.Write(" " & arrangements(n))
Next n
Console.Out.WriteLine()
End Sub
End Module
| #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool is_prime(unsigned int n) {
assert(n < 64);
static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};
return isprime[n];
}
void swap(unsigned int* a, size_t i, size_t j) {
unsigned int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
bool prime_triangle_row(unsigned int* a, size_t length) {
if (length == 2)
return is_prime(a[0] + a[1]);
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
if (prime_triangle_row(a + 1, length - 1))
return true;
swap(a, i, 1);
}
}
return false;
}
int prime_triangle_count(unsigned int* a, size_t length) {
int count = 0;
if (length == 2) {
if (is_prime(a[0] + a[1]))
++count;
} else {
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
count += prime_triangle_count(a + 1, length - 1);
swap(a, i, 1);
}
}
}
return count;
}
void print(unsigned int* a, size_t length) {
if (length == 0)
return;
printf("%2u", a[0]);
for (size_t i = 1; i < length; ++i)
printf(" %2u", a[i]);
printf("\n");
}
int main() {
clock_t start = clock();
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (prime_triangle_row(a, n))
print(a, n);
}
printf("\n");
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (n > 2)
printf(" ");
printf("%d", prime_triangle_count(a, n));
}
printf("\n");
clock_t end = clock();
double duration = (end - start + 0.0) / CLOCKS_PER_SEC;
printf("\nElapsed time: %f seconds\n", duration);
return 0;
}
|
Transform the following VB implementation into C, maintaining the same output and logic. | Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)
| #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
return 0;
}
|
Can you help me rewrite this code in C instead of VB, keeping it the same logically? | Option Explicit
Sub Main_Middle_three_digits()
Dim Numbers, i&
Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _
100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
For i = 0 To 16
Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i)))
Next
End Sub
Function Middle3digits(strNb As String) As String
If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1)
If Len(strNb) < 3 Then
Middle3digits = "Error ! Number of digits must be >= 3"
ElseIf Len(strNb) Mod 2 = 0 Then
Middle3digits = "Error ! Number of digits must be odd"
Else
Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)
End If
End Function
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, "%d", n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
1234567890};
int i;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = "error";
printf("%d: %s\n", x[i], m);
}
return 0;
}
|
Transform the following VB implementation into C, maintaining the same output and logic. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
| #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
|
Convert this VB block to C, preserving its control flow and logic. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
| #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
|
Generate an equivalent C version of this VB code. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
}
|
Port the following code from VB to C with equivalent syntax and logic. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
}
|
Write a version of this VB function in C with identical behavior. | Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
| #include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
const char *code =
"CREATE TABLE address (\n"
" addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" addrStreet TEXT NOT NULL,\n"
" addrCity TEXT NOT NULL,\n"
" addrState TEXT NOT NULL,\n"
" addrZIP TEXT NOT NULL)\n" ;
int main()
{
sqlite3 *db = NULL;
char *errmsg;
if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) {
fprintf(stderr, errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
|
Port the following code from VB to C with equivalent syntax and logic. | Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Dim l As List(Of Integer) = {1, 1}.ToList()
Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer
Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)
End Function
Sub Main(ByVal args As String())
Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,
selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}
Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1
Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take)
Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take)))
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:")
For Each ii As Integer In selection
Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1
Console.WriteLine("{0,3}: {1:n0}", ii, j)
Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max
If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For
Next
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" &
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module
| k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
}
|
Port the following code from VB to C with equivalent syntax and logic. |
tt=array( _
"Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _
"Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example")
tv=array( _
"A261","A261","G200","G200","H416","H416","L000","L300", _
"M220","P236","R163","R163","R150","T522","S532","E251")
For i=lbound(tt) To ubound(tt)
ts=soundex(tt(i))
If ts<>tv(i) Then ok=" KO "& tv(i) Else ok=""
Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok
Next
Function getCode(c)
Select Case c
Case "B", "F", "P", "V"
getCode = "1"
Case "C", "G", "J", "K", "Q", "S", "X", "Z"
getCode = "2"
Case "D", "T"
getCode = "3"
Case "L"
getCode = "4"
Case "M", "N"
getCode = "5"
Case "R"
getCode = "6"
Case "W","H"
getCode = "-"
End Select
End Function
Function soundex(s)
Dim code, previous, i
code = UCase(Mid(s, 1, 1))
previous = getCode(UCase(Mid(s, 1, 1)))
For i = 2 To Len(s)
current = getCode(UCase(Mid(s, i, 1)))
If current <> "" And current <> "-" And current <> previous Then code = code & current
If current <> "-" Then previous = current
Next
soundex = Mid(code & "000", 1, 4)
End Function
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
const char* soundex(const char *s)
{
static char out[5];
int c, prev, i;
out[0] = out[4] = 0;
if (!s || !*s) return out;
out[0] = *s++;
prev = code[(int)out[0]];
for (i = 1; *s && i < 4; s++) {
if ((c = code[(int)*s]) == prev) continue;
if (c == -1) prev = 0;
else if (c > 0) {
out[i++] = c + '0';
prev = c;
}
}
while (i < 4) out[i++] = '0';
return out;
}
int main()
{
int i;
const char *sdx, *names[][2] = {
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"},
{0, 0}
};
init();
puts(" Test name Code Got\n----------------------");
for (i = 0; names[i][0]; i++) {
sdx = soundex(names[i][0]);
printf("%11s %s %s ", names[i][0], names[i][1], sdx);
printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original VB code. | Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Module Module1
Class State
Private ReadOnly client As TcpClient
Private ReadOnly sb As New StringBuilder
Public Sub New(name As String, client As TcpClient)
Me.Name = name
Me.client = client
End Sub
Public ReadOnly Property Name As String
Public Sub Send(text As String)
Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text))
client.GetStream().Write(bytes, 0, bytes.Length)
End Sub
End Class
ReadOnly connections As New Dictionary(Of Integer, State)
Dim listen As TcpListener
Dim serverThread As Thread
Sub Main()
listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004)
serverThread = New Thread(New ThreadStart(AddressOf DoListen))
serverThread.Start()
End Sub
Private Sub DoListen()
listen.Start()
Console.WriteLine("Server: Started server")
Do
Console.Write("Server: Waiting...")
Dim client = listen.AcceptTcpClient()
Console.WriteLine(" Connected")
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))
clientThread.Start(client)
Loop
End Sub
Private Sub DoClient(client As TcpClient)
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId)
Dim bytes = Encoding.ASCII.GetBytes("Enter name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
Dim done As Boolean
Dim name As String
Do
If Not client.Connected Then
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End If
name = Receive(client)
done = True
For Each cl In connections
Dim state = cl.Value
If state.Name = name Then
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
done = False
End If
Next
Loop While Not done
connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Broadcast(String.Format("+++ {0} arrived +++", name))
Do
Dim text = Receive(client)
If text = "/quit" Then
Broadcast(String.Format("Connection from {0} closed.", name))
connections.Remove(Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Exit Do
End If
If Not client.Connected Then
Exit Do
End If
Broadcast(String.Format("{0}> {1}", name, text))
Loop
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End Sub
Private Function Receive(client As TcpClient) As String
Dim sb As New StringBuilder
Do
If client.Available > 0 Then
While client.Available > 0
Dim ch = Chr(client.GetStream.ReadByte())
If ch = vbCr Then
Continue While
End If
If ch = vbLf Then
Return sb.ToString()
End If
sb.Append(ch)
End While
Thread.Sleep(100)
End If
Loop
End Function
Private Sub Broadcast(text As String)
Console.WriteLine(text)
For Each client In connections
If client.Key <> Thread.CurrentThread.ManagedThreadId Then
Dim state = client.Value
state.Send(text)
End If
Next
End Sub
End Module
| #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h>
int tsocket;
struct sockaddr_in tsockinfo;
fd_set status, current;
void ClientText(int handle, char *buf, int buf_len);
struct client
{
char buffer[4096];
int pos;
char name[32];
} *connections[FD_SETSIZE];
void AddConnection(int handle)
{
connections[handle] = malloc(sizeof(struct client));
connections[handle]->buffer[0] = '\0';
connections[handle]->pos = 0;
connections[handle]->name[0] = '\0';
}
void CloseConnection(int handle)
{
char buf[512];
int j;
FD_CLR(handle, &status);
if (connections[handle]->name[0])
{
sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, buf, strlen(buf)) < 0)
{
CloseConnection(j);
}
}
}
} else
{
printf ("-- Connection %d disconnected\n", handle);
}
if (connections[handle])
{
free(connections[handle]);
}
close(handle);
}
void strip(char *buf)
{
char *x;
x = strchr(buf, '\n');
if (x) { *x='\0'; }
x = strchr(buf, '\r');
if (x) { *x='\0'; }
}
int RelayText(int handle)
{
char *begin, *end;
int ret = 0;
begin = connections[handle]->buffer;
if (connections[handle]->pos == 4000)
{
if (begin[3999] != '\n')
begin[4000] = '\0';
else {
begin[4000] = '\n';
begin[4001] = '\0';
}
} else {
begin[connections[handle]->pos] = '\0';
}
end = strchr(begin, '\n');
while (end != NULL)
{
char output[8000];
output[0] = '\0';
if (!connections[handle]->name[0])
{
strncpy(connections[handle]->name, begin, 31);
connections[handle]->name[31] = '\0';
strip(connections[handle]->name);
sprintf(output, "* Connected: %s\r\n", connections[handle]->name);
ret = 1;
} else
{
sprintf(output, "%s: %.*s\r\n", connections[handle]->name,
end-begin, begin);
ret = 1;
}
if (output[0])
{
int j;
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, output, strlen(output)) < 0)
{
CloseConnection(j);
}
}
}
}
begin = end+1;
end = strchr(begin, '\n');
}
strcpy(connections[handle]->buffer, begin);
connections[handle]->pos -= begin - connections[handle]->buffer;
return ret;
}
void ClientText(int handle, char *buf, int buf_len)
{
int i, j;
if (!connections[handle])
return;
j = connections[handle]->pos;
for (i = 0; i < buf_len; ++i, ++j)
{
connections[handle]->buffer[j] = buf[i];
if (j == 4000)
{
while (RelayText(handle));
j = connections[handle]->pos;
}
}
connections[handle]->pos = j;
while (RelayText(handle));
}
int ChatLoop()
{
int i, j;
FD_ZERO(&status);
FD_SET(tsocket, &status);
FD_SET(0, &status);
while(1)
{
current = status;
if (select(FD_SETSIZE, ¤t, NULL, NULL, NULL)==-1)
{
perror("Select");
return 0;
}
for (i = 0; i < FD_SETSIZE; ++i)
{
if (FD_ISSET(i, ¤t))
{
if (i == tsocket)
{
struct sockaddr_in cliinfo;
socklen_t addrlen = sizeof(cliinfo);
int handle;
handle = accept(tsocket, &cliinfo, &addrlen);
if (handle == -1)
{
perror ("Couldn't accept connection");
} else if (handle > FD_SETSIZE)
{
printf ("Unable to accept new connection.\n");
close(handle);
}
else
{
if (write(handle, "Enter name: ", 12) >= 0)
{
printf("-- New connection %d from %s:%hu\n",
handle,
inet_ntoa (cliinfo.sin_addr),
ntohs(cliinfo.sin_port));
FD_SET(handle, &status);
AddConnection(handle);
}
}
}
else
{
char buf[512];
int b;
b = read(i, buf, 500);
if (b <= 0)
{
CloseConnection(i);
}
else
{
ClientText(i, buf, b);
}
}
}
}
}
}
int main (int argc, char*argv[])
{
tsocket = socket(PF_INET, SOCK_STREAM, 0);
tsockinfo.sin_family = AF_INET;
tsockinfo.sin_port = htons(7070);
if (argc > 1)
{
tsockinfo.sin_port = htons(atoi(argv[1]));
}
tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));
if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)
{
perror("Couldn't bind socket");
return -1;
}
if (listen(tsocket, 10) == -1)
{
perror("Couldn't listen to port");
}
ChatLoop();
return 0;
}
|
Port the following code from VB to C with equivalent syntax and logic. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Port the provided VB code into C while preserving the original functionality. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Port the following code from VB to C with equivalent syntax and logic. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original VB code. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Generate a C translation of this VB snippet without changing its computational steps. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Please provide an equivalent version of this VB code in C. | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
| #include <sys/ioctl.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int
main()
{
struct winsize ws;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
}
|
Write a version of this VB function in C with identical behavior. | Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
| #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
void (*Action)(void);
const statechange table[MAXINPUTS];
} FSM;
char str[10];
void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
void Refund(void) { fprintf(stderr, "Please collect refund.\n"); }
void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
for (;;) {
fsm[state].Action();
each = 0;
while (!( ((fsm[state].table[each].in == -1)
|| (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
state = fsm[state].table[each].out;
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from VB to C. | Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
| #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
void (*Action)(void);
const statechange table[MAXINPUTS];
} FSM;
char str[10];
void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
void Refund(void) { fprintf(stderr, "Please collect refund.\n"); }
void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
for (;;) {
fsm[state].Action();
each = 0;
while (!( ((fsm[state].table[each].in == -1)
|| (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
state = fsm[state].table[each].out;
}
return 0;
}
|
Translate the given VB code snippet into C without altering its behavior. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Translate the given VB code snippet into C without altering its behavior. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Convert the following code from VB to C, ensuring the logic remains intact. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Generate a C translation of this VB snippet without changing its computational steps. | Private Sub sierpinski(Order_ As Integer, Side As Double)
Dim Circumradius As Double, Inradius As Double
Dim Height As Double, Diagonal As Double, HeightDiagonal As Double
Dim Pi As Double, p(5) As String, Shp As Shape
Circumradius = Sqr(50 + 10 * Sqr(5)) / 10
Inradius = Sqr(25 + 10 * Sqr(5)) / 10
Height = Circumradius + Inradius
Diagonal = (1 + Sqr(5)) / 2
HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4
Pi = WorksheetFunction.Pi
Ratio = Height / (2 * Height + HeightDiagonal)
Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _
2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)
p(0) = Shp.Name
Shp.Rotation = 180
Shp.Line.Weight = 0
For j = 1 To Order_
For i = 0 To 4
Set Shp = Shp.Duplicate
p(i + 1) = Shp.Name
If i = 0 Then Shp.Rotation = 0
Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)
Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)
Shp.Visible = msoTrue
Next i
Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group
p(0) = Shp.Name
If j < Order_ Then
Shp.ScaleHeight Ratio, False
Shp.ScaleWidth Ratio, False
Shp.Rotation = 180
Shp.Left = 2 * Side
Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side
End If
Next j
End Sub
Public Sub main()
sierpinski Order_:=5, Side:=200
End Sub
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
|
Please provide an equivalent version of this VB code in C. | Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
rep_string = tmp
Exit Do
Else
tmp = Mid(tmp,1,Len(tmp)-1)
End If
Loop
If Len(tmp) > 0 Then
rep_string = tmp
Else
rep_string = "No Repeating String"
End If
End Function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
"1111111111","0100101101","0100100","101","11","00","1")
For n = 0 To UBound(arr)
WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
WScript.StdOut.WriteLine
Next
| #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in VB. | Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
rep_string = tmp
Exit Do
Else
tmp = Mid(tmp,1,Len(tmp)-1)
End If
Loop
If Len(tmp) > 0 Then
rep_string = tmp
Else
rep_string = "No Repeating String"
End If
End Function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
"1111111111","0100101101","0100100","101","11","00","1")
For n = 0 To UBound(arr)
WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
WScript.StdOut.WriteLine
Next
| #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original VB code. | TYPE syswindowstru
screenheight AS INTEGER
screenwidth AS INTEGER
maxheight AS INTEGER
maxwidth AS INTEGER
END TYPE
DIM syswindow AS syswindowstru
syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
| #include<windows.h>
#include<stdio.h>
int main()
{
printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
return 0;
}
|
Write the same code in C as shown below in VB. |
Enum fruits
apple
banana
cherry
End Enum
Enum fruits2
pear = 5
mango = 10
kiwi = 20
pineapple = 20
End Enum
Sub test()
Dim f As fruits
f = apple
Debug.Print "apple equals "; f
Debug.Print "kiwi equals "; kiwi
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
| enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
|
Transform the following VB implementation into C, maintaining the same output and logic. | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Can you help me rewrite this code in C instead of VB, keeping it the same logically? | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Change the following VB code into C without altering its purpose. | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Please provide an equivalent version of this VB code in C. | Function parse_ip(addr)
Set ipv4_pattern = New RegExp
ipv4_pattern.Global = True
ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}"
Set ipv6_pattern = New RegExp
ipv6_pattern.Global = True
ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}"
If ipv4_pattern.Test(addr) Then
port = Split(addr,":")
octet = Split(port(0),".")
ipv4_hex = ""
For i = 0 To UBound(octet)
If octet(i) <= 255 And octet(i) >= 0 Then
ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2)
Else
ipv4_hex = "Erroneous Address"
Exit For
End If
Next
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: " & ipv4_hex & vbCrLf
If UBound(port) = 1 Then
If port(1) <= 65535 And port(1) >= 0 Then
parse_ip = parse_ip & "Port: " & port(1) & vbCrLf
Else
parse_ip = parse_ip & "Port: Invalid" & vbCrLf
End If
End If
End If
If ipv6_pattern.Test(addr) Then
parse_ip = "Test Case: " & addr & vbCrLf
port_v6 = "Port: "
ipv6_hex = ""
If InStr(1,addr,"[") Then
port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1)))
addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1))
End If
word = Split(addr,":")
word_count = 0
For i = 0 To UBound(word)
If word(i) = "" Then
If i < UBound(word) Then
If Int((7-(i+1))/2) = 1 Then
k = 1
ElseIf UBound(word) < 6 Then
k = Int((7-(i+1))/2)
ElseIf UBound(word) >= 6 Then
k = Int((7-(i+1))/2)-1
End If
For j = 0 To k
ipv6_hex = ipv6_hex & "0000"
word_count = word_count + 1
Next
Else
For j = 0 To (7-word_count)
ipv6_hex = ipv6_hex & "0000"
Next
End If
Else
ipv6_hex = ipv6_hex & Right("0000" & word(i),4)
word_count = word_count + 1
End If
Next
parse_ip = parse_ip & "Address: " & ipv6_hex &_
vbCrLf & port_v6 & vbCrLf
End If
If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: Invalid Address" & vbCrLf
End If
End Function
ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_
"[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode")
For n = 0 To UBound(ip_arr)
WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf
Next
| #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
|
Convert this VB block to C, preserving its control flow and logic. | Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function
Sub Main()
Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5
Dim P&, I&, G&, A&, M, Cur(Value To Volume)
Dim S As New Collection: S.Add Array(0)
Const SackW = 25, SackV = 0.25
Dim Panacea: Panacea = Array(3000, 0.3, 0.025)
Dim Ichor: Ichor = Array(1800, 0.2, 0.015)
Dim Gold: Gold = Array(2500, 2, 0.002)
For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))
For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))
For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))
For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next
If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _
S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1
Next G, I, P
Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount"
For Each M In S
If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)
Next
End Sub
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
double value;
double weight;
double volume;
} item_t;
item_t items[] = {
{"panacea", 3000.0, 0.3, 0.025},
{"ichor", 1800.0, 0.2, 0.015},
{"gold", 2500.0, 2.0, 0.002},
};
int n = sizeof (items) / sizeof (item_t);
int *count;
int *best;
double best_value;
void knapsack (int i, double value, double weight, double volume) {
int j, m1, m2, m;
if (i == n) {
if (value > best_value) {
best_value = value;
for (j = 0; j < n; j++) {
best[j] = count[j];
}
}
return;
}
m1 = weight / items[i].weight;
m2 = volume / items[i].volume;
m = m1 < m2 ? m1 : m2;
for (count[i] = m; count[i] >= 0; count[i]--) {
knapsack(
i + 1,
value + count[i] * items[i].value,
weight - count[i] * items[i].weight,
volume - count[i] * items[i].volume
);
}
}
int main () {
count = malloc(n * sizeof (int));
best = malloc(n * sizeof (int));
best_value = 0;
knapsack(0, 0.0, 25.0, 0.25);
int i;
for (i = 0; i < n; i++) {
printf("%d %s\n", best[i], items[i].name);
}
printf("best value: %.0f\n", best_value);
free(count); free(best);
return 0;
}
|
Change the following VB code into C without altering its purpose. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Set objKeyMap = CreateObject("Scripting.Dictionary")
With objKeyMap
.Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5"
.Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9"
End With
TotalWords = 0
UniqueCombinations = 0
Set objUniqueWords = CreateObject("Scripting.Dictionary")
Set objMoreThanOneWord = CreateObject("Scripting.Dictionary")
Do Until objInFile.AtEndOfStream
Word = objInFile.ReadLine
c = 0
Num = ""
If Word <> "" Then
For i = 1 To Len(Word)
For Each Key In objKeyMap.Keys
If InStr(1,Key,Mid(Word,i,1),1) > 0 Then
Num = Num & objKeyMap.Item(Key)
c = c + 1
End If
Next
Next
If c = Len(Word) Then
TotalWords = TotalWords + 1
If objUniqueWords.Exists(Num) = False Then
objUniqueWords.Add Num, ""
UniqueCombinations = UniqueCombinations + 1
Else
If objMoreThanOneWord.Exists(Num) = False Then
objMoreThanOneWord.Add Num, ""
End If
End If
End If
End If
Loop
WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_
"They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_
objMoreThanOneWord.Count & " digit combinations represent Textonyms."
objInFile.Close
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Can you help me rewrite this code in C instead of VB, keeping it the same logically? | Public Function RangeExtraction(AList) As String
Const RangeDelim = "-"
Dim result As String
Dim InRange As Boolean
Dim Posn, ub, lb, rangestart, rangelen As Integer
result = ""
ub = UBound(AList)
lb = LBound(AList)
Posn = lb
While Posn < ub
rangestart = Posn
rangelen = 0
InRange = True
While InRange
rangelen = rangelen + 1
If Posn = ub Then
InRange = False
Else
InRange = (AList(Posn + 1) = AList(Posn) + 1)
Posn = Posn + 1
End If
Wend
If rangelen > 2 Then
result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))
Else
For i = rangestart To rangestart + rangelen - 1
result = result & "," & Format$(AList(i))
Next
End If
Posn = rangestart + rangelen
Wend
RangeExtraction = Mid$(result, 2)
End Function
Public Sub RangeTest()
Dim MyList As Variant
MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
Debug.Print "a) "; RangeExtraction(MyList)
Dim MyOtherList(1 To 20) As Integer
MyOtherList(1) = -6
MyOtherList(2) = -3
MyOtherList(3) = -2
MyOtherList(4) = -1
MyOtherList(5) = 0
MyOtherList(6) = 1
MyOtherList(7) = 3
MyOtherList(8) = 4
MyOtherList(9) = 5
MyOtherList(10) = 7
MyOtherList(11) = 8
MyOtherList(12) = 9
MyOtherList(13) = 10
MyOtherList(14) = 11
MyOtherList(15) = 14
MyOtherList(16) = 15
MyOtherList(17) = 17
MyOtherList(18) = 18
MyOtherList(19) = 19
MyOtherList(20) = 20
Debug.Print "b) "; RangeExtraction(MyOtherList)
End Sub
| #include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "")
#define ol (s ? 100 : 0)
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
|
Convert this VB block to C, preserving its control flow and logic. | Public Sub main()
Dim c(1) As Currency
Dim d(1) As Double
Dim dt(1) As Date
Dim a(1) As Integer
Dim l(1) As Long
Dim s(1) As Single
Dim e As Variant
Dim o As Object
Set o = New Application
Debug.Print TypeName(o)
Debug.Print TypeName(1 = 1)
Debug.Print TypeName(CByte(1))
Set o = New Collection
Debug.Print TypeName(o)
Debug.Print TypeName(1@)
Debug.Print TypeName(c)
Debug.Print TypeName(CDate(1))
Debug.Print TypeName(dt)
Debug.Print TypeName(CDec(1))
Debug.Print TypeName(1#)
Debug.Print TypeName(d)
Debug.Print TypeName(e)
Debug.Print TypeName(CVErr(1))
Debug.Print TypeName(1)
Debug.Print TypeName(a)
Debug.Print TypeName(1&)
Debug.Print TypeName(l)
Set o = Nothing
Debug.Print TypeName(o)
Debug.Print TypeName([A1])
Debug.Print TypeName(1!)
Debug.Print TypeName(s)
Debug.Print TypeName(CStr(1))
Debug.Print TypeName(Worksheets(1))
End Sub
| #include<stdio.h>
#include<ctype.h>
void typeDetector(char* str){
if(isalnum(str[0])!=0)
printf("\n%c is alphanumeric",str[0]);
if(isalpha(str[0])!=0)
printf("\n%c is alphabetic",str[0]);
if(iscntrl(str[0])!=0)
printf("\n%c is a control character",str[0]);
if(isdigit(str[0])!=0)
printf("\n%c is a digit",str[0]);
if(isprint(str[0])!=0)
printf("\n%c is printable",str[0]);
if(ispunct(str[0])!=0)
printf("\n%c is a punctuation character",str[0]);
if(isxdigit(str[0])!=0)
printf("\n%c is a hexadecimal digit",str[0]);
}
int main(int argC, char* argV[])
{
int i;
if(argC==1)
printf("Usage : %s <followed by ASCII characters>");
else{
for(i=1;i<argC;i++)
typeDetector(argV[i]);
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. |
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\triangle.txt",1,False)
row = Split(objinfile.ReadAll,vbCrLf)
For i = UBound(row) To 0 Step -1
row(i) = Split(row(i)," ")
If i < UBound(row) Then
For j = 0 To UBound(row(i))
If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))
Else
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))
End If
Next
End If
Next
WScript.Echo row(0)(0)
objinfile.Close
Set objfso = Nothing
| #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
|
Port the following code from VB to C with equivalent syntax and logic. | Public n As Variant
Private Sub init()
n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]
End Sub
Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant
Dim wtb As Integer
Dim bn As Integer
Dim prev As String: prev = "#"
Dim next_ As String
Dim p2468 As String
For i = 1 To UBound(n)
next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)
wtb = wtb - (prev = "." And next_ <= "#")
bn = bn - (i > 1 And next_ <= "#")
If (i And 1) = 0 Then p2468 = p2468 & prev
prev = next_
Next i
If step = 2 Then
p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)
End If
Dim ret(2) As Variant
ret(0) = wtb
ret(1) = bn
ret(2) = p2468
AB = ret
End Function
Private Sub Zhang_Suen(text As Variant)
Dim wtb As Integer
Dim bn As Integer
Dim changed As Boolean, changes As Boolean
Dim p2468 As String
Dim x As Integer, y As Integer, step As Integer
Do While True
changed = False
For step = 1 To 2
changes = False
For y = 1 To UBound(text) - 1
For x = 2 To Len(text(y)) - 1
If Mid(text(y), x, 1) = "#" Then
ret = AB(text, y, x, step)
wtb = ret(0)
bn = ret(1)
p2468 = ret(2)
If wtb = 1 _
And bn >= 2 And bn <= 6 _
And InStr(1, Mid(p2468, 1, 3), ".") _
And InStr(1, Mid(p2468, 2, 3), ".") Then
changes = True
text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x)
End If
End If
Next x
Next y
If changes Then
For y = 1 To UBound(text) - 1
text(y) = Replace(text(y), "!", ".")
Next y
changed = True
End If
Next step
If Not changed Then Exit Do
Loop
Debug.Print Join(text, vbCrLf)
End Sub
Public Sub main()
init
Dim Small_rc(9) As String
Small_rc(0) = "................................"
Small_rc(1) = ".#########.......########......."
Small_rc(2) = ".###...####.....####..####......"
Small_rc(3) = ".###....###.....###....###......"
Small_rc(4) = ".###...####.....###............."
Small_rc(5) = ".#########......###............."
Small_rc(6) = ".###.####.......###....###......"
Small_rc(7) = ".###..####..###.####..####.###.."
Small_rc(8) = ".###...####.###..########..###.."
Small_rc(9) = "................................"
Zhang_Suen (Small_rc)
End Sub
| #include<stdlib.h>
#include<stdio.h>
char** imageMatrix;
char blankPixel,imagePixel;
typedef struct{
int row,col;
}pixel;
int getBlackNeighbours(int row,int col){
int i,j,sum = 0;
for(i=-1;i<=1;i++){
for(j=-1;j<=1;j++){
if(i!=0 || j!=0)
sum+= (imageMatrix[row+i][col+j]==imagePixel);
}
}
return sum;
}
int getBWTransitions(int row,int col){
return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)
+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)
+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)
+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)
+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)
+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)
+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)
+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));
}
int zhangSuenTest1(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel)
&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));
}
int zhangSuenTest2(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));
}
void zhangSuen(char* inputFile, char* outputFile){
int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;
pixel* markers;
FILE* inputP = fopen(inputFile,"r");
fscanf(inputP,"%d%d",&rows,&cols);
fscanf(inputP,"%d%d",&blankPixel,&imagePixel);
blankPixel<=9?blankPixel+='0':blankPixel;
imagePixel<=9?imagePixel+='0':imagePixel;
printf("\nPrinting original image :\n");
imageMatrix = (char**)malloc(rows*sizeof(char*));
for(i=0;i<rows;i++){
imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));
fscanf(inputP,"%s\n",imageMatrix[i]);
printf("\n%s",imageMatrix[i]);
}
fclose(inputP);
endRow = rows-2;
endCol = cols-2;
do{
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
if(processed==0)
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
}while(processed==1);
FILE* outputP = fopen(outputFile,"w");
printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("%c",imageMatrix[i][j]);
fprintf(outputP,"%c",imageMatrix[i][j]);
}
printf("\n");
fprintf(outputP,"\n");
}
fclose(outputP);
printf("\nImage also written to : %s",outputFile);
}
int main()
{
char inputFile[100],outputFile[100];
printf("Enter full path of input image file : ");
scanf("%s",inputFile);
printf("Enter full path of output image file : ");
scanf("%s",outputFile);
zhangSuen(inputFile,outputFile);
return 0;
}
|
Write a version of this VB function in C with identical behavior. | Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Sub Main
Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}
For i As Integer = 0 To Ubound(s)
Dim curr As Integer = s(i)
Dim prev As Integer
If i > 1 AndAlso curr = prev Then
Console.Out.WriteLine(i)
End If
prev = curr
Next i
End Sub
End Module
| #include <stdio.h>
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
for (i = 0; i < 7; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
return 0;
}
|
Write the same algorithm in C as shown in this VB implementation. | SUB Main()
END
| #include<stdio.h>
#define start main()
int start
{
printf("Hello World !");
return 0;
}
|
Port the following code from VB to C with equivalent syntax and logic. | SUB Main()
END
| #include<stdio.h>
#define start main()
int start
{
printf("Hello World !");
return 0;
}
|
Translate this program into C but keep the logic exactly as in VB. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
sub koch (n,le)
if n=0 then x.fw le :exit sub
koch n-1, le/3
x.lt 1
koch n-1, le/3
x.rt 2
koch n-1, le/3
x.lt 1
koch n-1, le/3
end sub
dim x,i
set x=new turtle
x.iangle=60
x.orient=0
x.incr=3
x.x=100:x.y=300
for i=0 to 3
koch 7,100
x.rt 2
next
set x=nothing
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}point;
void kochCurve(point p1,point p2,int times){
point p3,p4,p5;
double theta = pi/3;
if(times>0){
p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
kochCurve(p1,p3,times-1);
kochCurve(p3,p4,times-1);
kochCurve(p4,p5,times-1);
kochCurve(p5,p2,times-1);
}
else{
line(p1.x,p1.y,p2.x,p2.y);
}
}
int main(int argC, char** argV)
{
int w,h,r;
point p1,p2;
if(argC!=4){
printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
}
else{
w = atoi(argV[1]);
h = atoi(argV[2]);
r = atoi(argV[3]);
initwindow(w,h,"Koch Curve");
p1 = (point){10,h-10};
p2 = (point){w-10,h-10};
kochCurve(p1,p2,r);
getch();
closegraph();
}
return 0;
}
|
Can you help me rewrite this code in C instead of VB, keeping it the same logically? | Sub draw()
Dim sh As Shape, sl As Shape
Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)
Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)
sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)
End Sub
| #include<graphics.h>
int main()
{
initwindow(320,240,"Red Pixel");
putpixel(100,100,RED);
getch();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d=createobject("scripting.dictionary")
redim b(ubound(a))
i=0
for each x in a
s=trim(x)
if len(s)>=9 then
if len(s)= 9 then d.add s,""
b(i)=s
i=i+1
end if
next
redim preserve b(i-1)
wscript.echo i
j=1
for i=0 to ubound(b)-9
s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_
mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)
if d.exists(s9) then
wscript.echo j,s9
d.remove(s9)
j=j+1
end if
next
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 80
#define MIN_LENGTH 9
#define WORD_SIZE (MIN_LENGTH + 1)
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int word_compare(const void* p1, const void* p2) {
return memcmp(p1, p2, WORD_SIZE);
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
char* words = xmalloc(WORD_SIZE * capacity);
while (fgets(line, sizeof(line), in)) {
size_t len = strlen(line) - 1;
if (len < MIN_LENGTH)
continue;
line[len] = '\0';
if (size == capacity) {
capacity *= 2;
words = xrealloc(words, WORD_SIZE * capacity);
}
memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);
++size;
}
fclose(in);
qsort(words, size, WORD_SIZE, word_compare);
int count = 0;
char prev_word[WORD_SIZE] = { 0 };
for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {
char word[WORD_SIZE] = { 0 };
for (size_t j = 0; j < MIN_LENGTH; ++j)
word[j] = words[(i + j) * WORD_SIZE + j];
if (word_compare(word, prev_word) == 0)
continue;
if (bsearch(word, words, size, WORD_SIZE, word_compare))
printf("%2d. %s\n", ++count, word);
memcpy(prev_word, word, WORD_SIZE);
}
free(words);
return EXIT_SUCCESS;
}
|
Convert this VB block to C, preserving its control flow and logic. |
Function BFInpt(s, sp, d, dp, i, ip, o)
While sp < Len(s)
Select Case Mid(s, sp + 1, 1)
Case "+"
newd = Asc(d(dp)) + 1
If newd > 255 Then newd = newd Mod 256
d(dp) = Chr(newd)
Case "-"
newd = Asc(d(dp)) - 1
If newd < 0 Then newd = (newd Mod 256) + 256
d(dp) = Chr(newd)
Case ">"
dp = dp + 1
If dp > UBound(d) Then
ReDim Preserve d(UBound(d) + 1)
d(dp) = Chr(0)
End If
Case "<"
dp = dp - 1
Case "."
o = o & d(dp)
Case ","
If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)
Case "["
If Asc(d(dp)) = 0 Then
bracket = 1
While bracket And sp < Len(s)
sp = sp + 1
If Mid(s, sp + 1, 1) = "[" Then
bracket = bracket + 1
ElseIf Mid(s, sp + 1, 1) = "]" Then
bracket = bracket - 1
End If
WEnd
Else
pos = sp - 1
sp = sp + 1
If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos
End If
Case "]"
BFInpt = Asc(d(dp)) <> 0
Exit Function
End Select
sp = sp + 1
WEnd
End Function
Function BFuck(source, input)
Dim data() : ReDim data(0)
data(0) = Chr(0)
DataPtr = 0
SrcPtr = 0
InputPtr = 0
output = ""
BFInpt source , SrcPtr , _
data , DataPtr , _
input , InputPtr , _
output
BFuck = output
End Function
code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _
">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++."
inpstr = ""
WScript.StdOut.Write BFuck(code, inpstr)
| #include <stdio.h>
int main(){
int ptr=0, i=0, cell[7];
for( i=0; i<7; ++i) cell[i]=0;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 8;
while(cell[ptr])
{
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 9;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 2;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
cell[ptr]+= 1;
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 4;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 7;
putchar(cell[ptr]);
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 7;
putchar(cell[ptr]);
ptr-= 3;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 15;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
cell[ptr]-= 6;
putchar(cell[ptr]);
cell[ptr]-= 8;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
putchar(cell[ptr]);
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 4;
putchar(cell[ptr]);
return 0;
}
|
Port the following code from VB to C with equivalent syntax and logic. |
Function BFInpt(s, sp, d, dp, i, ip, o)
While sp < Len(s)
Select Case Mid(s, sp + 1, 1)
Case "+"
newd = Asc(d(dp)) + 1
If newd > 255 Then newd = newd Mod 256
d(dp) = Chr(newd)
Case "-"
newd = Asc(d(dp)) - 1
If newd < 0 Then newd = (newd Mod 256) + 256
d(dp) = Chr(newd)
Case ">"
dp = dp + 1
If dp > UBound(d) Then
ReDim Preserve d(UBound(d) + 1)
d(dp) = Chr(0)
End If
Case "<"
dp = dp - 1
Case "."
o = o & d(dp)
Case ","
If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)
Case "["
If Asc(d(dp)) = 0 Then
bracket = 1
While bracket And sp < Len(s)
sp = sp + 1
If Mid(s, sp + 1, 1) = "[" Then
bracket = bracket + 1
ElseIf Mid(s, sp + 1, 1) = "]" Then
bracket = bracket - 1
End If
WEnd
Else
pos = sp - 1
sp = sp + 1
If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos
End If
Case "]"
BFInpt = Asc(d(dp)) <> 0
Exit Function
End Select
sp = sp + 1
WEnd
End Function
Function BFuck(source, input)
Dim data() : ReDim data(0)
data(0) = Chr(0)
DataPtr = 0
SrcPtr = 0
InputPtr = 0
output = ""
BFInpt source , SrcPtr , _
data , DataPtr , _
input , InputPtr , _
output
BFuck = output
End Function
code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _
">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++."
inpstr = ""
WScript.StdOut.Write BFuck(code, inpstr)
| #include <stdio.h>
int main(){
int ptr=0, i=0, cell[7];
for( i=0; i<7; ++i) cell[i]=0;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 8;
while(cell[ptr])
{
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 9;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 2;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
cell[ptr]+= 1;
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 4;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 7;
putchar(cell[ptr]);
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 7;
putchar(cell[ptr]);
ptr-= 3;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 15;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
cell[ptr]-= 6;
putchar(cell[ptr]);
cell[ptr]-= 8;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
putchar(cell[ptr]);
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 4;
putchar(cell[ptr]);
return 0;
}
|
Port the provided VB code into C while preserving the original functionality. | Private Function unicode_2_utf8(x As Long) As Byte()
Dim y() As Byte
Dim r As Long
Select Case x
Case 0 To &H7F
ReDim y(0)
y(0) = x
Case &H80 To &H7FF
ReDim y(1)
y(0) = 192 + x \ 64
y(1) = 128 + x Mod 64
Case &H800 To &H7FFF
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case 32768 To 65535
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case &H10000 To &H10FFFF
ReDim y(3)
y(3) = 128 + x Mod 64
r = x \ 64
y(2) = 128 + r Mod 64
r = r \ 64
y(1) = 128 + r Mod 64
y(0) = 240 + r \ 64
Case Else
MsgBox "what else?" & x & " " & Hex(x)
End Select
unicode_2_utf8 = y
End Function
Private Function utf8_2_unicode(x() As Byte) As Long
Dim first As Long, second As Long, third As Long, fourth As Long
Dim total As Long
Select Case UBound(x) - LBound(x)
Case 0
If x(0) < 128 Then
total = x(0)
Else
MsgBox "highest bit set error"
End If
Case 1
If x(0) \ 32 = 6 Then
first = x(0) Mod 32
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
Else
MsgBox "mask error"
End If
Else
MsgBox "leading byte error"
End If
total = 64 * first + second
Case 2
If x(0) \ 16 = 14 Then
first = x(0) Mod 16
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error middle byte"
End If
Else
MsgBox "leading byte error"
End If
total = 4096 * first + 64 * second + third
Case 3
If x(0) \ 8 = 30 Then
first = x(0) Mod 8
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
If x(3) \ 64 = 2 Then
fourth = x(3) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error third byte"
End If
Else
MsgBox "mask error second byte"
End If
Else
MsgBox "mask error leading byte"
End If
total = CLng(262144 * first + 4096 * second + 64 * third + fourth)
Case Else
MsgBox "more bytes than expected"
End Select
utf8_2_unicode = total
End Function
Public Sub program()
Dim cp As Variant
Dim r() As Byte, s As String
cp = [{65, 246, 1046, 8364, 119070}]
Debug.Print "ch unicode UTF-8 encoded decoded"
For Each cpi In cp
r = unicode_2_utf8(CLng(cpi))
On Error Resume Next
s = CStr(Hex(cpi))
Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s,
If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s,
s = ""
For Each yz In r
s = s & CStr(Hex(yz)) & " "
Next yz
Debug.Print String$(13 - Len(s), " "); s;
s = CStr(Hex(utf8_2_unicode(r)))
Debug.Print String$(8 - Len(s), " "); s
Next cpi
End Sub
| #include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct {
char mask;
char lead;
uint32_t beg;
uint32_t end;
int bits_stored;
}utf_t;
utf_t * utf[] = {
[0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 },
[1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 },
[2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 },
[3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 },
[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 },
&(utf_t){0},
};
int codepoint_len(const uint32_t cp);
int utf8_len(const char ch);
char *to_utf8(const uint32_t cp);
uint32_t to_cp(const char chr[4]);
int codepoint_len(const uint32_t cp)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((cp >= (*u)->beg) && (cp <= (*u)->end)) {
break;
}
++len;
}
if(len > 4)
exit(1);
return len;
}
int utf8_len(const char ch)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((ch & ~(*u)->mask) == (*u)->lead) {
break;
}
++len;
}
if(len > 4) {
exit(1);
}
return len;
}
char *to_utf8(const uint32_t cp)
{
static char ret[5];
const int bytes = codepoint_len(cp);
int shift = utf[0]->bits_stored * (bytes - 1);
ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;
shift -= utf[0]->bits_stored;
for(int i = 1; i < bytes; ++i) {
ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;
shift -= utf[0]->bits_stored;
}
ret[bytes] = '\0';
return ret;
}
uint32_t to_cp(const char chr[4])
{
int bytes = utf8_len(*chr);
int shift = utf[0]->bits_stored * (bytes - 1);
uint32_t codep = (*chr++ & utf[bytes]->mask) << shift;
for(int i = 1; i < bytes; ++i, ++chr) {
shift -= utf[0]->bits_stored;
codep |= ((char)*chr & utf[0]->mask) << shift;
}
return codep;
}
int main(void)
{
const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};
printf("Character Unicode UTF-8 encoding (hex)\n");
printf("----------------------------------------\n");
char *utf8;
uint32_t codepoint;
for(in = input; *in; ++in) {
utf8 = to_utf8(*in);
codepoint = to_cp(utf8);
printf("%s U+%-7.4x", utf8, codepoint);
for(int i = 0; utf8[i] && i < 4; ++i) {
printf("%hhx ", utf8[i]);
}
printf("\n");
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in VB. |
n=8
pattern="1001011001101001"
size=n*n: w=len(size)
mult=n\4
wscript.echo "Magic square : " & n & " x " & n
i=0
For r=0 To n-1
l=""
For c=0 To n-1
bit=Mid(pattern, c\mult+(r\mult)*4+1, 1)
If bit="1" Then t=i+1 Else t=size-i
l=l & Right(Space(w) & t, w) & " "
i=i+1
Next
wscript.echo l
Next
wscript.echo "Magic constant=" & (n*n+1)*n/2
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
}
|
Generate a C translation of this VB snippet without changing its computational steps. | Function mtf_encode(s)
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122
symbol_table.Add Chr(j)
Next
output = ""
For i = 1 To Len(s)
char = Mid(s,i,1)
If i = Len(s) Then
output = output & symbol_table.IndexOf(char,0)
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
Else
output = output & symbol_table.IndexOf(char,0) & " "
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_encode = output
End Function
Function mtf_decode(s)
code = Split(s," ")
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122
symbol_table.Add Chr(j)
Next
output = ""
For i = 0 To UBound(code)
char = symbol_table(code(i))
output = output & char
If code(i) <> 0 Then
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_decode = output
End Function
wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
mtf_decode(mtf_encode(word)) & "."
WScript.StdOut.WriteBlankLines(1)
Next
| #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int move_to_front(char *str,char c)
{
char *q,*p;
int shift=0;
p=(char *)malloc(strlen(str)+1);
strcpy(p,str);
q=strchr(p,c);
shift=q-p;
strncpy(str+1,p,shift);
str[0]=c;
free(p);
return shift;
}
void decode(int* pass,int size,char *sym)
{
int i,index;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=table[pass[i]];
index=move_to_front(table,c);
if(pass[i]!=index) printf("there is an error");
sym[i]=c;
}
sym[size]='\0';
}
void encode(char *sym,int size,int *pass)
{
int i=0;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=sym[i];
pass[i]=move_to_front(table,c);
}
}
int check(char *sym,int size,int *pass)
{
int *pass2=malloc(sizeof(int)*size);
char *sym2=malloc(sizeof(char)*size);
int i,val=1;
encode(sym,size,pass2);
i=0;
while(i<size && pass[i]==pass2[i])i++;
if(i!=size)val=0;
decode(pass,size,sym2);
if(strcmp(sym,sym2)!=0)val=0;
free(sym2);
free(pass2);
return val;
}
int main()
{
char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
int pass[MAX_SIZE]={0};
int i,len,j;
for(i=0;i<3;i++)
{
len=strlen(sym[i]);
encode(sym[i],len,pass);
printf("%s : [",sym[i]);
for(j=0;j<len;j++)
printf("%d ",pass[j]);
printf("]\n");
if(check(sym[i],len,pass))
printf("Correct :)\n");
else
printf("Incorrect :(\n");
}
return 0;
}
|
Write the same code in C as shown below in VB. | Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
| #include <stdlib.h>
int main()
{
system("ls");
return 0;
}
|
Port the following code from VB to C with equivalent syntax and logic. | Option explicit
Function fileexists(fn)
fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function
Function xmlvalid(strfilename)
Dim xmldoc,xmldoc2,objSchemas
Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
If fileexists(Replace(strfilename,".xml",".dtd")) Then
xmlDoc.setProperty "ProhibitDTD", False
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
xmlDoc.setProperty "ProhibitDTD", True
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc2.validateOnParse = True
xmlDoc2.async = False
xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
objSchemas.Add "", xmlDoc2
Else
Set xmlvalid= Nothing:Exit Function
End If
Set xmlvalid=xmldoc.parseError
End Function
Sub displayerror (parserr)
Dim strresult
If parserr is Nothing Then
strresult= "could not find dtd or xsd for " & strFileName
Else
With parserr
Select Case .errorcode
Case 0
strResult = "Valid: " & strFileName & vbCr
Case Else
strResult = vbCrLf & "ERROR! Failed to validate " & _
strFileName & vbCrLf &.reason & vbCr & _
"Error code: " & .errorCode & ", Line: " & _
.line & ", Character: " & _
.linepos & ", Source: """ & _
.srcText & """ - " & vbCrLf
End Select
End With
End If
WScript.Echo strresult
End Sub
Dim strfilename
strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)
| #include <libxml/xmlschemastypes.h>
int main(int argC, char** argV)
{
if (argC <= 2) {
printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]);
return 0;
}
xmlDocPtr doc;
xmlSchemaPtr schema = NULL;
xmlSchemaParserCtxtPtr ctxt;
char *XMLFileName = argV[1];
char *XSDFileName = argV[2];
int ret;
xmlLineNumbersDefault(1);
ctxt = xmlSchemaNewParserCtxt(XSDFileName);
xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
schema = xmlSchemaParse(ctxt);
xmlSchemaFreeParserCtxt(ctxt);
doc = xmlReadFile(XMLFileName, NULL, 0);
if (doc == NULL){
fprintf(stderr, "Could not parse %s\n", XMLFileName);
}
else{
xmlSchemaValidCtxtPtr ctxt;
ctxt = xmlSchemaNewValidCtxt(schema);
xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
ret = xmlSchemaValidateDoc(ctxt, doc);
if (ret == 0){
printf("%s validates\n", XMLFileName);
}
else if (ret > 0){
printf("%s fails to validate\n", XMLFileName);
}
else{
printf("%s validation generated an internal error\n", XMLFileName);
}
xmlSchemaFreeValidCtxt(ctxt);
xmlFreeDoc(doc);
}
if(schema != NULL)
xmlSchemaFree(schema);
xmlSchemaCleanupTypes();
xmlCleanupParser();
xmlMemoryDump();
return 0;
}
|
Please provide an equivalent version of this VB code in C. |
option explicit
const x_=0
const y_=1
const z_=2
const r_=3
function clamp(x,b,t)
if x<b then
clamp=b
elseif x>t then
clamp =t
else
clamp=x
end if
end function
function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function
function normal (byval v)
dim ilen:ilen=1/sqr(dot(v,v)):
v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:
normal=v:
end function
function hittest(s,x,y)
dim z
z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2
if z>=0 then
z=sqr(z)
hittest=array(s(z_)-z,s(z_)+z)
else
hittest=0
end if
end function
sub deathstar(pos, neg, sun, k, amb)
dim x,y,shades,result,shade,hp,hn,xx,b
shades=array(" ",".",":","!","*","o","e","&","#","%","@")
for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5
for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5
hp=hittest (pos, x, y)
hn=hittest(neg,x,y)
if not isarray(hp) then
result=0
elseif not isarray(hn) then
result=1
elseif hn(0)>hp(0) then
result=1
elseif hn(1)>hp(1) then
result=0
elseif hn(1)>hp(0) then
result=2
else
result=1
end if
shade=-1
select case result
case 0
shade=0
case 1
xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))
case 2
xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))
end select
if shade <>0 then
b=dot(sun,xx)^k+amb
shade=clamp((1-b) *ubound(shades),1,ubound(shades))
end if
wscript.stdout.write string(2,shades(shade))
next
wscript.stdout.write vbcrlf
next
end sub
deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1
| #include <stdio.h>
#include <math.h>
#include <unistd.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { -50, 0, 50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
typedef struct { double cx, cy, cz, r; } sphere_t;
sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };
int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)
{
double zsq;
x -= sph->cx;
y -= sph->cy;
zsq = sph->r * sph->r - (x * x + y * y);
if (zsq < 0) return 0;
zsq = sqrt(zsq);
*z1 = sph->cz - zsq;
*z2 = sph->cz + zsq;
return 1;
}
void draw_sphere(double k, double ambient)
{
int i, j, intensity, hit_result;
double b;
double vec[3], x, y, zb1, zb2, zs1, zs2;
for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {
y = i + .5;
for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {
x = (j - pos.cx) / 2. + .5 + pos.cx;
if (!hit_sphere(&pos, x, y, &zb1, &zb2))
hit_result = 0;
else if (!hit_sphere(&neg, x, y, &zs1, &zs2))
hit_result = 1;
else if (zs1 > zb1) hit_result = 1;
else if (zs2 > zb2) hit_result = 0;
else if (zs2 > zb1) hit_result = 2;
else hit_result = 1;
switch(hit_result) {
case 0:
putchar('+');
continue;
case 1:
vec[0] = x - pos.cx;
vec[1] = y - pos.cy;
vec[2] = zb1 - pos.cz;
break;
default:
vec[0] = neg.cx - x;
vec[1] = neg.cy - y;
vec[2] = neg.cz - zs2;
}
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
}
putchar('\n');
}
}
int main()
{
double ang = 0;
while (1) {
printf("\033[H");
light[1] = cos(ang * 2);
light[2] = cos(ang);
light[0] = sin(ang);
normalize(light);
ang += .05;
draw_sphere(2, .3);
usleep(100000);
}
return 0;
}
|
Produce a language-to-language conversion: from VB to C, same semantics. | Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print " Chi-squared test for given frequencies"
Debug.Print "X-squared ="; ChiSquared; ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Public Sub test()
Dim O() As Variant
O = [{199809,200665,199607,200270,199649}]
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """"
O = [{522573,244456,139979,71531,21461}]
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """"
End Sub
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
typedef double (* Ifctn)( double t);
double Simpson3_8( Ifctn f, double a, double b, int N)
{
int j;
double l1;
double h = (b-a)/N;
double h1 = h/3.0;
double sum = f(a) + f(b);
for (j=3*N-1; j>0; j--) {
l1 = (j%3)? 3.0 : 2.0;
sum += l1*f(a+h1*j) ;
}
return h*sum/8.0;
}
#define A 12
double Gamma_Spouge( double z )
{
int k;
static double cspace[A];
static double *coefs = NULL;
double accum;
double a = A;
if (!coefs) {
double k1_factrl = 1.0;
coefs = cspace;
coefs[0] = sqrt(2.0*M_PI);
for(k=1; k<A; k++) {
coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;
k1_factrl *= -k;
}
}
accum = coefs[0];
for (k=1; k<A; k++) {
accum += coefs[k]/(z+k);
}
accum *= exp(-(z+a)) * pow(z+a, z+0.5);
return accum/z;
}
double aa1;
double f0( double t)
{
return pow(t, aa1)*exp(-t);
}
double GammaIncomplete_Q( double a, double x)
{
double y, h = 1.5e-2;
y = aa1 = a-1;
while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4;
if (y>x) y=x;
return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);
}
|
Write a version of this VB function in C with identical behavior. | Module Module1
Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)
Dim out As New List(Of String)
Dim comma = False
While Not String.IsNullOrEmpty(s)
Dim gs = GetItem(s, depth)
Dim g = gs.Item1
s = gs.Item2
If String.IsNullOrEmpty(s) Then
Exit While
End If
out.AddRange(g)
If s(0) = "}" Then
If comma Then
Return Tuple.Create(out, s.Substring(1))
End If
Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1))
End If
If s(0) = "," Then
comma = True
s = s.Substring(1)
End If
End While
Return Nothing
End Function
Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)
Dim out As New List(Of String) From {""}
While Not String.IsNullOrEmpty(s)
Dim c = s(0)
If depth > 0 AndAlso (c = "," OrElse c = "}") Then
Return Tuple.Create(out, s)
End If
If c = "{" Then
Dim x = GetGroup(s.Substring(1), depth + 1)
If Not IsNothing(x) Then
Dim tout As New List(Of String)
For Each a In out
For Each b In x.Item1
tout.Add(a + b)
Next
Next
out = tout
s = x.Item2
Continue While
End If
End If
If c = "\" AndAlso s.Length > 1 Then
c += s(1)
s = s.Substring(1)
End If
out = out.Select(Function(a) a + c).ToList()
s = s.Substring(1)
End While
Return Tuple.Create(out, s)
End Function
Sub Main()
For Each s In {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\, again\, }}more }cowbell!",
"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
}
Dim fmt = "{0}" + vbNewLine + vbTab + "{1}"
Dim parts = GetItem(s)
Dim res = String.Join(vbNewLine + vbTab, parts.Item1)
Console.WriteLine(fmt, s, res)
Next
End Sub
End Module
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
typedef unsigned char character;
typedef character *string;
typedef struct node_t node;
struct node_t {
enum tag_t {
NODE_LEAF,
NODE_TREE,
NODE_SEQ,
} tag;
union {
string str;
node *root;
} data;
node *next;
};
node *allocate_node(enum tag_t tag) {
node *n = malloc(sizeof(node));
if (n == NULL) {
fprintf(stderr, "Failed to allocate node for tag: %d\n", tag);
exit(1);
}
n->tag = tag;
n->next = NULL;
return n;
}
node *make_leaf(string str) {
node *n = allocate_node(NODE_LEAF);
n->data.str = str;
return n;
}
node *make_tree() {
node *n = allocate_node(NODE_TREE);
n->data.root = NULL;
return n;
}
node *make_seq() {
node *n = allocate_node(NODE_SEQ);
n->data.root = NULL;
return n;
}
void deallocate_node(node *n) {
if (n == NULL) {
return;
}
deallocate_node(n->next);
n->next = NULL;
if (n->tag == NODE_LEAF) {
free(n->data.str);
n->data.str = NULL;
} else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {
deallocate_node(n->data.root);
n->data.root = NULL;
} else {
fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag);
exit(1);
}
free(n);
}
void append(node *root, node *elem) {
if (root == NULL) {
fprintf(stderr, "Cannot append to uninitialized node.");
exit(1);
}
if (elem == NULL) {
return;
}
if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {
if (root->data.root == NULL) {
root->data.root = elem;
} else {
node *it = root->data.root;
while (it->next != NULL) {
it = it->next;
}
it->next = elem;
}
} else {
fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag);
exit(1);
}
}
size_t count(node *n) {
if (n == NULL) {
return 0;
}
if (n->tag == NODE_LEAF) {
return 1;
}
if (n->tag == NODE_TREE) {
size_t sum = 0;
node *it = n->data.root;
while (it != NULL) {
sum += count(it);
it = it->next;
}
return sum;
}
if (n->tag == NODE_SEQ) {
size_t prod = 1;
node *it = n->data.root;
while (it != NULL) {
prod *= count(it);
it = it->next;
}
return prod;
}
fprintf(stderr, "Cannot count node with tag: %d\n", n->tag);
exit(1);
}
void expand(node *n, size_t pos) {
if (n == NULL) {
return;
}
if (n->tag == NODE_LEAF) {
printf(n->data.str);
} else if (n->tag == NODE_TREE) {
node *it = n->data.root;
while (true) {
size_t cnt = count(it);
if (pos < cnt) {
expand(it, pos);
break;
}
pos -= cnt;
it = it->next;
}
} else if (n->tag == NODE_SEQ) {
size_t prod = pos;
node *it = n->data.root;
while (it != NULL) {
size_t cnt = count(it);
size_t rem = prod % cnt;
expand(it, rem);
it = it->next;
}
} else {
fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag);
exit(1);
}
}
string allocate_string(string src) {
size_t len = strlen(src);
string out = calloc(len + 1, sizeof(character));
if (out == NULL) {
fprintf(stderr, "Failed to allocate a copy of the string.");
exit(1);
}
strcpy(out, src);
return out;
}
node *parse_seq(string input, size_t *pos);
node *parse_tree(string input, size_t *pos) {
node *root = make_tree();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
size_t depth = 0;
bool asSeq = false;
bool allow = false;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = '\\';
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
asSeq = true;
depth++;
} else if (c == '}') {
if (depth-- > 0) {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
} else {
append(root, make_leaf(allocate_string(buffer)));
}
break;
}
} else if (c == ',') {
if (depth == 0) {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
bufpos = 0;
buffer[bufpos] = 0;
asSeq = false;
} else {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
return root;
}
node *parse_seq(string input, size_t *pos) {
node *root = make_seq();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
node *tree = parse_tree(input, pos);
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
append(root, tree);
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
return root;
}
void test(string input) {
size_t pos = 0;
node *n = parse_seq(input, &pos);
size_t cnt = count(n);
size_t i;
printf("Pattern: %s\n", input);
for (i = 0; i < cnt; i++) {
expand(n, i);
printf("\n");
}
printf("\n");
deallocate_node(n);
}
int main() {
test("~/{Downloads,Pictures}/*.{jpg,gif,png}");
test("It{{em,alic}iz,erat}e{d,}, please.");
test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!");
return 0;
}
|
Transform the following VB implementation into C, maintaining the same output and logic. |
Function no_arguments() As String
no_arguments = "ok"
End Function
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
Function optional_parameter(Optional argument1 = 1) As Integer
optional_parameter = argument1
End Function
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
Function return_value() As String
return_value = "ok"
End Function
Sub foo()
Debug.Print "subroutine",
End Sub
Function bar() As String
bar = "function"
End Function
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
Public Sub calling_a_function()
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
Debug.Print "fixed_number", , fixed_number(1, 1)
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
Debug.Print "variable number", variable_number([{"hello", "there"}])
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
statement
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
foo
Debug.Print , bar
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
|
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17);
v(.arg2=1);
v();
printf("%p", f);
double a = asin(1);
|
Transform the following VB implementation into C, maintaining the same output and logic. |
Function no_arguments() As String
no_arguments = "ok"
End Function
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
Function optional_parameter(Optional argument1 = 1) As Integer
optional_parameter = argument1
End Function
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
Function return_value() As String
return_value = "ok"
End Function
Sub foo()
Debug.Print "subroutine",
End Sub
Function bar() As String
bar = "function"
End Function
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
Public Sub calling_a_function()
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
Debug.Print "fixed_number", , fixed_number(1, 1)
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
Debug.Print "variable number", variable_number([{"hello", "there"}])
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
statement
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
foo
Debug.Print , bar
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
|
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17);
v(.arg2=1);
v();
printf("%p", f);
double a = asin(1);
|
Write the same code in C as shown below in VB. | VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 2265
ClientLeft = 60
ClientTop = 600
ClientWidth = 2175
LinkTopic = "Form1"
ScaleHeight = 2265
ScaleWidth = 2175
StartUpPosition = 3
Begin VB.CommandButton cmdRnd
Caption = "Random"
Height = 495
Left = 120
TabIndex = 2
Top = 1680
Width = 1215
End
Begin VB.CommandButton cmdInc
Caption = "Increment"
Height = 495
Left = 120
TabIndex = 1
Top = 1080
Width = 1215
End
Begin VB.TextBox txtValue
Height = 495
Left = 120
TabIndex = 0
Text = "0"
Top = 240
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Form_Load()
Randomize Timer
End Sub
Private Sub cmdRnd_Click()
If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11)
End Sub
Private Sub cmdInc_Click()
If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub
Private Sub txtValue_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 8, 43, 45, 48 To 57
Case Else
KeyAscii = 0
End Select
End Sub
| #include <windows.h>
#include "resource.h"
BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {
switch( msg ) {
case WM_INITDIALOG:
srand( GetTickCount() );
SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );
break;
case WM_COMMAND:
switch( LOWORD(wPar) ) {
case IDC_INCREMENT: {
UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );
SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );
} break;
case IDC_RANDOM: {
int reply = MessageBox( hwnd,
"Do you really want to\nget a random number?",
"Random input confirmation", MB_ICONQUESTION|MB_YESNO );
if( reply == IDYES )
SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );
} break;
case IDC_QUIT:
SendMessage( hwnd, WM_CLOSE, 0, 0 );
break;
default: ;
}
break;
case WM_CLOSE: {
int reply = MessageBox( hwnd,
"Do you really want to quit?",
"Quit confirmation", MB_ICONQUESTION|MB_YESNO );
if( reply == IDYES )
EndDialog( hwnd, 0 );
} break;
default: ;
}
return 0;
}
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {
return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );
}
|
Please provide an equivalent version of this VB code in C. | Dim chosen(10)
For j = 1 To 1000000
c = one_of_n(10)
chosen(c) = chosen(c) + 1
Next
For k = 1 To 10
WScript.StdOut.WriteLine k & ". " & chosen(k)
Next
Function one_of_n(n)
Randomize
For i = 1 To n
If Rnd(1) < 1/i Then
one_of_n = i
End If
Next
End Function
| #include <stdio.h>
#include <stdlib.h>
inline int irand(int n)
{
int r, randmax = RAND_MAX/n * n;
while ((r = rand()) >= randmax);
return r / (randmax / n);
}
inline int one_of_n(int n)
{
int i, r = 0;
for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
return r;
}
int main(void)
{
int i, r[10] = {0};
for (i = 0; i < 1000000; i++, r[one_of_n(10)]++);
for (i = 0; i < 10; i++)
printf("%d%c", r[i], i == 9 ? '\n':' ');
return 0;
}
|
Write the same code in C as shown below in VB. | Private Function ordinal(s As String) As String
Dim irregs As New Collection
irregs.Add "first", "one"
irregs.Add "second", "two"
irregs.Add "third", "three"
irregs.Add "fifth", "five"
irregs.Add "eighth", "eight"
irregs.Add "ninth", "nine"
irregs.Add "twelfth", "twelve"
Dim i As Integer
For i = Len(s) To 1 Step -1
ch = Mid(s, i, 1)
If ch = " " Or ch = "-" Then Exit For
Next i
On Error GoTo 1
ord = irregs(Right(s, Len(s) - i))
ordinal = Left(s, i) & ord
Exit Function
1:
If Right(s, 1) = "y" Then
s = Left(s, Len(s) - 1) & "ieth"
Else
s = s & "th"
End If
ordinal = s
End Function
Public Sub ordinals()
tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]
init
For i = 1 To UBound(tests)
Debug.Print ordinal(spell(tests(i)))
Next i
End Sub
| #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
typedef struct named_number_tag {
const char* cardinal;
const char* ordinal;
integer number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "billionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_small_name(const number_names* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const char* get_big_name(const named_number* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const named_number* get_named_number(integer n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
void append_number_name(GString* gstr, integer n, bool ordinal) {
if (n < 20)
g_string_append(gstr, get_small_name(&small[n], ordinal));
else if (n < 100) {
if (n % 10 == 0) {
g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));
} else {
g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));
g_string_append_c(gstr, '-');
g_string_append(gstr, get_small_name(&small[n % 10], ordinal));
}
} else {
const named_number* num = get_named_number(n);
integer p = num->number;
append_number_name(gstr, n/p, false);
g_string_append_c(gstr, ' ');
if (n % p == 0) {
g_string_append(gstr, get_big_name(num, ordinal));
} else {
g_string_append(gstr, get_big_name(num, false));
g_string_append_c(gstr, ' ');
append_number_name(gstr, n % p, ordinal);
}
}
}
GString* number_name(integer n, bool ordinal) {
GString* result = g_string_sized_new(8);
append_number_name(result, n, ordinal);
return result;
}
void test_ordinal(integer n) {
GString* name = number_name(n, true);
printf("%llu: %s\n", n, name->str);
g_string_free(name, TRUE);
}
int main() {
test_ordinal(1);
test_ordinal(2);
test_ordinal(3);
test_ordinal(4);
test_ordinal(5);
test_ordinal(11);
test_ordinal(15);
test_ordinal(21);
test_ordinal(42);
test_ordinal(65);
test_ordinal(98);
test_ordinal(100);
test_ordinal(101);
test_ordinal(272);
test_ordinal(300);
test_ordinal(750);
test_ordinal(23456);
test_ordinal(7891233);
test_ordinal(8007006005004003LL);
return 0;
}
|
Generate an equivalent C version of this VB code. | Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)) Then
If digit.Item(CStr(j)) = CInt(l) Then
c = c + 1
End If
ElseIf l = 0 Then
c = c + 1
Else
Exit For
End If
Next
If c = Len(n) Then
IsSelfDescribing = True
End If
End Function
start_time = Now
s = ""
For m = 1 To 100000000
If IsSelfDescribing(m) Then
WScript.StdOut.WriteLine m
End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
| #include <stdio.h>
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
}
int main()
{
int i;
for (i = 1; i < 100000000; i++)
if (self_desc(i)) printf("%d\n", i);
return 0;
}
|
Ensure the translated C code behaves exactly like the original VB snippet. | Module Module1
Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
Dim result As New List(Of Integer) From {
n
}
result.AddRange(seq)
Return result
End Function
Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
If pos > min_len OrElse seq(0) > n Then
Return Tuple.Create(min_len, 0)
End If
If seq(0) = n Then
Return Tuple.Create(pos, 1)
End If
If pos < min_len Then
Return TryPerm(0, pos, seq, n, min_len)
End If
Return Tuple.Create(min_len, 0)
End Function
Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
If i > pos Then
Return Tuple.Create(min_len, 0)
End If
Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)
Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)
If res2.Item1 < res1.Item1 Then
Return res2
End If
If res2.Item1 = res1.Item1 Then
Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)
End If
Throw New Exception("TryPerm exception")
End Function
Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)
Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)
End Function
Sub FindBrauer(num As Integer)
Dim res = InitTryPerm(num)
Console.WriteLine("N = {0}", num)
Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1)
Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2)
Console.WriteLine()
End Sub
Sub Main()
Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
Array.ForEach(nums, Sub(n) FindBrauer(n))
End Sub
End Module
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
typedef struct {
int x, y;
} pair;
int* example = NULL;
int exampleLen = 0;
void reverse(int s[], int len) {
int i, j, t;
for (i = 0, j = len - 1; i < j; ++i, --j) {
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);
pair checkSeq(int pos, int seq[], int n, int len, int minLen) {
pair p;
if (pos > minLen || seq[0] > n) {
p.x = minLen; p.y = 0;
return p;
}
else if (seq[0] == n) {
example = malloc(len * sizeof(int));
memcpy(example, seq, len * sizeof(int));
exampleLen = len;
p.x = pos; p.y = 1;
return p;
}
else if (pos < minLen) {
return tryPerm(0, pos, seq, n, len, minLen);
}
else {
p.x = minLen; p.y = 0;
return p;
}
}
pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {
int *seq2;
pair p, res1, res2;
size_t size = sizeof(int);
if (i > pos) {
p.x = minLen; p.y = 0;
return p;
}
seq2 = malloc((len + 1) * size);
memcpy(seq2 + 1, seq, len * size);
seq2[0] = seq[0] + seq[i];
res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);
res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);
free(seq2);
if (res2.x < res1.x)
return res2;
else if (res2.x == res1.x) {
p.x = res2.x; p.y = res1.y + res2.y;
return p;
}
else {
printf("Error in tryPerm\n");
p.x = 0; p.y = 0;
return p;
}
}
pair initTryPerm(int x, int minLen) {
int seq[1] = {1};
return tryPerm(0, 0, seq, x, 1, minLen);
}
void printArray(int a[], int len) {
int i;
printf("[");
for (i = 0; i < len; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
bool isBrauer(int a[], int len) {
int i, j;
bool ok;
for (i = 2; i < len; ++i) {
ok = FALSE;
for (j = i - 1; j >= 0; j--) {
if (a[i-1] + a[j] == a[i]) {
ok = TRUE;
break;
}
}
if (!ok) return FALSE;
}
return TRUE;
}
bool isAdditionChain(int a[], int len) {
int i, j, k;
bool ok, exit;
for (i = 2; i < len; ++i) {
if (a[i] > a[i - 1] * 2) return FALSE;
ok = FALSE; exit = FALSE;
for (j = i - 1; j >= 0; --j) {
for (k = j; k >= 0; --k) {
if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }
}
if (exit) break;
}
if (!ok) return FALSE;
}
if (example == NULL && !isBrauer(a, len)) {
example = malloc(len * sizeof(int));
memcpy(example, a, len * sizeof(int));
exampleLen = len;
}
return TRUE;
}
void nextChains(int index, int len, int seq[], int *pcount) {
for (;;) {
int i;
if (index < len - 1) {
nextChains(index + 1, len, seq, pcount);
}
if (seq[index] + len - 1 - index >= seq[len - 1]) return;
seq[index]++;
for (i = index + 1; i < len - 1; ++i) {
seq[i] = seq[i-1] + 1;
}
if (isAdditionChain(seq, len)) (*pcount)++;
}
}
int findNonBrauer(int num, int len, int brauer) {
int i, count = 0;
int *seq = malloc(len * sizeof(int));
seq[0] = 1;
seq[len - 1] = num;
for (i = 1; i < len - 1; ++i) {
seq[i] = seq[i - 1] + 1;
}
if (isAdditionChain(seq, len)) count = 1;
nextChains(2, len, seq, &count);
free(seq);
return count - brauer;
}
void findBrauer(int num, int minLen, int nbLimit) {
pair p = initTryPerm(num, minLen);
int actualMin = p.x, brauer = p.y, nonBrauer;
printf("\nN = %d\n", num);
printf("Minimum length of chains : L(%d) = %d\n", num, actualMin);
printf("Number of minimum length Brauer chains : %d\n", brauer);
if (brauer > 0) {
printf("Brauer example : ");
reverse(example, exampleLen);
printArray(example, exampleLen);
}
if (example != NULL) {
free(example);
example = NULL;
exampleLen = 0;
}
if (num <= nbLimit) {
nonBrauer = findNonBrauer(num, actualMin + 1, brauer);
printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer);
if (nonBrauer > 0) {
printf("Non-Brauer example : ");
printArray(example, exampleLen);
}
if (example != NULL) {
free(example);
example = NULL;
exampleLen = 0;
}
}
else {
printf("Non-Brauer analysis suppressed\n");
}
}
int main() {
int i;
int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};
printf("Searching for Brauer chains up to a minimum length of 12:\n");
for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);
return 0;
}
|
Generate an equivalent C version of this VB code. | Private Sub Repeat(rid As String, n As Integer)
For i = 1 To n
Application.Run rid
Next i
End Sub
Private Sub Hello()
Debug.Print "Hello"
End Sub
Public Sub main()
Repeat "Hello", 5
End Sub
| #include <stdio.h>
void repeat(void (*f)(void), unsigned int n) {
while (n-->0)
(*f)();
}
void example() {
printf("Example\n");
}
int main(int argc, char *argv[]) {
repeat(example, 4);
return 0;
}
|
Translate the given VB code snippet into C without altering its behavior. |
sub ensure_cscript()
if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then
createobject("wscript.shell").run "CSCRIPT //nologo """ &_
WScript.ScriptFullName &"""" ,,0
wscript.quit
end if
end sub
class bargraph
private bar,mn,mx,nn,cnt
Private sub class_initialize()
bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_
chrw(&h2586)&chrw(&h2587)&chrw(&h2588)
nn=8
end sub
public function bg (s)
a=split(replace(replace(s,","," ")," "," ")," ")
mn=999999:mx=-999999:cnt=ubound(a)+1
for i=0 to ubound(a)
a(i)=cdbl(trim(a(i)))
if a(i)>mx then mx=a(i)
if a(i)<mn then mn=a(i)
next
ss="Data: "
for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next
ss=ss+vbcrlf + "sparkline: "
for i=0 to ubound(a)
x=scale(a(i))
ss=ss & string(6,mid(bar,x,1))
next
bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _
" cnt: "& ubound(a)+1 &vbcrlf
end function
private function scale(x)
if x=<mn then
scale=1
elseif x>=mx then
scale=nn
else
scale=int(nn* (x-mn)/(mx-mn)+1)
end if
end function
end class
ensure_cscript
set b=new bargraph
wscript.stdout.writeblanklines 2
wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1")
wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5")
wscript.echo b.bg("0, 1, 19, 20")
wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999")
set b=nothing
wscript.echo "If bars don
"font to DejaVu Sans Mono or any other that has the bargrph characters" & _
vbcrlf
wscript.stdout.write "Press any key.." : wscript.stdin.read 1
| #include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>
int main(int argC,char* argV[])
{
double* arr,min,max;
char* str;
int i,len;
if(argC == 1)
printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
else{
arr = (double*)malloc((argC-1)*sizeof(double));
for(i=1;i<argC;i++){
len = strlen(argV[i]);
if(argV[i][len-1]==','){
str = (char*)malloc(len*sizeof(char));
strncpy(str,argV[i],len-1);
arr[i-1] = atof(str);
free(str);
}
else
arr[i-1] = atof(argV[i]);
if(i==1){
min = arr[i-1];
max = arr[i-1];
}
else{
min=(min<arr[i-1]?min:arr[i-1]);
max=(max>arr[i-1]?max:arr[i-1]);
}
}
printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min);
setlocale(LC_ALL, "");
for(i=1;i<argC;i++){
printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));
}
}
return 0;
}
|
Convert this VB snippet to C and keep its semantics consistent. |
sub ensure_cscript()
if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then
createobject("wscript.shell").run "CSCRIPT //nologo """ &_
WScript.ScriptFullName &"""" ,,0
wscript.quit
end if
end sub
class bargraph
private bar,mn,mx,nn,cnt
Private sub class_initialize()
bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_
chrw(&h2586)&chrw(&h2587)&chrw(&h2588)
nn=8
end sub
public function bg (s)
a=split(replace(replace(s,","," ")," "," ")," ")
mn=999999:mx=-999999:cnt=ubound(a)+1
for i=0 to ubound(a)
a(i)=cdbl(trim(a(i)))
if a(i)>mx then mx=a(i)
if a(i)<mn then mn=a(i)
next
ss="Data: "
for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next
ss=ss+vbcrlf + "sparkline: "
for i=0 to ubound(a)
x=scale(a(i))
ss=ss & string(6,mid(bar,x,1))
next
bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _
" cnt: "& ubound(a)+1 &vbcrlf
end function
private function scale(x)
if x=<mn then
scale=1
elseif x>=mx then
scale=nn
else
scale=int(nn* (x-mn)/(mx-mn)+1)
end if
end function
end class
ensure_cscript
set b=new bargraph
wscript.stdout.writeblanklines 2
wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1")
wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5")
wscript.echo b.bg("0, 1, 19, 20")
wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999")
set b=nothing
wscript.echo "If bars don
"font to DejaVu Sans Mono or any other that has the bargrph characters" & _
vbcrlf
wscript.stdout.write "Press any key.." : wscript.stdin.read 1
| #include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>
int main(int argC,char* argV[])
{
double* arr,min,max;
char* str;
int i,len;
if(argC == 1)
printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
else{
arr = (double*)malloc((argC-1)*sizeof(double));
for(i=1;i<argC;i++){
len = strlen(argV[i]);
if(argV[i][len-1]==','){
str = (char*)malloc(len*sizeof(char));
strncpy(str,argV[i],len-1);
arr[i-1] = atof(str);
free(str);
}
else
arr[i-1] = atof(argV[i]);
if(i==1){
min = arr[i-1];
max = arr[i-1];
}
else{
min=(min<arr[i-1]?min:arr[i-1]);
max=(max>arr[i-1]?max:arr[i-1]);
}
}
printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min);
setlocale(LC_ALL, "");
for(i=1;i<argC;i++){
printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));
}
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | Private Function mul_inv(a As Long, n As Long) As Variant
If n < 0 Then n = -n
If a < 0 Then a = n - ((-a) Mod n)
Dim t As Long: t = 0
Dim nt As Long: nt = 1
Dim r As Long: r = n
Dim nr As Long: nr = a
Dim q As Long
Do While nr <> 0
q = r \ nr
tmp = t
t = nt
nt = tmp - q * nt
tmp = r
r = nr
nr = tmp - q * nr
Loop
If r > 1 Then
mul_inv = "a is not invertible"
Else
If t < 0 Then t = t + n
mul_inv = t
End If
End Function
Public Sub mi()
Debug.Print mul_inv(42, 2017)
Debug.Print mul_inv(40, 1)
Debug.Print mul_inv(52, -217)
Debug.Print mul_inv(-486, 217)
Debug.Print mul_inv(40, 2018)
End Sub
| #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
printf("%d\n", mul_inv(42, 2017));
return 0;
}
|
Write a version of this VB function in C with identical behavior. | Class HTTPSock
Inherits TCPSocket
Event Sub DataAvailable()
Dim headers As New InternetHeaders
headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!")))
headers.AppendHeader("Content-Type", "text/plain")
headers.AppendHeader("Content-Encoding", "identity")
headers.AppendHeader("Connection", "close")
Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!"
Me.Write(data)
Me.Close
End Sub
End Class
Class HTTPServ
Inherits ServerSocket
Event Sub AddSocket() As TCPSocket
Return New HTTPSock
End Sub
End Class
Class App
Inherits Application
Event Sub Run(Args() As String)
Dim sock As New HTTPServ
sock.Port = 8080
sock.Listen()
While True
App.DoEvents
Wend
End Sub
End Class
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>"
"<style>body { background-color: #111 }"
"h1 { font-size:4cm; text-align: center; color: black;"
" text-shadow: 0 0 2mm red}</style></head>"
"<body><h1>Goodbye, world!</h1></body></html>\r\n";
int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}
listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
printf("got connection\n");
if (client_fd == -1) {
perror("Can't accept");
continue;
}
write(client_fd, response, sizeof(response) - 1);
close(client_fd);
}
}
|
Can you help me rewrite this code in C instead of VB, keeping it the same logically? | Option Strict On
Option Explicit On
Imports System.IO
Module OwnDigitsPowerSum
Public Sub Main
Dim used(9) As Integer
Dim check(9) As Integer
Dim power(9, 9) As Long
For i As Integer = 0 To 9
check(i) = 0
Next i
For i As Integer = 1 To 9
power(1, i) = i
Next i
For j As Integer = 2 To 9
For i As Integer = 1 To 9
power(j, i) = power(j - 1, i) * i
Next i
Next j
Dim lowestDigit(9) As Integer
lowestDigit(1) = -1
lowestDigit(2) = -1
Dim p10 As Long = 100
For i As Integer = 3 To 9
For p As Integer = 2 To 9
Dim np As Long = power(i, p) * i
If Not ( np < p10) Then Exit For
lowestDigit(i) = p
Next p
p10 *= 10
Next i
Dim maxZeros(9, 9) As Integer
For i As Integer = 1 To 9
For j As Integer = 1 To 9
maxZeros(i, j) = 0
Next j
Next i
p10 = 1000
For w As Integer = 3 To 9
For d As Integer = lowestDigit(w) To 9
Dim nz As Integer = 9
Do
If nz < 0 Then
Exit Do
Else
Dim np As Long = power(w, d) * nz
IF Not ( np > p10) Then Exit Do
End If
nz -= 1
Loop
maxZeros(w, d) = If(nz > w, 0, w - nz)
Next d
p10 *= 10
Next w
Dim numbers(100) As Long
Dim nCount As Integer = 0
Dim tryCount As Integer = 0
Dim digits(9) As Integer
For d As Integer = 1 To 9
digits(d) = 9
Next d
For d As Integer = 0 To 8
used(d) = 0
Next d
used(9) = 9
Dim width As Integer = 9
Dim last As Integer = width
p10 = 100000000
Do While width > 2
tryCount += 1
Dim dps As Long = 0
check(0) = used(0)
For i As Integer = 1 To 9
check(i) = used(i)
If used(i) <> 0 Then
dps += used(i) * power(width, i)
End If
Next i
Dim n As Long = dps
Do
check(CInt(n Mod 10)) -= 1
n \= 10
Loop Until n <= 0
Dim reduceWidth As Boolean = dps <= p10
If Not reduceWidth Then
Dim zCount As Integer = 0
For i As Integer = 0 To 9
If check(i) <> 0 Then Exit For
zCount+= 1
Next i
If zCount = 10 Then
nCount += 1
numbers(nCount) = dps
End If
used(digits(last)) -= 1
digits(last) -= 1
If digits(last) = 0 Then
If used(0) >= maxZeros(width, digits(1)) Then
digits(last) = -1
End If
End If
If digits(last) >= 0 Then
used(digits(last)) += 1
Else
Dim prev As Integer = last
Do
prev -= 1
If prev < 1 Then
Exit Do
Else
used(digits(prev)) -= 1
digits(prev) -= 1
IF digits(prev) >= 0 Then Exit Do
End If
Loop
If prev > 0 Then
If prev = 1 Then
If digits(1) <= lowestDigit(width) Then
prev = 0
End If
End If
If prev <> 0 Then
used(digits(prev)) += 1
For i As Integer = prev + 1 To width
digits(i) = digits(prev)
used(digits(prev)) += 1
Next i
End If
End If
If prev <= 0 Then
reduceWidth = True
End If
End If
End If
If reduceWidth Then
last -= 1
width = last
If last > 0 Then
For d As Integer = 1 To last
digits(d) = 9
Next d
For d As Integer = last + 1 To 9
digits(d) = -1
Next d
For d As Integer = 0 To 8
used(d) = 0
Next d
used(9) = last
p10 \= 10
End If
End If
Loop
Console.Out.WriteLine("Own digits power sums for N = 3 to 9 inclusive:")
For i As Integer = nCount To 1 Step -1
Console.Out.WriteLine(numbers(i))
Next i
Console.Out.WriteLine("Considered " & tryCount & " digit combinations")
End Sub
End Module
| #include <stdio.h>
#include <math.h>
#define MAX_DIGITS 9
int digits[MAX_DIGITS];
void getDigits(int i) {
int ix = 0;
while (i > 0) {
digits[ix++] = i % 10;
i /= 10;
}
}
int main() {
int n, d, i, max, lastDigit, sum, dp;
int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};
printf("Own digits power sums for N = 3 to 9 inclusive:\n");
for (n = 3; n < 10; ++n) {
for (d = 2; d < 10; ++d) powers[d] *= d;
i = (int)pow(10, n-1);
max = i * 10;
lastDigit = 0;
while (i < max) {
if (!lastDigit) {
getDigits(i);
sum = 0;
for (d = 0; d < n; ++d) {
dp = digits[d];
sum += powers[dp];
}
} else if (lastDigit == 1) {
sum++;
} else {
sum += powers[lastDigit] - powers[lastDigit-1];
}
if (sum == i) {
printf("%d\n", i);
if (lastDigit == 0) printf("%d\n", i + 1);
i += 10 - lastDigit;
lastDigit = 0;
} else if (sum > i) {
i += 10 - lastDigit;
lastDigit = 0;
} else if (lastDigit < 9) {
i++;
lastDigit++;
} else {
i++;
lastDigit = 0;
}
}
}
return 0;
}
|
Write a version of this VB function in C with identical behavior. | Option Strict On
Option Explicit On
Imports System.IO
Module KlarnerRado
Private Const bitsWidth As Integer = 31
Private bitMask() As Integer = _
New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _
, 2048, 4096, 8192, 16384, 32768, 65536, 131072 _
, 262144, 524288, 1048576, 2097152, 4194304, 8388608 _
, 16777216, 33554432, 67108864, 134217728, 268435456 _
, 536870912, 1073741824 _
}
Private Const maxElement As Integer = 1100000000
Private Function BitSet(bit As Integer, v As Integer) As Boolean
Return (v And bitMask(bit - 1)) <> 0
End Function
Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer
Return b Or bitMask(bit - 1)
End Function
Public Sub Main
Dim kr(maxElement \ bitsWidth) As Integer
For i As Integer = 0 To kr.Count() - 1
kr(i) = 0
Next i
Dim krCount As Integer = 0
Dim n21 As Integer = 3
Dim n31 As Integer = 4
Dim p10 As Integer = 1000
Dim iBit As Integer = 0
Dim iOverBw As Integer = 0
Dim p2Bit As Integer = 1
Dim p2OverBw As Integer = 0
Dim p3Bit As Integer = 1
Dim p3OverBw As Integer = 0
kr(0) = SetBit(1, kr(0))
Dim kri As Boolean = True
Dim lastI As Integer = 0
For i As Integer = 1 To maxElement
iBit += 1
If iBit > bitsWidth Then
iBit = 1
iOverBw += 1
End If
If i = n21 Then
If BitSet(p2Bit, kr(p2OverBw)) Then
kri = True
End If
p2Bit += 1
If p2Bit > bitsWidth Then
p2Bit = 1
p2OverBw += 1
End If
n21 += 2
End If
If i = n31 Then
If BitSet(p3Bit, kr(p3OverBw)) Then
kri = True
End If
p3Bit += 1
If p3Bit > bitsWidth Then
p3Bit = 1
p3OverBw += 1
End If
n31 += 3
End If
If kri Then
lastI = i
kr(iOverBw) = SetBit(iBit, kr(iOverBw))
krCount += 1
If krCount <= 100 Then
Console.Out.Write(" " & i.ToString().PadLeft(3))
If krCount Mod 20 = 0 Then
Console.Out.WriteLine()
End If
ElseIf krCount = p10 Then
Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10))
p10 *= 10
End If
kri = False
End If
Next i
Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10))
End Sub
End Module
| #include <stdio.h>
#define ELEMENTS 10000000U
void make_klarner_rado(unsigned int *dst, unsigned int n) {
unsigned int i, i2 = 0, i3 = 0;
unsigned int m, m2 = 1, m3 = 1;
for (i = 0; i < n; ++i) {
dst[i] = m = m2 < m3 ? m2 : m3;
if (m2 == m) m2 = dst[i2++] << 1 | 1;
if (m3 == m) m3 = dst[i3++] * 3 + 1;
}
}
int main(void) {
static unsigned int klarner_rado[ELEMENTS];
unsigned int i;
make_klarner_rado(klarner_rado, ELEMENTS);
for (i = 0; i < 99; ++i)
printf("%u ", klarner_rado[i]);
for (i = 100; i <= ELEMENTS; i *= 10)
printf("%u\n", klarner_rado[i - 1]);
return 0;
}
|
Generate an equivalent C version of this VB code. | Option Strict On
Option Explicit On
Imports System.IO
Module KlarnerRado
Private Const bitsWidth As Integer = 31
Private bitMask() As Integer = _
New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _
, 2048, 4096, 8192, 16384, 32768, 65536, 131072 _
, 262144, 524288, 1048576, 2097152, 4194304, 8388608 _
, 16777216, 33554432, 67108864, 134217728, 268435456 _
, 536870912, 1073741824 _
}
Private Const maxElement As Integer = 1100000000
Private Function BitSet(bit As Integer, v As Integer) As Boolean
Return (v And bitMask(bit - 1)) <> 0
End Function
Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer
Return b Or bitMask(bit - 1)
End Function
Public Sub Main
Dim kr(maxElement \ bitsWidth) As Integer
For i As Integer = 0 To kr.Count() - 1
kr(i) = 0
Next i
Dim krCount As Integer = 0
Dim n21 As Integer = 3
Dim n31 As Integer = 4
Dim p10 As Integer = 1000
Dim iBit As Integer = 0
Dim iOverBw As Integer = 0
Dim p2Bit As Integer = 1
Dim p2OverBw As Integer = 0
Dim p3Bit As Integer = 1
Dim p3OverBw As Integer = 0
kr(0) = SetBit(1, kr(0))
Dim kri As Boolean = True
Dim lastI As Integer = 0
For i As Integer = 1 To maxElement
iBit += 1
If iBit > bitsWidth Then
iBit = 1
iOverBw += 1
End If
If i = n21 Then
If BitSet(p2Bit, kr(p2OverBw)) Then
kri = True
End If
p2Bit += 1
If p2Bit > bitsWidth Then
p2Bit = 1
p2OverBw += 1
End If
n21 += 2
End If
If i = n31 Then
If BitSet(p3Bit, kr(p3OverBw)) Then
kri = True
End If
p3Bit += 1
If p3Bit > bitsWidth Then
p3Bit = 1
p3OverBw += 1
End If
n31 += 3
End If
If kri Then
lastI = i
kr(iOverBw) = SetBit(iBit, kr(iOverBw))
krCount += 1
If krCount <= 100 Then
Console.Out.Write(" " & i.ToString().PadLeft(3))
If krCount Mod 20 = 0 Then
Console.Out.WriteLine()
End If
ElseIf krCount = p10 Then
Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10))
p10 *= 10
End If
kri = False
End If
Next i
Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10))
End Sub
End Module
| #include <stdio.h>
#define ELEMENTS 10000000U
void make_klarner_rado(unsigned int *dst, unsigned int n) {
unsigned int i, i2 = 0, i3 = 0;
unsigned int m, m2 = 1, m3 = 1;
for (i = 0; i < n; ++i) {
dst[i] = m = m2 < m3 ? m2 : m3;
if (m2 == m) m2 = dst[i2++] << 1 | 1;
if (m3 == m) m3 = dst[i3++] * 3 + 1;
}
}
int main(void) {
static unsigned int klarner_rado[ELEMENTS];
unsigned int i;
make_klarner_rado(klarner_rado, ELEMENTS);
for (i = 0; i < 99; ++i)
printf("%u ", klarner_rado[i]);
for (i = 100; i <= ELEMENTS; i *= 10)
printf("%u\n", klarner_rado[i - 1]);
return 0;
}
|
Produce a functionally identical C code for the snippet given in VB. |
Public Sub printarray(A)
For i = LBound(A) To UBound(A)
Debug.Print A(i),
Next
Debug.Print
End Sub
Public Sub Flip(ByRef A, p1, p2, trace)
If trace Then Debug.Print "we
Cut = Int((p2 - p1 + 1) / 2)
For i = 0 To Cut - 1
temp = A(i)
A(i) = A(p2 - i)
A(p2 - i) = temp
Next
End Sub
Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False)
lb = LBound(A)
ub = UBound(A)
Length = ub - lb + 1
If Length <= 1 Then
Exit Sub
End If
For i = ub To lb + 1 Step -1
P = lb
Maximum = A(P)
For j = lb + 1 To i
If A(j) > Maximum Then
P = j
Maximum = A(j)
End If
Next j
If P < i Then
If P > 1 Then
Flip A, lb, P, trace
If trace Then printarray A
End If
Flip A, lb, i, trace
If trace Then printarray A
End If
Next i
End Sub
Public Sub TestPancake(Optional trace As Boolean = False)
Dim A()
A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)
Debug.Print "Initial array:"
printarray A
pancakesort A, trace
Debug.Print "Final array:"
printarray A
End Sub
| int pancake_sort(int *list, unsigned int length)
{
if(length<2)
return 0;
int i,a,max_num_pos,moves;
moves=0;
for(i=length;i>1;i--)
{
max_num_pos=0;
for(a=0;a<i;a++)
{
if(list[a]>list[max_num_pos])
max_num_pos=a;
}
if(max_num_pos==i-1)
continue;
if(max_num_pos)
{
moves++;
do_flip(list, length, max_num_pos+1);
}
moves++;
do_flip(list, length, i);
}
return moves;
}
|
Ensure the translated C code behaves exactly like the original VB snippet. | Const n = 2200
Public Sub pq()
Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3
Dim l(n) As Boolean, l_add(9680000) As Boolean
For x = 1 To n
x2 = x * x
For y = x To n
l_add(x2 + y * y) = True
Next y
Next x
For x = 1 To n
s1 = s
s = s + 2
s2 = s
For y = x + 1 To n
If l_add(s1) Then l(y) = True
s1 = s1 + s2
s2 = s2 + 2
Next
Next
For x = 1 To n
If Not l(x) Then Debug.Print x;
Next
Debug.Print
End Sub
| #include <stdio.h>
#include <math.h>
#include <string.h>
#define N 2200
int main(int argc, char **argv){
int a,b,c,d;
int r[N+1];
memset(r,0,sizeof(r));
for(a=1; a<=N; a++){
for(b=a; b<=N; b++){
int aabb;
if(a&1 && b&1) continue;
aabb=a*a + b*b;
for(c=b; c<=N; c++){
int aabbcc=aabb + c*c;
d=(int)sqrt((float)aabbcc);
if(aabbcc == d*d && d<=N) r[d]=1;
}
}
}
for(a=1; a<=N; a++)
if(!r[a]) printf("%d ",a);
printf("\n");
}
|
Produce a functionally identical C code for the snippet given in VB. | Option Explicit
Randomize Timer
Function pad(s,n)
If n<0 Then pad= right(space(-n) & s ,-n) Else pad= left(s& space(n),n) End If
End Function
Sub print(s)
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
Function Rounds(maxsecs,wiz,a)
Dim mystep,maxstep,toend,j,i,x,d
If IsArray(a) Then d=True: print "seconds behind pending"
maxstep=100
For j=1 To maxsecs
For i=1 To wiz
If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1
maxstep=maxstep+1
Next
mystep=mystep+1
If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function
If d Then
If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)
End If
Next
Rounds=Array(maxsecs,maxstep)
End Function
Dim n,r,a,sumt,sums,ntests,t,maxsecs
ntests=10000
maxsecs=7000
t=timer
a=Array(600,609)
For n=1 To ntests
r=Rounds(maxsecs,5,a)
If r(0)<>maxsecs Then
sumt=sumt+r(0)
sums=sums+r(1)
End if
a=""
Next
print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds"
print "escaped in " & sumt/ntests & " seconds with " & sums/ntests & " stairs"
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int trial, secs_tot=0, steps_tot=0;
int sbeh, slen, wiz, secs;
time_t t;
srand((unsigned) time(&t));
printf( "Seconds steps behind steps ahead\n" );
for( trial=1;trial<=10000;trial++ ) {
sbeh = 0; slen = 100; secs = 0;
while(sbeh<slen) {
sbeh+=1;
for(wiz=1;wiz<=5;wiz++) {
if(rand()%slen < sbeh)
sbeh+=1;
slen+=1;
}
secs+=1;
if(trial==1&&599<secs&&secs<610)
printf("%d %d %d\n", secs, sbeh, slen-sbeh );
}
secs_tot+=secs;
steps_tot+=slen;
}
printf( "Average secs taken: %f\n", secs_tot/10000.0 );
printf( "Average final length of staircase: %f\n", steps_tot/10000.0 );
return 0;
}
|
Ensure the translated C code behaves exactly like the original VB snippet. | Option Explicit
Dim seed As Long
Sub Main()
Dim i As Integer
seed = 675248
For i = 1 To 5
Debug.Print Rand
Next i
End Sub
Function Rand() As Variant
Dim s As String
s = CStr(seed ^ 2)
Do While Len(s) <> 12
s = "0" + s
Loop
seed = Val(Mid(s, 4, 6))
Rand = seed
End Function
| #include<stdio.h>
long long seed;
long long random(){
seed = seed * seed / 1000 % 1000000;
return seed;
}
int main(){
seed = 675248;
for(int i=1;i<=5;i++)
printf("%lld\n",random());
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.