Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in VB while keeping its functionality equivalent to the C++ version. | class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
| Class Animal
End Class
Class Dog
Inherits Animal
End Class
Class Lab
Inherits Dog
End Class
Class Collie
Inherits Dog
End Class
Class Cat
Inherits Animal
End Class
|
Convert this C++ snippet to VB and keep its semantics consistent. | #include <map>
| Option Explicit
Sub Test()
Dim h As Object
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
Debug.Print h.Item("A")
h.Item("C") = 4
h.Key("C") = "D"
Debug.Print h.exists("C")
h.Remove "B"
Debug.Print h.Count
h.RemoveAll
Debug.Print h.Count
End Sub
|
Translate this program into VB but keep the logic exactly as in C++. | #include <map>
| Option Explicit
Sub Test()
Dim h As Object
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
Debug.Print h.Item("A")
h.Item("C") = 4
h.Key("C") = "D"
Debug.Print h.exists("C")
h.Remove "B"
Debug.Print h.Count
h.RemoveAll
Debug.Print h.Count
End Sub
|
Rewrite this program in VB while keeping its functionality equivalent to the C++ version. |
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
| Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property get xmax():xmax=xmaxi:end property
public property get ymax():ymax=ymaxi:end property
public property let depth(x)
if x<>8 and x<>32 then err.raise 9
Imgdepth=x
end property
public sub set0 (x0,y0)
if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9
xmini=-x0
ymini=-y0
xmaxi=xmini+imgl-1
ymaxi=ymini+imgh-1
end sub
Public Default Function Init(name,w,h,orient,dep,bkg,mipal)
dim i,j
ImgL=w
ImgH=h
tt=timer
loc=getlocale
set0 0,0
redim imgArray(ImgL-1,ImgH-1)
bkclr=bkg
if bkg<>0 then
for i=0 to ImgL-1
for j=0 to ImgH-1
imgarray(i,j)=bkg
next
next
end if
Select Case orient
Case 1: dirx=1 : diry=1
Case 2: dirx=-1 : diry=1
Case 3: dirx=-1 : diry=-1
Case 4: dirx=1 : diry=-1
End select
filename=name
ImgDepth =dep
if imgdepth=8 then
loadpal(mipal)
end if
set init=me
end function
private sub loadpal(mipale)
if isarray(mipale) Then
palette=mipale
szpal=UBound(mipale)+1
Else
szpal=256
, not relevant
End if
End Sub
Private Sub Class_Terminate
if err<>0 then wscript.echo "Error " & err.number
wscript.echo "copying image to bmp file"
savebmp
wscript.echo "opening " & filename & " with your default bmp viewer"
CreateObject("Shell.Application").ShellExecute filename
wscript.echo timer-tt & " iseconds"
End Sub
function long2wstr( x)
dim k1,k2,x1
k1= (x and &hffff&)
k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0))
long2wstr=chrw(k1) & chrw(k2)
end function
function int2wstr(x)
int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))
End Function
Public Sub SaveBMP
Dim s,ostream, x,y,loc
const hdrs=54
dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4)
dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0
with CreateObject("ADODB.Stream")
.Charset = "UTF-16LE"
.Type = 2
.open
.writetext ChrW(&h4d42)
.writetext long2wstr(hdrs+palsize+bms)
.writetext long2wstr(0)
.writetext long2wstr (hdrs+palsize)
.writetext long2wstr(40)
.writetext long2wstr(Imgl)
.writetext long2wstr(imgh)
.writetext int2wstr(1)
.writetext int2wstr(imgdepth)
.writetext long2wstr(&H0)
.writetext long2wstr(bms)
.writetext long2wstr(&Hc4e)
.writetext long2wstr(&hc43)
.writetext long2wstr(szpal)
.writetext long2wstr(&H0)
Dim x1,x2,y1,y2
If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1
If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1
Select Case imgdepth
Case 32
For y=y1 To y2 step diry
For x=x1 To x2 Step dirx
.writetext long2wstr(Imgarray(x,y))
Next
Next
Case 8
For x=0 to szpal-1
.writetext long2wstr(palette(x))
Next
dim pad:pad=ImgL mod 4
For y=y1 to y2 step diry
For x=x1 To x2 step dirx*2
.writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))
Next
if pad and 1 then .writetext chrw(ImgArray(x2,y))
if pad >1 then .writetext chrw(0)
Next
Case Else
WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits"
End Select
Dim outf:Set outf= CreateObject("ADODB.Stream")
outf.Type = 1
outf.Open
.position=2
.CopyTo outf
.close
outf.savetofile filename,2
outf.close
end with
End Sub
end class
function hsv2rgb( Hue, Sat, Value)
dim Angle, Radius,Ur,Vr,Wr,Rdim
dim r,g,b, rgb
Angle = (Hue-150) *0.01745329251994329576923690768489
Ur = Value * 2.55
Radius = Ur * tan(Sat *0.01183199)
Vr = Radius * cos(Angle) *0.70710678
Wr = Radius * sin(Angle) *0.40824829
r = (Ur - Vr - Wr)
g = (Ur + Vr - Wr)
b = (Ur + Wr + Wr)
if r >255 then
Rdim = (Ur - 255) / (Vr + Wr)
r = 255
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
elseif r < 0 then
Rdim = Ur / (Vr + Wr)
r = 0
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
end if
if g >255 then
Rdim = (255 - Ur) / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 255
b = Ur + 2 * Wr * Rdim
elseif g<0 then
Rdim = -Ur / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 0
b = Ur + 2 * Wr * Rdim
end if
if b>255 then
Rdim = (255 - Ur) / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 255
elseif b<0 then
Rdim = -Ur / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 0
end If
hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)
end function
function ang(col,row)
if col =0 then
if row<0 then ang=90 else ang=270 end if
else
if col>0 then
ang=atn(-row/col)*57.2957795130
else
ang=(atn(row/-col)*57.2957795130)+180
end if
end if
ang=(ang+360) mod 360
end function
Dim X,row,col,fn,tt,hr,sat,row2
const h=160
const w=160
const rad=159
const r2=25500
tt=timer
fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp"
Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)
x.set0 w,h
for row=x.xmin+1 to x.xmax
row2=row*row
hr=int(Sqr(r2-row2))
For col=hr To 159
Dim a:a=((col\16 +row\16) And 1)* &hffffff
x.imgArray(col+160,row+160)=a
x.imgArray(-col+160,row+160)=a
next
for col=-hr to hr
sat=100-sqr(row2+col*col)/rad *50
x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)
next
next
Set X = Nothing
|
Maintain the same structure and functionality when rewriting this code in VB. |
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
| Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property get xmax():xmax=xmaxi:end property
public property get ymax():ymax=ymaxi:end property
public property let depth(x)
if x<>8 and x<>32 then err.raise 9
Imgdepth=x
end property
public sub set0 (x0,y0)
if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9
xmini=-x0
ymini=-y0
xmaxi=xmini+imgl-1
ymaxi=ymini+imgh-1
end sub
Public Default Function Init(name,w,h,orient,dep,bkg,mipal)
dim i,j
ImgL=w
ImgH=h
tt=timer
loc=getlocale
set0 0,0
redim imgArray(ImgL-1,ImgH-1)
bkclr=bkg
if bkg<>0 then
for i=0 to ImgL-1
for j=0 to ImgH-1
imgarray(i,j)=bkg
next
next
end if
Select Case orient
Case 1: dirx=1 : diry=1
Case 2: dirx=-1 : diry=1
Case 3: dirx=-1 : diry=-1
Case 4: dirx=1 : diry=-1
End select
filename=name
ImgDepth =dep
if imgdepth=8 then
loadpal(mipal)
end if
set init=me
end function
private sub loadpal(mipale)
if isarray(mipale) Then
palette=mipale
szpal=UBound(mipale)+1
Else
szpal=256
, not relevant
End if
End Sub
Private Sub Class_Terminate
if err<>0 then wscript.echo "Error " & err.number
wscript.echo "copying image to bmp file"
savebmp
wscript.echo "opening " & filename & " with your default bmp viewer"
CreateObject("Shell.Application").ShellExecute filename
wscript.echo timer-tt & " iseconds"
End Sub
function long2wstr( x)
dim k1,k2,x1
k1= (x and &hffff&)
k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0))
long2wstr=chrw(k1) & chrw(k2)
end function
function int2wstr(x)
int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))
End Function
Public Sub SaveBMP
Dim s,ostream, x,y,loc
const hdrs=54
dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4)
dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0
with CreateObject("ADODB.Stream")
.Charset = "UTF-16LE"
.Type = 2
.open
.writetext ChrW(&h4d42)
.writetext long2wstr(hdrs+palsize+bms)
.writetext long2wstr(0)
.writetext long2wstr (hdrs+palsize)
.writetext long2wstr(40)
.writetext long2wstr(Imgl)
.writetext long2wstr(imgh)
.writetext int2wstr(1)
.writetext int2wstr(imgdepth)
.writetext long2wstr(&H0)
.writetext long2wstr(bms)
.writetext long2wstr(&Hc4e)
.writetext long2wstr(&hc43)
.writetext long2wstr(szpal)
.writetext long2wstr(&H0)
Dim x1,x2,y1,y2
If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1
If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1
Select Case imgdepth
Case 32
For y=y1 To y2 step diry
For x=x1 To x2 Step dirx
.writetext long2wstr(Imgarray(x,y))
Next
Next
Case 8
For x=0 to szpal-1
.writetext long2wstr(palette(x))
Next
dim pad:pad=ImgL mod 4
For y=y1 to y2 step diry
For x=x1 To x2 step dirx*2
.writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))
Next
if pad and 1 then .writetext chrw(ImgArray(x2,y))
if pad >1 then .writetext chrw(0)
Next
Case Else
WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits"
End Select
Dim outf:Set outf= CreateObject("ADODB.Stream")
outf.Type = 1
outf.Open
.position=2
.CopyTo outf
.close
outf.savetofile filename,2
outf.close
end with
End Sub
end class
function hsv2rgb( Hue, Sat, Value)
dim Angle, Radius,Ur,Vr,Wr,Rdim
dim r,g,b, rgb
Angle = (Hue-150) *0.01745329251994329576923690768489
Ur = Value * 2.55
Radius = Ur * tan(Sat *0.01183199)
Vr = Radius * cos(Angle) *0.70710678
Wr = Radius * sin(Angle) *0.40824829
r = (Ur - Vr - Wr)
g = (Ur + Vr - Wr)
b = (Ur + Wr + Wr)
if r >255 then
Rdim = (Ur - 255) / (Vr + Wr)
r = 255
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
elseif r < 0 then
Rdim = Ur / (Vr + Wr)
r = 0
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
end if
if g >255 then
Rdim = (255 - Ur) / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 255
b = Ur + 2 * Wr * Rdim
elseif g<0 then
Rdim = -Ur / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 0
b = Ur + 2 * Wr * Rdim
end if
if b>255 then
Rdim = (255 - Ur) / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 255
elseif b<0 then
Rdim = -Ur / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 0
end If
hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)
end function
function ang(col,row)
if col =0 then
if row<0 then ang=90 else ang=270 end if
else
if col>0 then
ang=atn(-row/col)*57.2957795130
else
ang=(atn(row/-col)*57.2957795130)+180
end if
end if
ang=(ang+360) mod 360
end function
Dim X,row,col,fn,tt,hr,sat,row2
const h=160
const w=160
const rad=159
const r2=25500
tt=timer
fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp"
Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)
x.set0 w,h
for row=x.xmin+1 to x.xmax
row2=row*row
hr=int(Sqr(r2-row2))
For col=hr To 159
Dim a:a=((col\16 +row\16) And 1)* &hffffff
x.imgArray(col+160,row+160)=a
x.imgArray(-col+160,row+160)=a
next
for col=-hr to hr
sat=100-sqr(row2+col*col)/rad *50
x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)
next
next
Set X = Nothing
|
Convert this C++ snippet to VB and keep its semantics consistent. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
| with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
dim b(25)
dim c(128)
with new regexp
.pattern="([^aeiou])"
.global=true
for each i in a
if len(trim(i))>10 then
set matches= .execute(i)
rep=false
for each m in matches
x=asc(m)
c(x)=c(x)+1
if c(x)>1 then rep=true :exit for
next
erase c
if not rep then
x1=matches.count
b(x1)=b(x1)&" "&i
end if
end if
next
end with
for i=25 to 0 step -1
if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf
next
|
Preserve the algorithm and functionality while converting the code from C++ to VB. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
| with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
dim b(25)
dim c(128)
with new regexp
.pattern="([^aeiou])"
.global=true
for each i in a
if len(trim(i))>10 then
set matches= .execute(i)
rep=false
for each m in matches
x=asc(m)
c(x)=c(x)+1
if c(x)>1 then rep=true :exit for
next
erase c
if not rep then
x1=matches.count
b(x1)=b(x1)&" "&i
end if
end if
next
end with
for i=25 to 0 step -1
if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf
next
|
Convert this C++ snippet to VB and keep its semantics consistent. | #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
typedef unsigned char byte;
enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };
class fieldData
{
public:
fieldData() : value( CLOSED ), open( false ) {}
byte value;
bool open, mine;
};
class game
{
public:
~game()
{ if( field ) delete [] field; }
game( int x, int y )
{
go = false; wid = x; hei = y;
field = new fieldData[x * y];
memset( field, 0, x * y * sizeof( fieldData ) );
oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;
mMines = 0;
int mx, my, m = 0;
for( ; m < oMines; m++ )
{
do
{ mx = rand() % wid; my = rand() % hei; }
while( field[mx + wid * my].mine );
field[mx + wid * my].mine = true;
}
graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*';
graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X';
}
void gameLoop()
{
string c, r, a;
int col, row;
while( !go )
{
drawBoard();
cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n";
cin >> c >> r >> a;
if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;
col = c[0] - 65; row = r[0] - 49;
makeMove( col, row, a );
}
}
private:
void makeMove( int x, int y, string a )
{
fieldData* fd = &field[wid * y + x];
if( fd->open && fd->value < CLOSED )
{
cout << "This cell is already open!";
Sleep( 3000 ); return;
}
if( a[0] == 'O' ) openCell( x, y );
else if( a[0] == 'F' )
{
fd->open = true;
fd->value = FLAG;
mMines++;
checkWin();
}
else
{
fd->open = true;
fd->value = UNKNOWN;
}
}
bool openCell( int x, int y )
{
if( !isInside( x, y ) ) return false;
if( field[x + y * wid].mine ) boom();
else
{
if( field[x + y * wid].value == FLAG )
{
field[x + y * wid].value = CLOSED;
field[x + y * wid].open = false;
mMines--;
}
recOpen( x, y );
checkWin();
}
return true;
}
void drawBoard()
{
system( "cls" );
cout << "Marked mines: " << mMines << " from " << oMines << "\n\n";
for( int x = 0; x < wid; x++ )
cout << " " << ( char )( 65 + x ) << " ";
cout << "\n"; int yy;
for( int y = 0; y < hei; y++ )
{
yy = y * wid;
for( int x = 0; x < wid; x++ )
cout << "+---";
cout << "+\n"; fieldData* fd;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy]; cout<< "| ";
if( !fd->open ) cout << ( char )graphs[1] << " ";
else
{
if( fd->value > 9 )
cout << ( char )graphs[fd->value - 9] << " ";
else
{
if( fd->value < 1 ) cout << " ";
else cout << ( char )(fd->value + 48 ) << " ";
}
}
}
cout << "| " << y + 1 << "\n";
}
for( int x = 0; x < wid; x++ )
cout << "+---";
cout << "+\n\n";
}
void checkWin()
{
int z = wid * hei - oMines, yy;
fieldData* fd;
for( int y = 0; y < hei; y++ )
{
yy = wid * y;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy];
if( fd->open && fd->value != FLAG ) z--;
}
}
if( !z ) lastMsg( "Congratulations, you won the game!");
}
void boom()
{
int yy; fieldData* fd;
for( int y = 0; y < hei; y++ )
{
yy = wid * y;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy];
if( fd->value == FLAG )
{
fd->open = true;
fd->value = fd->mine ? MINE : ERR;
}
else if( fd->mine )
{
fd->open = true;
fd->value = MINE;
}
}
}
lastMsg( "B O O O M M M M M !" );
}
void lastMsg( string s )
{
go = true; drawBoard();
cout << s << "\n\n";
}
bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }
void recOpen( int x, int y )
{
if( !isInside( x, y ) || field[x + y * wid].open ) return;
int bc = getMineCount( x, y );
field[x + y * wid].open = true;
field[x + y * wid].value = bc;
if( bc ) return;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( xx == 0 && yy == 0 ) continue;
recOpen( x + xx, y + yy );
}
}
int getMineCount( int x, int y )
{
int m = 0;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( xx == 0 && yy == 0 ) continue;
if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;
}
return m;
}
int wid, hei, mMines, oMines;
fieldData* field; bool go;
int graphs[6];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
game g( 4, 6 ); g.gameLoop();
return system( "pause" );
}
| Option Explicit
Public vTime As Single
Public PlaysCount As Long
Sub Main_MineSweeper()
Dim Userf As New cMinesweeper
Userf.Show 0, True
End Sub
|
Convert this C++ snippet to VB and keep its semantics consistent. | #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
auto size = g.size();
std::vector<bool> vis(size);
std::vector<int> l(size);
auto x = size;
std::vector<std::vector<int>> t(size);
std::function<void(int)> visit;
visit = [&](int u) {
if (!vis[u]) {
vis[u] = true;
for (auto v : g[u]) {
visit(v);
t[v].push_back(u);
}
l[--x] = u;
}
};
for (int i = 0; i < g.size(); ++i) {
visit(i);
}
std::vector<int> c(size);
std::function<void(int, int)> assign;
assign = [&](int u, int root) {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (auto v : t[u]) {
assign(v, root);
}
}
};
for (auto u : l) {
assign(u, u);
}
return c;
}
std::vector<std::vector<int>> g = {
{1},
{2},
{0},
{1, 2, 4},
{3, 5},
{2, 6},
{5},
{4, 6, 7},
};
int main() {
using namespace std;
cout << kosaraju(g) << endl;
return 0;
}
| Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Integer))
Next
Dim visit As Action(Of Integer) = Sub(u As Integer)
If Not vis(u) Then
vis(u) = True
For Each v In g(u)
visit(v)
t(v).Add(u)
Next
x -= 1
l(x) = u
End If
End Sub
For i = 1 To size
visit(i - 1)
Next
Dim c(size - 1) As Integer
Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)
If vis(u) Then
vis(u) = False
c(u) = root
For Each v In t(u)
assign(v, root)
Next
End If
End Sub
For Each u In l
assign(u, u)
Next
Return c.ToList
End Function
Sub Main()
Dim g = New List(Of List(Of Integer)) From {
New List(Of Integer) From {1},
New List(Of Integer) From {2},
New List(Of Integer) From {0},
New List(Of Integer) From {1, 2, 4},
New List(Of Integer) From {3, 5},
New List(Of Integer) From {2, 6},
New List(Of Integer) From {5},
New List(Of Integer) From {4, 6, 7}
}
Dim output = Kosaraju(g)
Console.WriteLine("[{0}]", String.Join(", ", output))
End Sub
End Module
|
Translate the given C++ code snippet into VB without altering its behavior. | #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
auto size = g.size();
std::vector<bool> vis(size);
std::vector<int> l(size);
auto x = size;
std::vector<std::vector<int>> t(size);
std::function<void(int)> visit;
visit = [&](int u) {
if (!vis[u]) {
vis[u] = true;
for (auto v : g[u]) {
visit(v);
t[v].push_back(u);
}
l[--x] = u;
}
};
for (int i = 0; i < g.size(); ++i) {
visit(i);
}
std::vector<int> c(size);
std::function<void(int, int)> assign;
assign = [&](int u, int root) {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (auto v : t[u]) {
assign(v, root);
}
}
};
for (auto u : l) {
assign(u, u);
}
return c;
}
std::vector<std::vector<int>> g = {
{1},
{2},
{0},
{1, 2, 4},
{3, 5},
{2, 6},
{5},
{4, 6, 7},
};
int main() {
using namespace std;
cout << kosaraju(g) << endl;
return 0;
}
| Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Integer))
Next
Dim visit As Action(Of Integer) = Sub(u As Integer)
If Not vis(u) Then
vis(u) = True
For Each v In g(u)
visit(v)
t(v).Add(u)
Next
x -= 1
l(x) = u
End If
End Sub
For i = 1 To size
visit(i - 1)
Next
Dim c(size - 1) As Integer
Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)
If vis(u) Then
vis(u) = False
c(u) = root
For Each v In t(u)
assign(v, root)
Next
End If
End Sub
For Each u In l
assign(u, u)
Next
Return c.ToList
End Function
Sub Main()
Dim g = New List(Of List(Of Integer)) From {
New List(Of Integer) From {1},
New List(Of Integer) From {2},
New List(Of Integer) From {0},
New List(Of Integer) From {1, 2, 4},
New List(Of Integer) From {3, 5},
New List(Of Integer) From {2, 6},
New List(Of Integer) From {5},
New List(Of Integer) From {4, 6, 7}
}
Dim output = Kosaraju(g)
Console.WriteLine("[{0}]", String.Join(", ", output))
End Sub
End Module
|
Generate an equivalent VB version of this C++ code. | #include <iostream>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
if(index < 0 || index >= (int)size(payloads)) cout << "null";
else cout << "'" << payloads[index] << "'";
if (!isLast) cout << ", ";
}
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
std::apply
(
[&payloads, isLast](Ts const&... tupleArgs)
{
size_t n{0};
cout << "[";
(PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
cout << "]";
cout << (isLast ? "\n" : ",\n");
}, nestedTuple
);
}
void FindUniqueIndexes(set<int> &indexes, int index)
{
indexes.insert(index);
}
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
std::apply
(
[&indexes](Ts const&... tupleArgs)
{
(FindUniqueIndexes(indexes, tupleArgs),...);
}, nestedTuple
);
}
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
for(size_t i = 0; i < size(payloads); i++)
{
if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
}
}
int main()
{
vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"};
auto tpl = make_tuple(make_tuple(
make_tuple(1, 2),
make_tuple(3, 4, 1),
5));
cout << "Mapping indexes to payloads:\n";
PrintPayloads(payloads, tpl);
cout << "\nFinding unused payloads:\n";
set<int> usedIndexes;
FindUniqueIndexes(usedIndexes, tpl);
PrintUnusedPayloads(usedIndexes, payloads);
cout << "\nMapping to some out of range payloads:\n";
PrintPayloads(shortPayloads, tpl);
return 0;
}
| Public Sub test()
Dim t(2) As Variant
t(0) = [{1,2}]
t(1) = [{3,4,1}]
t(2) = 5
p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}]
Dim q(6) As Boolean
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
For j = LBound(t(i)) To UBound(t(i))
q(t(i)(j)) = True
t(i)(j) = p(t(i)(j) + 1)
Next j
Else
q(t(i)) = True
t(i) = p(t(i) + 1)
End If
Next i
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
Debug.Print Join(t(i), ", ")
Else
Debug.Print t(i)
End If
Next i
For i = LBound(q) To UBound(q)
If Not q(i) Then Debug.Print p(i + 1); " is not used"
Next i
End Sub
|
Please provide an equivalent version of this PHP code in C#. | <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
| using System;
using System.IO;
namespace DeleteFile {
class Program {
static void Main() {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete("/input.txt");
Directory.Delete("/docs");
}
}
}
|
Convert this PHP block to C#, preserving its control flow and logic. | <?php
$Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);
$MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath");
$DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle");
$Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');
$Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay");
$Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux");
$edate = explode(" ",date('Y m j L'));
$usery = $edate[0];
$userm = $edate[1];
$userd = $edate[2];
$IsLeap = $edate[3];
if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {
$usery = $_GET['y'];
$userm = $_GET['m'];
$userd = $_GET['d'];
$IsLeap = 0;
if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;
if ($usery%400 == 0) $IsLeap = 1;
}
$userdays = 0;
$i = 0;
while ($i < ($userm-1)) {
$userdays = $userdays + $Anerisia[$i];
$i = $i +1;
}
$userdays = $userdays + $userd;
$IsHolyday = 0;
$dyear = $usery + 1166;
$dmonth = $MONTHS[$userdays/73.2];
$dday = $userdays%73;
if (0 == $dday) $dday = 73;
$Dname = $DAYS[$userdays%5];
$Holyday = "St. Tibs Day";
if ($dday == 5) {
$Holyday = $Holy5[$userdays/73.2];
$IsHolyday =1;
}
if ($dday == 50) {
$Holyday = $Holy50[$userdays/73.2];
$IsHolyday =1;
}
if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;
$suff = $Dsuff[$dday%10] ;
if ((11 <= $dday) && (19 >= $dday)) $suff='th';
if ($IsHolyday ==2)
echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear;
if ($IsHolyday ==1)
echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday;
if ($IsHolyday == 0)
echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear;
?>
| using System;
public static class DiscordianDate
{
static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" };
static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" };
static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" };
static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" };
public static string Discordian(this DateTime date) {
string yold = $" in the YOLD {date.Year + 1166}.";
int dayOfYear = date.DayOfYear;
if (DateTime.IsLeapYear(date.Year)) {
if (dayOfYear == 60) return "St. Tib's day" + yold;
else if (dayOfYear > 60) dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
int seasonNr = dayOfYear / 73;
int weekdayNr = dayOfYear % 5;
string holyday = "";
if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!";
else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!";
return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}";
}
public static void Main() {
foreach (var (day, month, year) in new [] {
(1, 1, 2010),
(5, 1, 2010),
(19, 2, 2011),
(28, 2, 2012),
(29, 2, 2012),
(1, 3, 2012),
(19, 3, 2013),
(3, 5, 2014),
(31, 5, 2015),
(22, 6, 2016),
(15, 7, 2016),
(12, 8, 2017),
(19, 9, 2018),
(26, 9, 2018),
(24, 10, 2019),
(8, 12, 2020),
(31, 12, 2020)
})
{
Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}");
}
}
}
|
Produce a language-to-language conversion: from PHP to C#, same semantics. | <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
| class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}
|
Port the following code from PHP to C# with equivalent syntax and logic. | #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
| using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
}
|
Generate an equivalent C# version of this PHP code. | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks
{
class Program
{
static void Main ( string[ ] args )
{
FindCommonDirectoryPath.Test ( );
}
}
class FindCommonDirectoryPath
{
public static void Test ( )
{
Console.WriteLine ( "Find Common Directory Path" );
Console.WriteLine ( );
List<string> PathSet1 = new List<string> ( );
PathSet1.Add ( "/home/user1/tmp/coverage/test" );
PathSet1.Add ( "/home/user1/tmp/covert/operator" );
PathSet1.Add ( "/home/user1/tmp/coven/members" );
Console.WriteLine("Path Set 1 (All Absolute Paths):");
foreach ( string path in PathSet1 )
{
Console.WriteLine ( path );
}
Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
}
public static string FindCommonPath ( string Separator, List<string> Paths )
{
string CommonPath = String.Empty;
List<string> SeparatedPath = Paths
.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
.ToList ( );
foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
{
if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
{
CommonPath = PathSegment;
}
else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
{
CommonPath += Separator + PathSegment;
}
else
{
break;
}
}
return CommonPath;
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original PHP code. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Convert the following code from PHP to C#, ensuring the logic remains intact. | <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaTicTacToe
{
class Program
{
static string[][] Players = new string[][] {
new string[] { "COMPUTER", "X" },
new string[] { "HUMAN", "O" }
};
const int Unplayed = -1;
const int Computer = 0;
const int Human = 1;
static int[] GameBoard = new int[9];
static int[] corners = new int[] { 0, 2, 6, 8 };
static int[][] wins = new int[][] {
new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 },
new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 },
new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };
static void Main(string[] args)
{
while (true)
{
Console.Clear();
Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#.");
initializeGameBoard();
displayGameBoard();
int currentPlayer = rnd.Next(0, 2);
Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer));
while (true)
{
int thisMove = getMoveFor(currentPlayer);
if (thisMove == Unplayed)
{
Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer));
break;
}
playMove(thisMove, currentPlayer);
displayGameBoard();
if (isGameWon())
{
Console.WriteLine("{0} has won the game!", playerName(currentPlayer));
break;
}
else if (isGameTied())
{
Console.WriteLine("Cat game ... we have a tie.");
break;
}
currentPlayer = getNextPlayer(currentPlayer);
}
if (!playAgain())
return;
}
}
static int getMoveFor(int player)
{
if (player == Human)
return getManualMove(player);
else
{
int selectedMove = getSemiRandomMove(player);
Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1);
return selectedMove;
}
}
static int getManualMove(int player)
{
while (true)
{
Console.Write("{0}, enter you move (number): ", playerName(player));
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
if (keyInfo.Key == ConsoleKey.Escape)
return Unplayed;
if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)
{
int move = keyInfo.KeyChar - '1';
if (GameBoard[move] == Unplayed)
return move;
else
Console.WriteLine("Spot {0} is already taken, please select again.", move + 1);
}
else
Console.WriteLine("Illegal move, please select again.\n");
}
}
static int getRandomMove(int player)
{
int movesLeft = GameBoard.Count(position => position == Unplayed);
int x = rnd.Next(0, movesLeft);
for (int i = 0; i < GameBoard.Length; i++)
{
if (GameBoard[i] == Unplayed && x < 0)
return i;
x--;
}
return Unplayed;
}
static int getSemiRandomMove(int player)
{
int posToPlay;
if (checkForWinningMove(player, out posToPlay))
return posToPlay;
if (checkForBlockingMove(player, out posToPlay))
return posToPlay;
return getRandomMove(player);
}
static int getBestMove(int player)
{
return -1;
}
static bool checkForWinningMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(player, line, out posToPlay))
return true;
return false;
}
static bool checkForBlockingMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))
return true;
return false;
}
static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)
{
int cnt = 0;
posToPlay = int.MinValue;
foreach (int pos in line)
{
if (GameBoard[pos] == player)
cnt++;
else if (GameBoard[pos] == Unplayed)
posToPlay = pos;
}
return cnt == 2 && posToPlay >= 0;
}
static void playMove(int boardPosition, int player)
{
GameBoard[boardPosition] = player;
}
static bool isGameWon()
{
return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));
}
static bool takenBySamePlayer(int a, int b, int c)
{
return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];
}
static bool isGameTied()
{
return !GameBoard.Any(spot => spot == Unplayed);
}
static Random rnd = new Random();
static void initializeGameBoard()
{
for (int i = 0; i < GameBoard.Length; i++)
GameBoard[i] = Unplayed;
}
static string playerName(int player)
{
return Players[player][0];
}
static string playerToken(int player)
{
return Players[player][1];
}
static int getNextPlayer(int player)
{
return (player + 1) % 2;
}
static void displayGameBoard()
{
Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8));
Console.WriteLine();
}
static string pieceAt(int boardPosition)
{
if (GameBoard[boardPosition] == Unplayed)
return (boardPosition + 1).ToString();
return playerToken(GameBoard[boardPosition]);
}
private static bool playAgain()
{
Console.WriteLine("\nDo you want to play again?");
return Console.ReadKey(false).Key == ConsoleKey.Y;
}
}
}
|
Write the same algorithm in C# as shown in this PHP implementation. | <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
| private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
|
Change the following PHP code into C# without altering its purpose. | <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
| using System;
static class YCombinator<T, TResult>
{
private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);
public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}
static class Program
{
static void Main()
{
var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));
Console.WriteLine(fac(10));
Console.WriteLine(fib(10));
}
}
|
Preserve the algorithm and functionality while converting the code from PHP to C#. | for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo "\n";
continue;
}
echo ', ';
}
| using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
|
Translate this program into C# but keep the logic exactly as in PHP. | <?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
}
?>
| using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
|
Produce a functionally identical C# code for the snippet given in PHP. | $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
| using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
|
Produce a functionally identical C# code for the snippet given in PHP. | $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
| using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
|
Generate a C# translation of this PHP snippet without changing its computational steps. | <?php
$time = new DateTime('March 7 2009 7:30pm EST');
$time->modify('+12 hours');
echo $time->format('c');
?>
| class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
|
Generate an equivalent C# version of this PHP code. | <?php
$buffer = 1;
$pids = [];
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | <?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
$a[$i][$j] = rand(1, 20);
foreach ($a as $row) {
foreach ($row as $element) {
echo " $element";
if ($element == 20)
break 2; // 2 is the number of loops we want to break out of
}
echo "\n";
}
echo "\n";
?>
| using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}
|
Write the same code in C# as shown below in PHP. | $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
| int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
|
Transform the following PHP implementation into C#, maintaining the same output and logic. | <?php
function lookAndSay($str) {
return preg_replace_callback('#(.)\1*#', function($matches) {
return strlen($matches[0]).$matches[1];
}, $str);
}
$num = "1";
foreach(range(1,10) as $i) {
echo $num."<br/>";
$num = lookAndSay($num);
}
?>
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Change the programming language of this snippet from PHP to C# without modifying what it does. | $stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
|
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek();
top = stack.Pop();
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek();
top = stack.Pop();
|
Please provide an equivalent version of this PHP code in C#. | <?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?>
| if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
|
Ensure the translated C# code behaves exactly like the original PHP snippet. | <?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
| using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original PHP code. | function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}
| class SelectionSort<T> where T : IComparable {
public T[] Sort(T[] list) {
int k;
T temp;
for (int i = 0; i < list.Length; i++) {
k = i;
for (int j=i + 1; j < list.Length; j++) {
if (list[j].CompareTo(list[k]) < 0) {
k = j;
}
}
temp = list[i];
list[i] = list[k];
list[k] = temp;
}
return list;
}
}
|
Ensure the translated C# code behaves exactly like the original PHP snippet. | function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
| int[] intArray = { 1, 2, 3, 4, 5 };
int[] squares1 = intArray.Select(x => x * x).ToArray();
int[] squares2 = (from x in intArray
select x * x).ToArray();
foreach (var i in intArray)
Console.WriteLine(i * i);
|
Preserve the algorithm and functionality while converting the code from PHP to C#. | class Singleton {
protected static $instance = null;
public $test_var;
private function __construct(){
}
public static function getInstance(){
if (is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}
$foo = Singleton::getInstance();
$foo->test_var = 'One';
$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'
$fail = new Singleton(); //Fatal error
| public sealed class Singleton1
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}
|
Translate this program into C# but keep the logic exactly as in PHP. | for ($i = 10; $i >= 0; $i--)
echo "$i\n";
| for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
|
Produce a functionally identical C# code for the snippet given in PHP. | for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo '*';
}
echo "\n";
}
| using System;
class Program {
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
|
Write a version of this PHP function in C# with identical behavior. | <?php
function longMult($a, $b)
{
$as = (string) $a;
$bs = (string) $b;
for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)
{
for($p = 0; $p < $pi; $p++)
{
$regi[$ai][] = 0;
}
for($bi = strlen($bs) - 1; $bi >= 0; $bi--)
{
$regi[$ai][] = $as[$ai] * $bs[$bi];
}
}
return $regi;
}
function longAdd($arr)
{
$outer = count($arr);
$inner = count($arr[$outer-1]) + $outer;
for($i = 0; $i <= $inner; $i++)
{
for($o = 0; $o < $outer; $o++)
{
$val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;
@$sum[$i] += $val;
}
}
return $sum;
}
function carry($arr)
{
for($i = 0; $i < count($arr); $i++)
{
$s = (string) $arr[$i];
switch(strlen($s))
{
case 2:
$arr[$i] = $s{1};
@$arr[$i+1] += $s{0};
break;
case 3:
$arr[$i] = $s{2};
@$arr[$i+1] += $s{0}.$s{1};
break;
}
}
return ltrim(implode('',array_reverse($arr)),'0');
}
function lm($a,$b)
{
return carry(longAdd(longMult($a,$b)));
}
if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')
{
echo 'pass!';
}; // 2^64 * 2^64
| using System;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static decimal mx = 1E28M, hm = 1E14M, a;
struct bi { public decimal hi, lo; }
static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }
static string toStr(bi a, bool comma = false) {
string r = a.hi == 0 ? string.Format("{0:0}", a.lo) :
string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo);
if (!comma) return r; string rc = "";
for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc;
return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }
static decimal Pow_dec(decimal bas, uint exp) {
if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
if ((exp & 1) == 0) return tmp; return tmp * bas; }
static void Main(string[] args) {
for (uint p = 64; p < 95; p += 30) {
bi x = set4sq(a = Pow_dec(2M, p)), y;
WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2);
y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;
a = x.hi * x.lo * 2M;
y.hi += Math.Floor(a / hm);
y.lo += (a % hm) * hm;
while (y.lo > mx) { y.lo -= mx; y.hi++; }
WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true),
BS.ToString() == toStr(y) ? "does" : "fails to"); } }
}
|
Transform the following PHP implementation into C#, maintaining the same output and logic. | <?php
$size = 4;
$chosen = implode(array_rand(array_flip(range(1,9)), $size));
echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";
for ($guesses = 1; ; $guesses++) {
while (true) {
echo "\nNext guess [$guesses]: ";
$guess = rtrim(fgets(STDIN));
if (!checkguess($guess))
echo "$size digits, no repetition, no 0... retry\n";
else
break;
}
if ($guess == $chosen) {
echo "You did it in $guesses attempts!\n";
break;
} else {
$bulls = 0;
$cows = 0;
foreach (range(0, $size-1) as $i) {
if ($guess[$i] == $chosen[$i])
$bulls++;
else if (strpos($chosen, $guess[$i]) !== FALSE)
$cows++;
}
echo "$cows cows, $bulls bulls\n";
}
}
function checkguess($g)
{
global $size;
return count(array_unique(str_split($g))) == $size &&
preg_match("/^[1-9]{{$size}}$/", $g);
}
?>
| using System;
namespace BullsnCows
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
KnuthShuffle<int>(ref nums);
int[] chosenNum = new int[4];
Array.Copy(nums, chosenNum, 4);
Console.WriteLine("Your Guess ?");
while (!game(Console.ReadLine(), chosenNum))
{
Console.WriteLine("Your next Guess ?");
}
Console.ReadKey();
}
public static void KnuthShuffle<T>(ref T[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(array.Length);
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}
public static bool game(string guess, int[] num)
{
char[] guessed = guess.ToCharArray();
int bullsCount = 0, cowsCount = 0;
if (guessed.Length != 4)
{
Console.WriteLine("Not a valid guess.");
return false;
}
for (int i = 0; i < 4; i++)
{
int curguess = (int) char.GetNumericValue(guessed[i]);
if (curguess < 1 || curguess > 9)
{
Console.WriteLine("Digit must be ge greater 0 and lower 10.");
return false;
}
if (curguess == num[i])
{
bullsCount++;
}
else
{
for (int j = 0; j < 4; j++)
{
if (curguess == num[j])
cowsCount++;
}
}
}
if (bullsCount == 4)
{
Console.WriteLine("Congratulations! You have won!");
return true;
}
else
{
Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
return false;
}
}
}
}
|
Write the same algorithm in C# as shown in this PHP implementation. | function bubbleSort(array $array){
foreach($array as $i => &$val){
foreach($array as $k => &$val2){
if($k <= $i)
continue;
if($val > $val2) {
list($val, $val2) = [$val2, $val];
break;
}
}
}
return $array;
}
| using System;
using System.Collections.Generic;
namespace RosettaCode.BubbleSort
{
public static class BubbleSortMethods
{
public static void BubbleSort<T>(this List<T> list) where T : IComparable
{
bool madeChanges;
int itemCount = list.Count;
do
{
madeChanges = false;
itemCount--;
for (int i = 0; i < itemCount; i++)
{
if (list[i].CompareTo(list[i + 1]) > 0)
{
T temp = list[i + 1];
list[i + 1] = list[i];
list[i] = temp;
madeChanges = true;
}
}
} while (madeChanges);
}
}
class Program
{
static void Main()
{
List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
testList.BubbleSort();
foreach (var t in testList) Console.Write(t + " ");
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | <?php
if (!$in = fopen('input.txt', 'r')) {
die('Could not open input file.');
}
if (!$out = fopen('output.txt', 'w')) {
die('Could not open output file.');
}
while (!feof($in)) {
$data = fread($in, 512);
fwrite($out, $data);
}
fclose($out);
fclose($in);
?>
| using System;
using System.IO;
namespace FileIO
{
class Program
{
static void Main()
{
String s = scope .();
File.ReadAllText("input.txt", s);
File.WriteAllText("output.txt", s);
}
}
}
|
Ensure the translated C# code behaves exactly like the original PHP snippet. | <?php
$a = fgets(STDIN);
$b = fgets(STDIN);
echo
"sum: ", $a + $b, "\n",
"difference: ", $a - $b, "\n",
"product: ", $a * $b, "\n",
"truncating quotient: ", (int)($a / $b), "\n",
"flooring quotient: ", floor($a / $b), "\n",
"remainder: ", $a % $b, "\n",
"power: ", $a ** $b, "\n"; // PHP 5.6+ only
?>
| using System;
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(args[0]);
int b = Convert.ToInt32(args[1]);
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
Console.WriteLine("{0} % {1} = {2}", a, b, a % b);
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}
|
Write the same code in C# as shown below in PHP. | function transpose($m) {
if (count($m) == 0) // special case: empty matrix
return array();
else if (count($m) == 1) // special case: row matrix
return array_chunk($m[0], 1);
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('array_map', $m);
}
| using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
double[,] t = Transpose( m );
for( int i=0; i<t.GetLength(0); i++ )
{
for( int j=0; j<t.GetLength(1); j++ )
Console.Write( t[i,j] + " " );
Console.WriteLine("");
}
}
public static double[,] Transpose( double[,] m )
{
double[,] t = new double[m.GetLength(1),m.GetLength(0)];
for( int i=0; i<m.GetLength(0); i++ )
for( int j=0; j<m.GetLength(1); j++ )
t[j,i] = m[i,j];
return t;
}
}
}
|
Can you help me rewrite this code in C# instead of PHP, keeping it the same logically? | <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
$b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
return A(--$k,$b,$x1,$x2,$x3,$x4);
};
return $k <= 0 ? $x4() + $x5() : $b();
}
echo A(10, function () { return 1; },
function () { return -1; },
function () { return -1; },
function () { return 1; },
function () { return 0; }) . "\n";
?>
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Keep all operations the same but rewrite the snippet in C#. | <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Produce a functionally identical C# code for the snippet given in PHP. | <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Ensure the translated C# code behaves exactly like the original PHP snippet. | function is_perfect($number)
{
$sum = 0;
for($i = 1; $i < $number; $i++)
{
if($number % $i == 0)
$sum += $i;
}
return $sum == $number;
}
echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
if(is_perfect($num))
echo $num . PHP_EOL;
}
| static void Main(string[] args)
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
for (int x = 0; x < 33550337; x++)
{
if (IsPerfect(x))
Console.WriteLine(x + " is perfect.");
}
Console.ReadLine();
}
static bool IsPerfect(int num)
{
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
sum += i;
}
return sum == num ;
}
|
Convert this PHP snippet to C# and keep its semantics consistent. | <?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y));
?>
| using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
Console.WriteLine("n digits = {0}", result.Length);
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the PHP version. | <?php
function buildInvertedIndex($filenames)
{
$invertedIndex = [];
foreach($filenames as $filename)
{
$data = file_get_contents($filename);
if($data === false) die('Unable to read file: ' . $filename);
preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER);
foreach($matches as $match)
{
$word = strtolower($match[0]);
if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];
if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;
}
}
return $invertedIndex;
}
function lookupWord($invertedIndex, $word)
{
return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;
}
$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);
foreach(['cat', 'is', 'banana', 'it'] as $word)
{
$matches = lookupWord($invertedIndex, $word);
if($matches !== false)
{
echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n";
}
else
{
echo "Unable to find the word \"$word\" in the index\n";
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class InvertedIndex
{
static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
{
return dictionary
.SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))
.GroupBy(keyValuePair => keyValuePair.Key)
.ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));
}
static void Main()
{
Console.Write("files: ");
var files = Console.ReadLine();
Console.Write("find: ");
var find = Console.ReadLine();
var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());
Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find]));
}
}
|
Produce a language-to-language conversion: from PHP to C#, same semantics. | echo lcm(12, 18) == 36;
function lcm($m, $n) {
if ($m == 0 || $n == 0) return 0;
$r = ($m * $n) / gcd($m, $n);
return abs($r);
}
function gcd($a, $b) {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
return $a;
}
| Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
|
Change the following PHP code into C# without altering its purpose. | echo lcm(12, 18) == 36;
function lcm($m, $n) {
if ($m == 0 || $n == 0) return 0;
$r = ($m * $n) / gcd($m, $n);
return abs($r);
}
function gcd($a, $b) {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
return $a;
}
| Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
|
Ensure the translated C# code behaves exactly like the original PHP snippet. | while (true) {
$a = rand(0,19);
echo "$a\n";
if ($a == 10)
break;
$b = rand(0,19);
echo "$b\n";
}
| class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
}
|
Port the provided PHP code into C# while preserving the original functionality. |
function middlethree($integer)
{
$int = (int)str_replace('-','',$integer);
$length = strlen($int);
if(is_int($int))
{
if($length >= 3)
{
if($length % 2 == 1)
{
$middle = floor($length / 2) - 1;
return substr($int,$middle, 3);
}
else
{
return 'The value must contain an odd amount of digits...';
}
}
else
{
return 'The value must contain at least three digits...';
}
}
else
{
return 'The value does not appear to be an integer...';
}
}
$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);
foreach($numbers as $nums)
{
echo $nums.' : '.middlethree($nums). '<br>';
}
| using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original PHP code. | 'c'; # character
'hello'; # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n'; # 2-character string with a backslash and "n"
"\n"; # newline character
`ls`; # runs a command in the shell and returns the output as a string
<<END # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END' # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END;
| string path = @"C:\Windows\System32";
string multiline = @"Line 1.
Line 2.
Line 3.";
|
Produce a functionally identical C# code for the snippet given in PHP. |
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
class Fruit {
const APPLE = 0;
const BANANA = 1;
const CHERRY = 2;
}
$value = Fruit::APPLE;
define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);
| enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits : int { apple = 0, banana = 1, cherry = 2 }
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
|
Produce a functionally identical C# code for the snippet given in PHP. | <?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Unix_ls
{
public class UnixLS
{
public static void Main(string[] args)
{
UnixLS ls = new UnixLS();
ls.list(args.Length.Equals(0) ? "." : args[0]);
}
private void list(string folder)
{
foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(fileSystemInfo.Name);
}
}
}
}
|
Convert this PHP snippet to C# and keep its semantics consistent. | <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace MoveToFront
{
class Program
{
private static char[] symbolTable;
private static void setSymbolTable()
{
symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
}
private static void moveToFront(int charIndex)
{
char toFront = symbolTable[charIndex];
for (int j = charIndex; j > 0; j--)
{
symbolTable[j] = symbolTable[j - 1];
}
symbolTable[0] = toFront;
}
public static int[] Encode(string input)
{
setSymbolTable();
var output = new List<int>();
foreach (char c in input)
{
for (int i = 0; i < 26; i++)
{
if (symbolTable[i] == c)
{
output.Add(i);
moveToFront(i);
break;
}
}
}
return output.ToArray();
}
public static string Decode(int[] input)
{
setSymbolTable();
var output = new StringBuilder(input.Length);
foreach (int n in input)
{
output.Append(symbolTable[n]);
moveToFront(n);
}
return output.ToString();
}
static void Main(string[] args)
{
string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" };
int[] encoding;
foreach (string s in testInputs)
{
Console.WriteLine($"Encoding for '{s}':");
encoding = Encode(s);
foreach (int i in encoding)
{
Console.Write($"{i} ");
}
Console.WriteLine($"\nDecoding for '{s}':");
Console.WriteLine($"{Decode(encoding)}\n");
}
}
}
}
|
Please provide an equivalent version of this PHP code in C#. | @exec($command,$output);
echo nl2br($output);
| using System.Diagnostics;
namespace Execute
{
class Program
{
static void Main(string[] args)
{
Process.Start("cmd.exe", "/c dir");
}
}
}
|
Please provide an equivalent version of this PHP code in C#. | libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load('shiporder.xml');
if (!$xml->schemaValidate('shiporder.xsd')) {
var_dump(libxml_get_errors()); exit;
} else {
echo 'success';
}
| using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class Test
{
public static void Main()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, "http:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
XmlReader reader = XmlReader.Create("http:
while (reader.Read());
Console.WriteLine("The XML file is valid for the given xsd file");
}
private static void ValidationCallBack(object sender, ValidationEventArgs e) {
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
|
Preserve the algorithm and functionality while converting the code from PHP to C#. | <?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class LIS
{
public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>
values == null ? throw new ArgumentNullException() :
FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();
private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {
if (index == values.Count) return current;
if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)
return FindRecImpl(values, current, index + 1, comparer);
return Max(
FindRecImpl(values, current, index + 1, comparer),
FindRecImpl(values, current + values[index], index + 1, comparer)
);
}
private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;
class Sequence<T> : IEnumerable<T>
{
public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);
public Sequence(T value, Sequence<T> tail)
{
Value = value;
Tail = tail;
Length = tail == null ? 0 : tail.Length + 1;
}
public T Value { get; }
public Sequence<T> Tail { get; }
public int Length { get; }
public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);
public IEnumerator<T> GetEnumerator()
{
for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
Convert this PHP snippet to C# and keep its semantics consistent. | function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static System.Linq.Enumerable;
public static class BraceExpansion
{
enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }
const char L = '{', R = '}', S = ',';
public static void Main() {
string[] input = {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
@"{,{,gotta have{ ,\, again\, }}more }cowbell!",
@"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
};
foreach (string text in input) Expand(text);
}
static void Expand(string input) {
Token token = Tokenize(input);
foreach (string value in token) Console.WriteLine(value);
Console.WriteLine();
}
static Token Tokenize(string input) {
var tokens = new List<Token>();
var buffer = new StringBuilder();
bool escaping = false;
int level = 0;
foreach (char c in input) {
(escaping, level, tokens, buffer) = c switch {
_ when escaping => (false, level, tokens, buffer.Append(c)),
'\\' => (true, level, tokens, buffer.Append(c)),
L => (escaping, level + 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),
S when level > 0 => (escaping, level,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),
R when level > 0 => (escaping, level - 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),
_ => (escaping, level, tokens, buffer.Append(c))
};
}
if (buffer.Length > 0) tokens.Add(buffer.Flush());
for (int i = 0; i < tokens.Count; i++) {
if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {
tokens[i] = tokens[i].Value;
}
}
return new Token(tokens, TokenType.Concat);
}
static List<Token> Merge(this List<Token> list) {
int separators = 0;
int last = list.Count - 1;
for (int i = list.Count - 3; i >= 0; i--) {
if (list[i].Type == TokenType.Separator) {
separators++;
Concat(list, i + 1, last);
list.RemoveAt(i);
last = i;
} else if (list[i].Type == TokenType.OpenBrace) {
Concat(list, i + 1, last);
if (separators > 0) {
list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);
list.RemoveRange(i+1, list.Count - i - 1);
} else {
list[i] = L.ToString();
list[^1] = R.ToString();
Concat(list, i, list.Count);
}
break;
}
}
return list;
}
static void Concat(List<Token> list, int s, int e) {
for (int i = e - 2; i >= s; i--) {
(Token a, Token b) = (list[i], list[i+1]);
switch (a.Type, b.Type) {
case (TokenType.Text, TokenType.Text):
list[i] = a.Value + b.Value;
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Concat):
a.SubTokens.AddRange(b.SubTokens);
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Text) when b.Value == "":
list.RemoveAt(i+1);
break;
case (TokenType.Text, TokenType.Concat) when a.Value == "":
list.RemoveAt(i);
break;
default:
list[i] = new Token(new [] { a, b }, TokenType.Concat);
list.RemoveAt(i+1);
break;
}
}
}
private struct Token : IEnumerable<string>
{
private List<Token>? _subTokens;
public string Value { get; }
public TokenType Type { get; }
public List<Token> SubTokens => _subTokens ??= new List<Token>();
public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);
public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList());
public static implicit operator Token(string value) => new Token(value, TokenType.Text);
public IEnumerator<string> GetEnumerator() => (Type switch
{
TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)),
TokenType.Alternate => from t in SubTokens from s in t select s,
_ => Repeat(Value, 1)
}).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
static List<Token> With(this List<Token> list, Token token) {
list.Add(token);
return list;
}
static IEnumerable<Token> Range(this List<Token> list, Range range) {
int start = range.Start.GetOffset(list.Count);
int end = range.End.GetOffset(list.Count);
for (int i = start; i < end; i++) yield return list[i];
}
static string Flush(this StringBuilder builder) {
string result = builder.ToString();
builder.Clear();
return result;
}
}
|
Produce a language-to-language conversion: from PHP to C#, same semantics. | <?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf("%d\n", invmod(42, 2017));
?>
| public class Program
{
static void Main()
{
System.Console.WriteLine(42.ModInverse(2017));
}
}
public static class IntExtensions
{
public static int ModInverse(this int a, int m)
{
if (m == 1) return 0;
int m0 = m;
(int x, int y) = (1, 0);
while (a > 1) {
int q = a / m;
(a, m) = (m, a % m);
(x, y) = (y, x - q * y);
}
return x < 0 ? x + m0 : x;
}
}
|
Rewrite the snippet below in C# so it works the same as the original PHP code. | <?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
socket_bind($socket, 0, 8080);
socket_listen($socket);
$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';
for (;;) {
if ($client = @socket_accept($socket)) {
socket_write($client, "HTTP/1.1 200 OK\r\n" .
"Content-length: " . strlen($msg) . "\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n\r\n" .
$msg);
}
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?>
| using System.Text;
using System.Net.Sockets;
using System.Net;
namespace WebServer
{
class GoodByeWorld
{
static void Main(string[] args)
{
const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";
const int port = 8080;
bool serverRunning = true;
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (serverRunning)
{
Socket socketConnection = tcpListener.AcceptSocket();
byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);
socketConnection.Send(bMsg);
socketConnection.Disconnect(true);
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
|
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
|
Convert the following code from PHP to C#, ensuring the logic remains intact. | .12
0.1234
1.2e3
7E-10
| double d = 1;
d = 1d;
d = 1D;
d = 1.2;
d = 1.2d;
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2;
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m;
|
Translate this program into C# but keep the logic exactly as in PHP. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
| using System;
public delegate Church Church(Church f);
public static class ChurchNumeral
{
public static readonly Church ChurchZero = _ => x => x;
public static readonly Church ChurchOne = f => f;
public static Church Successor(this Church n) => f => x => f(n(f)(x));
public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));
public static Church Multiply(this Church m, Church n) => f => m(n(f));
public static Church Exponent(this Church m, Church n) => n(m);
public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);
public static Church Predecessor(this Church n) =>
f => x => n(g => h => h(g(f)))(_ => x)(a => a);
public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);
static Church looper(this Church v, Church d) =>
v(_ => v.divr(d).Successor())(ChurchZero);
static Church divr(this Church n, Church d) =>
n.Subtract(d).looper(d);
public static Church Divide(this Church dvdnd, Church dvsr) =>
(dvdnd.Successor()).divr(dvsr);
public static Church FromInt(int i) =>
i <= 0 ? ChurchZero : Successor(FromInt(i - 1));
public static int ToInt(this Church ch) {
int count = 0;
ch(x => { count++; return x; })(null);
return count;
}
public static void Main() {
Church c3 = FromInt(3);
Church c4 = c3.Successor();
Church c11 = FromInt(11);
Church c12 = c11.Successor();
int sum = c3.Add(c4).ToInt();
int product = c3.Multiply(c4).ToInt();
int exp43 = c4.Exponent(c3).ToInt();
int exp34 = c3.Exponent(c4).ToInt();
int tst0 = ChurchZero.IsZero().ToInt();
int pred4 = c4.Predecessor().ToInt();
int sub43 = c4.Subtract(c3).ToInt();
int div11by3 = c11.Divide(c3).ToInt();
int div12by3 = c12.Divide(c3).ToInt();
Console.Write($"{sum} {product} {exp43} {exp34} {tst0} ");
Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}");
}
}
|
Can you help me rewrite this code in C# instead of PHP, keeping it the same logically? | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
| using System;
public delegate Church Church(Church f);
public static class ChurchNumeral
{
public static readonly Church ChurchZero = _ => x => x;
public static readonly Church ChurchOne = f => f;
public static Church Successor(this Church n) => f => x => f(n(f)(x));
public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));
public static Church Multiply(this Church m, Church n) => f => m(n(f));
public static Church Exponent(this Church m, Church n) => n(m);
public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);
public static Church Predecessor(this Church n) =>
f => x => n(g => h => h(g(f)))(_ => x)(a => a);
public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);
static Church looper(this Church v, Church d) =>
v(_ => v.divr(d).Successor())(ChurchZero);
static Church divr(this Church n, Church d) =>
n.Subtract(d).looper(d);
public static Church Divide(this Church dvdnd, Church dvsr) =>
(dvdnd.Successor()).divr(dvsr);
public static Church FromInt(int i) =>
i <= 0 ? ChurchZero : Successor(FromInt(i - 1));
public static int ToInt(this Church ch) {
int count = 0;
ch(x => { count++; return x; })(null);
return count;
}
public static void Main() {
Church c3 = FromInt(3);
Church c4 = c3.Successor();
Church c11 = FromInt(11);
Church c12 = c11.Successor();
int sum = c3.Add(c4).ToInt();
int product = c3.Multiply(c4).ToInt();
int exp43 = c4.Exponent(c3).ToInt();
int exp34 = c3.Exponent(c4).ToInt();
int tst0 = ChurchZero.IsZero().ToInt();
int pred4 = c4.Predecessor().ToInt();
int sub43 = c4.Subtract(c3).ToInt();
int div11by3 = c11.Divide(c3).ToInt();
int div12by3 = c12.Divide(c3).ToInt();
Console.Write($"{sum} {product} {exp43} {exp34} {tst0} ");
Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}");
}
}
|
Change the programming language of this snippet from PHP to C# without modifying what it does. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the PHP version. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
}
|
Write the same code in C# as shown below in PHP. | $myObj = new Object();
$serializedObj = serialize($myObj);
| using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace Object_serialization
{
[Serializable] public class Being
{
public bool Alive { get; set; }
}
[Serializable] public class Animal: Being
{
public Animal() { }
public Animal(long id, string name, bool alive = true)
{
Id = id;
Name = name;
Alive = alive;
}
public long Id { get; set; }
public string Name { get; set; }
public void Print() { Console.WriteLine("{0}, id={1} is {2}",
Name, Id, Alive ? "alive" : "dead"); }
}
internal class Program
{
private static void Main()
{
string path =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat";
var n = new List<Animal>
{
new Animal(1, "Fido"),
new Animal(2, "Lupo"),
new Animal(7, "Wanda"),
new Animal(3, "Kiki", alive: false)
};
foreach(Animal animal in n)
animal.Print();
using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))
new BinaryFormatter().Serialize(stream, n);
n.Clear();
Console.WriteLine("---------------");
List<Animal> m;
using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
m = (List<Animal>) new BinaryFormatter().Deserialize(stream);
foreach(Animal animal in m)
animal.Print();
}
}
}
|
Convert the following code from PHP to C#, ensuring the logic remains intact. | function isLongYear($year) {
return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}
for ($y=1995; $y<=2045; ++$y) {
if (isLongYear($y)) {
printf("%s\n", $y);
}
}
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program
{
public static void Main()
{
WriteLine("Long years in the 21st century:");
WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
}
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i < end; i++) yield return i;
}
}
|
Translate the given PHP code snippet into C# without altering its behavior. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
|
Write a version of this PHP function in C# with identical behavior. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
|
Transform the following PHP implementation into C#, maintaining the same output and logic. | <?php
function markovChainTextGenerator($text, $keySize, $maxWords) {
$token = array();
$position = 0;
$maxPosition = strlen($text);
while ($position < $maxPosition) {
if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) {
$token[] = $matches[1];
$position += strlen($matches[1]);
}
elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) {
$position += strlen($matches[1]);
}
else {
die(
'Unknown token found at position ' . $position . ' : ' .
substr($text, $position, 25) . '...' . PHP_EOL
);
}
}
$dictionary = array();
for ($i = 0 ; $i < count($token) - $keySize ; $i++) {
$prefix = '';
$separator = '';
for ($c = 0 ; $c < $keySize ; $c++) {
$prefix .= $separator . $token[$i + $c];
$separator = '.';
}
$dictionary[$prefix][] = $token[$i + $keySize];
}
$rand = rand(0, count($token) - $keySize);
$startToken = array();
for ($c = 0 ; $c < $keySize ; $c++) {
array_push($startToken, $token[$rand + $c]);
}
$text = implode(' ', $startToken);
$words = $keySize;
do {
$tokenKey = implode('.', $startToken);
$rand = rand(0, count($dictionary[$tokenKey]) - 1);
$newToken = $dictionary[$tokenKey][$rand];
$text .= ' ' . $newToken;
$words++;
array_shift($startToken);
array_push($startToken, $newToken);
} while($words < $maxWords);
return $text;
}
srand(5678);
$text = markovChainTextGenerator(
file_get_contents(__DIR__ . '/inc/alice_oz.txt'),
3,
308
);
echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MarkovChainTextGenerator {
class Program {
static string Join(string a, string b) {
return a + " " + b;
}
static string Markov(string filePath, int keySize, int outputSize) {
if (keySize < 1) throw new ArgumentException("Key size can't be less than 1");
string body;
using (StreamReader sr = new StreamReader(filePath)) {
body = sr.ReadToEnd();
}
var words = body.Split();
if (outputSize < keySize || words.Length < outputSize) {
throw new ArgumentException("Output size is out of range");
}
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
for (int i = 0; i < words.Length - keySize; i++) {
var key = words.Skip(i).Take(keySize).Aggregate(Join);
string value;
if (i + keySize < words.Length) {
value = words[i + keySize];
} else {
value = "";
}
if (dict.ContainsKey(key)) {
dict[key].Add(value);
} else {
dict.Add(key, new List<string>() { value });
}
}
Random rand = new Random();
List<string> output = new List<string>();
int n = 0;
int rn = rand.Next(dict.Count);
string prefix = dict.Keys.Skip(rn).Take(1).Single();
output.AddRange(prefix.Split());
while (true) {
var suffix = dict[prefix];
if (suffix.Count == 1) {
if (suffix[0] == "") {
return output.Aggregate(Join);
}
output.Add(suffix[0]);
} else {
rn = rand.Next(suffix.Count);
output.Add(suffix[rn]);
}
if (output.Count >= outputSize) {
return output.Take(outputSize).Aggregate(Join);
}
n++;
prefix = output.Skip(n).Take(keySize).Aggregate(Join);
}
}
static void Main(string[] args) {
Console.WriteLine(Markov("alice_oz.txt", 3, 200));
}
}
}
|
Produce a functionally identical C# code for the snippet given in PHP. | <?php
function dijkstra($graph_array, $source, $target) {
$vertices = array();
$neighbours = array();
foreach ($graph_array as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]);
$neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]);
}
$vertices = array_unique($vertices);
foreach ($vertices as $vertex) {
$dist[$vertex] = INF;
$previous[$vertex] = NULL;
}
$dist[$source] = 0;
$Q = $vertices;
while (count($Q) > 0) {
$min = INF;
foreach ($Q as $vertex){
if ($dist[$vertex] < $min) {
$min = $dist[$vertex];
$u = $vertex;
}
}
$Q = array_diff($Q, array($u));
if ($dist[$u] == INF or $u == $target) {
break;
}
if (isset($neighbours[$u])) {
foreach ($neighbours[$u] as $arr) {
$alt = $dist[$u] + $arr["cost"];
if ($alt < $dist[$arr["end"]]) {
$dist[$arr["end"]] = $alt;
$previous[$arr["end"]] = $u;
}
}
}
}
$path = array();
$u = $target;
while (isset($previous[$u])) {
array_unshift($path, $u);
$u = $previous[$u];
}
array_unshift($path, $u);
return $path;
}
$graph_array = array(
array("a", "b", 7),
array("a", "c", 9),
array("a", "f", 14),
array("b", "c", 10),
array("b", "d", 15),
array("c", "d", 11),
array("c", "f", 2),
array("d", "e", 6),
array("e", "f", 9)
);
$path = dijkstra($graph_array, "a", "e");
echo "path is: ".implode(", ", $path)."\n";
| using static System.Linq.Enumerable;
using static System.String;
using static System.Console;
using System.Collections.Generic;
using System;
using EdgeList = System.Collections.Generic.List<(int node, double weight)>;
public static class Dijkstra
{
public static void Main() {
Graph graph = new Graph(6);
Func<char, int> id = c => c - 'a';
Func<int , char> name = i => (char)(i + 'a');
foreach (var (start, end, cost) in new [] {
('a', 'b', 7),
('a', 'c', 9),
('a', 'f', 14),
('b', 'c', 10),
('b', 'd', 15),
('c', 'd', 11),
('c', 'f', 2),
('d', 'e', 6),
('e', 'f', 9),
}) {
graph.AddEdge(id(start), id(end), cost);
}
var path = graph.FindPath(id('a'));
for (int d = id('b'); d <= id('f'); d++) {
WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse()));
}
IEnumerable<(double distance, int node)> Path(int start, int destination) {
yield return (path[destination].distance, destination);
for (int i = destination; i != start; i = path[i].prev) {
yield return (path[path[i].prev].distance, path[i].prev);
}
}
}
}
sealed class Graph
{
private readonly List<EdgeList> adjacency;
public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();
public int Count => adjacency.Count;
public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);
public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;
public bool AddEdge(int s, int e, double weight) {
if (HasEdge(s, e)) return false;
adjacency[s].Add((e, weight));
return true;
}
public (double distance, int prev)[] FindPath(int start) {
var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();
info[start].distance = 0;
var visited = new System.Collections.BitArray(adjacency.Count);
var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));
heap.Push((start, 0));
while (heap.Count > 0) {
var current = heap.Pop();
if (visited[current.node]) continue;
var edges = adjacency[current.node];
for (int n = 0; n < edges.Count; n++) {
int v = edges[n].node;
if (visited[v]) continue;
double alt = info[current.node].distance + edges[n].weight;
if (alt < info[v].distance) {
info[v] = (alt, current.node);
heap.Push((v, alt));
}
}
visited[current.node] = true;
}
return info;
}
}
sealed class Heap<T>
{
private readonly IComparer<T> comparer;
private readonly List<T> list = new List<T> { default };
public Heap() : this(default(IComparer<T>)) { }
public Heap(IComparer<T> comparer) {
this.comparer = comparer ?? Comparer<T>.Default;
}
public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }
public int Count => list.Count - 1;
public void Push(T element) {
list.Add(element);
SiftUp(list.Count - 1);
}
public T Pop() {
T result = list[1];
list[1] = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
SiftDown(1);
return result;
}
private static int Parent(int i) => i / 2;
private static int Left(int i) => i * 2;
private static int Right(int i) => i * 2 + 1;
private void SiftUp(int i) {
while (i > 1) {
int parent = Parent(i);
if (comparer.Compare(list[i], list[parent]) > 0) return;
(list[parent], list[i]) = (list[i], list[parent]);
i = parent;
}
}
private void SiftDown(int i) {
for (int left = Left(i); left < list.Count; left = Left(i)) {
int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;
int right = Right(i);
if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;
if (smallest == i) return;
(list[i], list[smallest]) = (list[smallest], list[i]);
i = smallest;
}
}
}
|
Can you help me rewrite this code in C# instead of PHP, keeping it the same logically? | <?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
foreach($pairs as $value) {
echo "values = $value\n";
}
?>
| using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
assocArray["!"] = 3;
foreach (KeyValuePair<string, int> kvp in assocArray)
{
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | <?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
array(28, "Glory"),
array(18, "Popeye"),
array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
array("Jonah", "Spiders"),
array("Alan", "Ghosts"),
array("Alan", "Zombies"),
array("Glory", "Buffy"),
array("Bob", "foo"));
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?>
| using System;
using System.Collections.Generic;
using System.Linq;
namespace HashJoin
{
public class AgeName
{
public AgeName(byte age, string name)
{
Age = age;
Name = name;
}
public byte Age { get; private set; }
public string Name { get; private set; }
}
public class NameNemesis
{
public NameNemesis(string name, string nemesis)
{
Name = name;
Nemesis = nemesis;
}
public string Name { get; private set; }
public string Nemesis { get; private set; }
}
public class DataContext
{
public DataContext()
{
AgeName = new List<AgeName>();
NameNemesis = new List<NameNemesis>();
}
public List<AgeName> AgeName { get; set; }
public List<NameNemesis> NameNemesis { get; set; }
}
public class AgeNameNemesis
{
public AgeNameNemesis(byte age, string name, string nemesis)
{
Age = age;
Name = name;
Nemesis = nemesis;
}
public byte Age { get; private set; }
public string Name { get; private set; }
public string Nemesis { get; private set; }
}
class Program
{
public static void Main()
{
var data = GetData();
var result = ExecuteHashJoin(data);
WriteResultToConsole(result);
}
private static void WriteResultToConsole(List<AgeNameNemesis> result)
{
result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}",
ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));
}
private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)
{
return (data.AgeName.Join(data.NameNemesis,
ageName => ageName.Name, nameNemesis => nameNemesis.Name,
(ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))
.ToList();
}
private static DataContext GetData()
{
var context = new DataContext();
context.AgeName.AddRange(new [] {
new AgeName(27, "Jonah"),
new AgeName(18, "Alan"),
new AgeName(28, "Glory"),
new AgeName(18, "Popeye"),
new AgeName(28, "Alan")
});
context.NameNemesis.AddRange(new[]
{
new NameNemesis("Jonah", "Whales"),
new NameNemesis("Jonah", "Spiders"),
new NameNemesis("Alan", "Ghosts"),
new NameNemesis("Alan", "Zombies"),
new NameNemesis("Glory", "Buffy")
});
return context;
}
}
}
|
Produce a language-to-language conversion: from PHP to C#, same semantics. | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$example->foo(); // prints "this is foo"
$example->bar(); // prints "this is bar"
$example->grill(); // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"
?>
| using System;
using System.Dynamic;
class Example : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
Console.WriteLine("This is {0}.", binder.Name);
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic ex = new Example();
ex.Foo();
ex.Bar();
}
}
|
Translate the given PHP code snippet into C# without altering its behavior. | class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Lab extends Dog {
}
class Collie extends Dog {
}
| class Animal
{
}
class Dog : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
}
class Cat : Animal
{
}
|
Generate a C# translation of this PHP snippet without changing its computational steps. | $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']); // bar
echo($array['moo']); // Undefined index
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
| System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";
|
Port the provided PHP code into C# while preserving the original functionality. | class Point
{
protected $_x;
protected $_y;
public function __construct()
{
switch( func_num_args() )
{
case 1:
$point = func_get_arg( 0 );
$this->setFromPoint( $point );
break;
case 2:
$x = func_get_arg( 0 );
$y = func_get_arg( 1 );
$this->setX( $x );
$this->setY( $y );
break;
default:
throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
}
}
public function setFromPoint( Point $point )
{
$this->setX( $point->getX() );
$this->setY( $point->getY() );
}
public function getX()
{
return $this->_x;
}
public function setX( $x )
{
if( !is_numeric( $x ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_x = (float) $x;
}
public function getY()
{
return $this->_y;
}
public function setY( $y )
{
if( !is_numeric( $y ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_y = (float) $y;
}
public function output()
{
echo $this->__toString();
}
public function __toString()
{
return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
}
}
| using System;
class Point
{
protected int x, y;
public Point() : this(0) {}
public Point(int x) : this(x,0) {}
public Point(int x, int y) { this.x = x; this.y = y; }
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
public virtual void print() { System.Console.WriteLine("Point"); }
}
public class Circle : Point
{
private int r;
public Circle(Point p) : this(p,0) { }
public Circle(Point p, int r) : base(p) { this.r = r; }
public Circle() : this(0) { }
public Circle(int x) : this(x,0) { }
public Circle(int x, int y) : this(x,y,0) { }
public Circle(int x, int y, int r) : base(x,y) { this.r = r; }
public int R { get { return r; } set { r = value; } }
public override void print() { System.Console.WriteLine("Circle"); }
public static void main(String args[])
{
Point p = new Point();
Point c = new Circle();
p.print();
c.print();
}
}
|
Port the provided PHP code into C# while preserving the original functionality. | <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
var_dump(get_object_vars($obj));
?>
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetPropertyValues(t, flags)) {
Console.WriteLine(prop);
}
foreach (var field in GetFieldValues(t, flags)) {
Console.WriteLine(field);
}
}
public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>
from p in typeof(T).GetProperties(flags)
where p.GetIndexParameters().Length == 0
select (p.Name, p.GetValue(obj, null));
public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>
typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));
class TestClass
{
private int privateField = 7;
public int PublicNumber { get; } = 4;
private int PrivateNumber { get; } = 2;
}
}
|
Change the programming language of this snippet from PHP to C# without modifying what it does. | <?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'C' => STR_PAD_BOTH);
function aligner($str, $justification = 'L') {
global $j2justtype;
assert(array_key_exists($justification, $j2justtype));
$justtype = $j2justtype[$justification];
$fieldsbyrow = array();
foreach (explode("\n", $str) as $line)
$fieldsbyrow[] = explode('$', $line);
$maxfields = max(array_map('count', $fieldsbyrow));
foreach (range(0, $maxfields - 1) as $col) {
$maxwidth = 0;
foreach ($fieldsbyrow as $fields)
$maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
foreach ($fieldsbyrow as &$fields)
$fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
unset($fields); // see http://bugs.php.net/29992
}
$result = '';
foreach ($fieldsbyrow as $fields)
$result .= implode(' ', $fields) . "\n";
return $result;
}
$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.';
foreach (array('L', 'R', 'C') as $j)
echo aligner($textinfile, $j);
?>
| using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].TrimEnd(Separator).Split(Separator);
if (columns < row.Length) columns = row.Length;
table[i] = row;
}
string[][] formattedTable = new string[table.Length][];
for (int i = 0; i < formattedTable.Length; i++)
{
formattedTable[i] = new string[columns];
}
for (int j = 0; j < columns; j++)
{
int columnWidth = 0;
for (int i = 0; i < table.Length; i++)
{
if (j < table[i].Length && columnWidth < table[i][j].Length)
columnWidth = table[i][j].Length;
}
for (int i = 0; i < formattedTable.Length; i++)
{
if (j < table[i].Length)
formattedTable[i][j] = justification(table[i][j], columnWidth);
else
formattedTable[i][j] = new String(' ', columnWidth);
}
}
string[] result = new string[formattedTable.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = String.Join(" ", formattedTable[i]);
}
return result;
}
static string JustifyLeft(string s, int width) { return s.PadRight(width); }
static string JustifyRight(string s, int width) { return s.PadLeft(width); }
static string JustifyCenter(string s, int width)
{
return s.PadLeft((width + s.Length) / 2).PadRight(width);
}
static void Main()
{
string[] input = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column.",
};
foreach (string line in AlignColumns(input, JustifyCenter))
{
Console.WriteLine(line);
}
}
}
|
Change the following PHP code into C# without altering its purpose. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:John.Doe@example.com',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo:
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql:
ParseUrl("ftp:
ParseUrl("http:
ParseUrl("ldap:
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet:
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
|
Produce a functionally identical C# code for the snippet given in PHP. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:John.Doe@example.com',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo:
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql:
ParseUrl("ftp:
ParseUrl("http:
ParseUrl("ldap:
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet:
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
|
Convert this PHP snippet to C# and keep its semantics consistent. | <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
| using System;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string varname = Console.ReadLine();
dynamic expando = new ExpandoObject();
var map = expando as IDictionary<string, object>;
map.Add(varname, "Hello world!");
Console.WriteLine(expando.foo);
}
}
|
Rewrite the snippet below in C# so it works the same as the original PHP code. | <?
class Foo {
function bar(int $x) {
}
}
$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
echo "$name\n";
$method_info = new ReflectionMethod('Foo', $name);
echo $method_info;
}
?>
| using System;
using System.Reflection;
public class Rosetta
{
public static void Main()
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.DeclaredOnly;
foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))
Console.WriteLine(method);
}
class TestForMethodReflection
{
public void MyPublicMethod() {}
private void MyPrivateMethod() {}
public static void MyPublicStaticMethod() {}
private static void MyPrivateStaticMethod() {}
}
}
|
Write the same code in C# as shown below in PHP. | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
echo call_user_func(array($example, $name), 5), "\n";
?>
| using System;
class Example
{
public int foo(int x)
{
return 42 + x;
}
}
class Program
{
static void Main(string[] args)
{
var example = new Example();
var method = "foo";
var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });
Console.WriteLine("{0}(5) = {1}", method, result);
}
}
|
Convert the following code from PHP to C#, ensuring the logic remains intact. | <?php
# NULL typed variable
$null = NULL; var_dump($null); // output: null
# defining a boolean
$boolean = true; var_dump($boolean); // output: boolean true
$boolean = false; var_dump($boolean); // output: boolean false
# bool and boolean is the same
$boolean = (bool)1; var_dump($boolean); // output: boolean true
$boolean = (boolean)1; var_dump($boolean); // output: boolean true
$boolean = (bool)0; var_dump($boolean); // output: boolean false
$boolean = (boolean)0; var_dump($boolean); // output: boolean false
# defining an integer
$int = 0; var_dump($int); // output: int 0
# defining a float,
$float = 0.01; var_dump($float); // output: float 0.01
# which is also identical to "real" and "double"
var_dump((double)$float); // output: float 0.01
var_dump((real)$float); // output: float 0.01
# casting back to int (auto flooring the value)
var_dump((int)$float); // output: int 0
var_dump((int)($float+1)); // output: int 1
var_dump((int)($float+1.9)); // output: int 1
# defining a string
$string = 'string';
var_dump($string); // output: string 'string' (length=6)
# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
$string = "I'm the same string!";
var_dump($another_string);
# "deleting" a variable from memory
unset($another_string);
$string = 'string';
$parsed_string = "This is a $string";
var_dump($parsed_string);
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass(); var_dump($stdObject);
# defining an object typed Foo
class Foo {}
$foo = new Foo(); var_dump($foo);
# defining an empty array
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL, // <=== key 3 is NULL
3, // <=== this is a value, not a key (key is 4)
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
# not reachable
var_dump(isset($foo)); // output: boolean false
global $foo;
# "global" (reachable) inside a_function()'s scope
var_dump(isset($foo)); // output: boolean true
}
a_function();
| int j;
|
Convert this PHP snippet to C# and keep its semantics consistent. | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
|
using System;
using System.Dynamic;
namespace DynamicClassVariable
{
internal static class Program
{
#region Static Members
private static void Main()
{
dynamic sampleObj = new ExpandoObject();
sampleObj.bar = 1;
Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar );
Console.WriteLine( "< Press any key >" );
Console.ReadKey();
}
#endregion
}
}
|
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically? | #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
| import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open("notes.txt", "r") as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open("notes.txt", "a") as f:
f.write(datetime.datetime.now().isoformat() + "\n")
f.write("\t%s\n" % ' '.join(sys.argv[1:]))
|
Translate this program into Python but keep the logic exactly as in PHP. | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
|
Port the provided PHP code into Python while preserving the original functionality. | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
|
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically? | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
|
Change the following PHP code into Python without altering its purpose. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
Change the following PHP code into Python without altering its purpose. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
Produce a functionally identical Python code for the snippet given in PHP. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
Keep all operations the same but rewrite the snippet in Python. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.