Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate this program into PHP but keep the logic exactly as in Python. | >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2
| <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
Produce a functionally identical PHP code for the snippet given in Python. | 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:]))
| #!/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');
|
Translate the given Python code snippet into PHP without altering its behavior. | 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:]))
| #!/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');
|
Write the same algorithm in PHP as shown in this VB implementation. | Debug.Print Hex(&HF0F0 And &HFF00)
Debug.Print Hex(&HF0F0 Or &HFF00)
Debug.Print Hex(&HF0F0 Xor &HFF00)
Debug.Print Hex(Not &HF0F0)
Debug.Print Hex(&HF0F0 Eqv &HFF00)
Debug.Print Hex(&HF0F0 Imp &HFF00)
| function bitwise($a, $b)
{
function zerofill($a,$b) {
if($a>=0) return $a>>$b;
if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens
return ((~$a)>>$b)^(0x7fffffff>>($b-1));
echo '$a AND $b: ' . $a & $b . '\n';
echo '$a OR $b: ' . $a | $b . '\n';
echo '$a XOR $b: ' . $a ^ $b . '\n';
echo 'NOT $a: ' . ~$a . '\n';
echo '$a << $b: ' . $a << $b . '\n'; // left shift
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}
|
Write the same code in PHP as shown below in VB. | $Include "Rapidq.inc"
dim file as qfilestream
if file.open("c:\A Test.txt", fmOpenRead) then
while not File.eof
print File.readline
wend
else
print "Cannot read file"
end if
input "Press enter to exit: ";a$
| <?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
$line = rtrim($line); // removes linebreaks and spaces at end
echo strrev($line) . "\n"; // reverse line and upload it
}
|
Produce a language-to-language conversion: from VB to PHP, same semantics. | Private Function to_base(ByVal number As Long, base As Integer) As String
Dim digits As String, result As String
Dim i As Integer, digit As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Do While number > 0
digit = number Mod base
result = Mid(digits, digit + 1, 1) & result
number = number \ base
Loop
to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
Dim digits As String, result As Long
Dim i As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
For i = 2 To Len(number)
result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
Next i
from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub
| base_convert("26", 10, 16); // returns "1a"
|
Change the programming language of this snippet from VB to PHP without modifying what it does. | Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
| function findFiles($dir = '.', $pattern = '/./'){
$prefix = $dir . '/';
$dir = dir($dir);
while (false !== ($file = $dir->read())){
if ($file === '.' || $file === '..') continue;
$file = $prefix . $file;
if (is_dir($file)) findFiles($file, $pattern);
if (preg_match($pattern, $file)){
echo $file . "\n";
}
}
}
findFiles('./foo', '/\.bar$/');
|
Generate a PHP translation of this VB snippet without changing its computational steps. | dim crctbl(255)
const crcc =&hEDB88320
sub gencrctable
for i= 0 to 255
k=i
for j=1 to 8
if k and 1 then
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
k=k xor crcc
else
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
end if
next
crctbl(i)=k
next
end sub
function crc32 (buf)
dim r,r1,i
r=&hffffffff
for i=1 to len(buf)
r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255)
next
crc32=r xor &hffffffff
end function
gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
| printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
|
Convert the following code from VB to PHP, ensuring the logic remains intact. | Class NumberContainer
Private TheNumber As Integer
Sub Constructor(InitialNumber As Integer)
TheNumber = InitialNumber
End Sub
Function Number() As Integer
Return TheNumber
End Function
Sub Number(Assigns NewNumber As Integer)
TheNumber = NewNumber
End Sub
End Class
| class MyClass {
public static $classVar;
public $instanceVar; // can also initialize it here
function __construct() {
$this->instanceVar = 0;
}
function someMethod() {
$this->instanceVar = 1;
self::$classVar = 3;
}
}
$myObj = new MyClass();
|
Translate this program into PHP but keep the logic exactly as in VB. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| set_time_limit(300);
print_r(array_filter(range(1, 10000), 'isKaprekar'));
echo count(array_filter(range(1, 1000000), 'isKaprekar'));
function isKaprekar($n) {
$a = $n * $n;
$b = bcmod("$a", "10");
for ($d = 1, $t = 0; $a > 0; $d *= 10) {
$b += $t * $d;
if ($b > $n) break;
$a = floor($a / 10);
if ($b && $a + $b == $n)
return true;
$t = bcmod("$a", "10");
}
return false;
}
|
Write the same algorithm in PHP as shown in this VB implementation. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| set_time_limit(300);
print_r(array_filter(range(1, 10000), 'isKaprekar'));
echo count(array_filter(range(1, 1000000), 'isKaprekar'));
function isKaprekar($n) {
$a = $n * $n;
$b = bcmod("$a", "10");
for ($d = 1, $t = 0; $a > 0; $d *= 10) {
$b += $t * $d;
if ($b > $n) break;
$a = floor($a / 10);
if ($b && $a + $b == $n)
return true;
$t = bcmod("$a", "10");
}
return false;
}
|
Maintain the same structure and functionality when rewriting this code in PHP. | Option Explicit
Const numchars=127
Function LZWCompress(si)
Dim oDict, intMaxCode, i,z,ii,ss,strCurrent,strNext,j
Set oDict = CreateObject("Scripting.Dictionary")
ReDim a(Len(si))
intMaxCode = numchars
For i = 0 To numchars
oDict.Add Chr(i), i
Next
strCurrent = Left(si,1)
j=0
For ii=2 To Len(si)
strNext = Mid(si,ii,1)
ss=strCurrent & strNext
If oDict.Exists(ss) Then
strCurrent = ss
Else
a(j)=oDict.Item(strCurrent) :j=j+1
intMaxCode = intMaxCode + 1
oDict.Add ss, intMaxCode
strCurrent = strNext
End If
Next
a(j)=oDict.Item(strCurrent)
ReDim preserve a(j)
LZWCompress=a
Set oDict = Nothing
End Function
Function lzwUncompress(sc)
Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j
s=""
reDim dict(1000)
intMaxCode = numchars
For i = 0 To numchars : dict(i)= Chr(i) : Next
intCurrent=sc(0)
For j=1 To UBound(sc)
ss=dict(intCurrent)
s= s & ss
intMaxCode = intMaxCode + 1
intnext=sc(j)
If intNext<intMaxCode Then
dict(intMaxCode)=ss & Left(dict(intNext), 1)
Else
dict(intMaxCode)=ss & Left(ss, 1)
End If
intCurrent = intNext
Next
s= s & dict(intCurrent)
lzwUncompress=s
End function
Sub printvec(a)
Dim s,i,x
s="("
For i=0 To UBound (a)
s=s & x & a(i)
x=", "
Next
WScript.echo s &")"
End sub
Dim a,b
b="TOBEORNOTTOBEORTOBEORNOT"
WScript.Echo b
a=LZWCompress (b)
printvec(a)
WScript.echo lzwUncompress (a )
wscript.quit 1
| class LZW
{
function compress($unc) {
$i;$c;$wc;
$w = "";
$dictionary = array();
$result = array();
$dictSize = 256;
for ($i = 0; $i < 256; $i += 1) {
$dictionary[chr($i)] = $i;
}
for ($i = 0; $i < strlen($unc); $i++) {
$c = $unc[$i];
$wc = $w.$c;
if (array_key_exists($w.$c, $dictionary)) {
$w = $w.$c;
} else {
array_push($result,$dictionary[$w]);
$dictionary[$wc] = $dictSize++;
$w = (string)$c;
}
}
if ($w !== "") {
array_push($result,$dictionary[$w]);
}
return implode(",",$result);
}
function decompress($com) {
$com = explode(",",$com);
$i;$w;$k;$result;
$dictionary = array();
$entry = "";
$dictSize = 256;
for ($i = 0; $i < 256; $i++) {
$dictionary[$i] = chr($i);
}
$w = chr($com[0]);
$result = $w;
for ($i = 1; $i < count($com);$i++) {
$k = $com[$i];
if (isset($dictionary[$k])) {
$entry = $dictionary[$k];
} else {
if ($k === $dictSize) {
$entry = $w.$w[0];
} else {
return null;
}
}
$result .= $entry;
$dictionary[$dictSize++] = $w . $entry[0];
$w = $entry;
}
return $result;
}
}
$str = 'TOBEORNOTTOBEORTOBEORNOT';
$lzw = new LZW();
$com = $lzw->compress($str);
$dec = $lzw->decompress($com);
echo $com . "<br>" . $dec;
|
Generate a PHP translation of this VB snippet without changing its computational steps. | Sub Main()
Debug.Print F(-10)
Debug.Print F(10)
End Sub
Private Function F(N As Long) As Variant
If N < 0 Then
F = "Error. Negative argument"
ElseIf N <= 1 Then
F = N
Else
F = F(N - 1) + F(N - 2)
End If
End Function
| <?php
function fib($n) {
if ($n < 0)
throw new Exception('Negative numbers not allowed');
$f = function($n) { // This function must be called using call_user_func() only
if ($n < 2)
return 1;
else {
$g = debug_backtrace()[1]['args'][0];
return call_user_func($g, $n-1) + call_user_func($g, $n-2);
}
};
return call_user_func($f, $n);
}
echo fib(8), "\n";
?>
|
Change the programming language of this snippet from VB to PHP without modifying what it does. | string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2))
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1))
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
| <?php
echo substr("knight", 1), "\n"; // strip first character
echo substr("socks", 0, -1), "\n"; // strip last character
echo substr("brooms", 1, -1), "\n"; // strip both first and last characters
?>
|
Port the provided VB code into PHP while preserving the original functionality. | string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2))
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1))
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
| <?php
echo substr("knight", 1), "\n"; // strip first character
echo substr("socks", 0, -1), "\n"; // strip last character
echo substr("brooms", 1, -1), "\n"; // strip both first and last characters
?>
|
Write a version of this VB function in PHP with identical behavior. |
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\input.txt",1)
list = ""
previous_line = ""
l = Len(previous_line)
Do Until objfile.AtEndOfStream
current_line = objfile.ReadLine
If Mid(current_line,l+1,1) <> "" Then
list = current_line & vbCrLf
previous_line = current_line
l = Len(previous_line)
ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then
list = list & current_line & vbCrLf
End If
Loop
WScript.Echo list
objfile.Close
Set objfso = Nothing
| <?php
echo 'Enter strings (empty string to finish) :', PHP_EOL;
$output = $previous = readline();
while ($current = readline()) {
$p = $previous;
$c = $current;
while ($p and $c) {
$p = substr($p, 1);
$c = substr($c, 1);
}
if (!$p and !$c) {
$output .= PHP_EOL . $current;
}
if ($c) {
$output = $previous = $current;
}
}
echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
|
Produce a functionally identical PHP code for the snippet given in VB. | Public Sub create_file()
Dim FileNumber As Integer
FileNumber = FreeFile
MkDir "docs"
Open "docs\output.txt" For Output As #FreeFile
Close #FreeFile
MkDir "C:\docs"
Open "C:\docs\output.txt" For Output As #FreeFile
Close #FreeFile
End Sub
| <?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?>
|
Produce a functionally identical PHP code for the snippet given in VB. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
|
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up';
$input = 'riG rePEAT copies put mo rest types fup. 6 poweRin';
$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';
$table = makeCommandTable($commands);
$table_keys = array_keys($table);
$inputTable = processInput($input);
foreach ($inputTable as $word) {
$rs = searchCommandTable($word, $table);
if ($rs) {
$output[] = $rs;
} else {
$output[] = '*error*';
}
}
echo 'Input: '. $input. PHP_EOL;
echo 'Output: '. implode(' ', $output). PHP_EOL;
function searchCommandTable($search, $table) {
foreach ($table as $key => $value) {
if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {
return $key;
}
}
return false;
}
function processInput($input) {
$input = preg_replace('!\s+!', ' ', $input);
$pieces = explode(' ', trim($input));
return $pieces;
}
function makeCommandTable($commands) {
$commands = preg_replace('!\s+!', ' ', $commands);
$pieces = explode(' ', trim($commands));
foreach ($pieces as $word) {
$rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)];
}
return $rs;
}
|
Produce a functionally identical PHP code for the snippet given in VB. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
|
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up';
$input = 'riG rePEAT copies put mo rest types fup. 6 poweRin';
$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';
$table = makeCommandTable($commands);
$table_keys = array_keys($table);
$inputTable = processInput($input);
foreach ($inputTable as $word) {
$rs = searchCommandTable($word, $table);
if ($rs) {
$output[] = $rs;
} else {
$output[] = '*error*';
}
}
echo 'Input: '. $input. PHP_EOL;
echo 'Output: '. implode(' ', $output). PHP_EOL;
function searchCommandTable($search, $table) {
foreach ($table as $key => $value) {
if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {
return $key;
}
}
return false;
}
function processInput($input) {
$input = preg_replace('!\s+!', ' ', $input);
$pieces = explode(' ', trim($input));
return $pieces;
}
function makeCommandTable($commands) {
$commands = preg_replace('!\s+!', ' ', $commands);
$pieces = explode(' ', trim($commands));
foreach ($pieces as $word) {
$rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)];
}
return $rs;
}
|
Port the provided VB code into PHP while preserving the original functionality. | Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _
overlapped As Ptr) As Boolean
Declare Function GetLastError Lib "Kernel32" () As Integer
Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean
Const FILE_SHARE_READ = &h00000001
Const FILE_SHARE_WRITE = &h00000002
Const OPEN_EXISTING = 3
Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
If fHandle > 0 Then
Dim mb As MemoryBlock = "Hello, World!"
Dim bytesWritten As Integer
If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then
MsgBox("Error Number: " + Str(GetLastError))
End If
Call CloseHandle(fHandle)
Else
MsgBox("Error Number: " + Str(GetLastError))
End If
| $ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll");
$cstr = $ffi->_strdup("success");
$str = FFI::string($cstr);
echo $str;
FFI::free($cstr);
|
Rewrite this program in PHP while keeping its functionality equivalent to the VB version. | Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Keep all operations the same but rewrite the snippet in PHP. | Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Maintain the same structure and functionality when rewriting this code in PHP. | DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}
Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
| $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
|
Produce a language-to-language conversion: from VB to PHP, same semantics. | Public Sub text()
Debug.Print InputBox("Input a string")
Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
End Sub
| #!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);
|
Produce a language-to-language conversion: from VB to PHP, same semantics. |
Option Explicit
Const maxWeight = 400
Dim DataList As Variant
Dim xList(64, 3) As Variant
Dim nItems As Integer
Dim s As String, xss As String
Dim xwei As Integer, xval As Integer, nn As Integer
Sub Main()
Dim i As Integer, j As Integer
DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _
"glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _
"cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _
"T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _
"waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _
"note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50)
nItems = (UBound(DataList) + 1) / 3
j = 0
For i = 1 To nItems
xList(i, 1) = DataList(j)
xList(i, 2) = DataList(j + 1)
xList(i, 3) = DataList(j + 2)
j = j + 3
Next i
s = ""
For i = 1 To nItems
s = s & Chr(i)
Next
nn = 0
Call ChoiceBin(1, "")
For i = 1 To Len(xss)
j = Asc(Mid(xss, i, 1))
Debug.Print xList(j, 1)
Next i
Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval
End Sub
Private Sub ChoiceBin(n As String, ss As String)
Dim r As String
Dim i As Integer, j As Integer, iwei As Integer, ival As Integer
Dim ipct As Integer
If n = Len(s) + 1 Then
iwei = 0: ival = 0
For i = 1 To Len(ss)
j = Asc(Mid(ss, i, 1))
iwei = iwei + xList(j, 2)
ival = ival + xList(j, 3)
Next
If iwei <= maxWeight And ival > xval Then
xss = ss: xwei = iwei: xval = ival
End If
Else
r = Mid(s, n, 1)
Call ChoiceBin(n + 1, ss & r)
Call ChoiceBin(n + 1, ss)
End If
End Sub
| #########################################################
# 0-1 Knapsack Problem Solve with memoization optimize and index returns
# $w = weight of item
# $v = value of item
# $i = index
# $aW = Available Weight
# $m = Memo items array
# PHP Translation from Python, Memoization,
# and index return functionality added by Brian Berneker
#
#########################################################
function knapSolveFast2($w, $v, $i, $aW, &$m) {
global $numcalls;
$numcalls ++;
if (isset($m[$i][$aW])) {
return array( $m[$i][$aW], $m['picked'][$i][$aW] );
} else {
if ($i == 0) {
if ($w[$i] <= $aW) { // Will this item fit?
$m[$i][$aW] = $v[$i]; // Memo this item
$m['picked'][$i][$aW] = array($i); // and the picked item
return array($v[$i],array($i)); // Return the value of this item and add it to the picked list
} else {
$m[$i][$aW] = 0; // Memo zero
$m['picked'][$i][$aW] = array(); // and a blank array entry...
return array(0,array()); // Return nothing
}
}
list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);
if ($w[$i] > $aW) { // Does it return too many?
$m[$i][$aW] = $without_i; // Memo without including this one
$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...
return array($without_i, $without_PI); // and return it
} else {
list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);
$with_i += $v[$i]; // ..and add the value of this one..
if ($with_i > $without_i) {
$res = $with_i;
$picked = $with_PI;
array_push($picked,$i);
} else {
$res = $without_i;
$picked = $without_PI;
}
$m[$i][$aW] = $res; // Store it in the memo
$m['picked'][$i][$aW] = $picked; // and store the picked item
return array ($res,$picked); // and then return it
}
}
}
$items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book");
$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);
$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);
## Initialize
$numcalls = 0; $m = array(); $pickedItems = array();
## Solve
list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);
# Display Result
echo "<b>Items:</b><br>".join(", ",$items4)."<br>";
echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>";
echo "<b>Array Indices:</b><br>".join(",",$pickedItems)."<br>";
echo "<b>Chosen Items:</b><br>";
echo "<table border cellspacing=0>";
echo "<tr><td>Item</td><td>Value</td><td>Weight</td></tr>";
$totalVal = $totalWt = 0;
foreach($pickedItems as $key) {
$totalVal += $v4[$key];
$totalWt += $w4[$key];
echo "<tr><td>".$items4[$key]."</td><td>".$v4[$key]."</td><td>".$w4[$key]."</td></tr>";
}
echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>";
echo "</table><hr>";
|
Keep all operations the same but rewrite the snippet in PHP. | dim _proper_divisors(100)
sub proper_divisors(n)
dim i
dim _proper_divisors_count = 0
if n <> 1 then
for i = 1 to (n \ 2)
if n %% i = 0 then
_proper_divisors_count = _proper_divisors_count + 1
_proper_divisors(_proper_divisors_count) = i
end if
next
end if
return _proper_divisors_count
end sub
sub show_proper_divisors(n, tabbed)
dim cnt = proper_divisors(n)
print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) ";
dim j
for j = 1 to cnt
if tabbed then
print str$(_proper_divisors(j)),
else
print str$(_proper_divisors(j));
end if
if (j < cnt) then print ",";
next
print
end sub
dim i
for i = 1 to 10
show_proper_divisors(i, false)
next
dim c
dim maxindex = 0
dim maxlength = 0
for t = 1 to 20000
c = proper_divisors(t)
if c > maxlength then
maxindex = t
maxlength = c
end if
next
print "A maximum at ";
show_proper_divisors(maxindex, false)
| <?php
function ProperDivisors($n) {
yield 1;
$large_divisors = [];
for ($i = 2; $i <= sqrt($n); $i++) {
if ($n % $i == 0) {
yield $i;
if ($i*$i != $n) {
$large_divisors[] = $n / $i;
}
}
}
foreach (array_reverse($large_divisors) as $i) {
yield $i;
}
}
assert([1, 2, 4, 5, 10, 20, 25, 50] ==
iterator_to_array(ProperDivisors(100)));
foreach (range(1, 10) as $n) {
echo "$n =>";
foreach (ProperDivisors($n) as $divisor) {
echo " $divisor";
}
echo "\n";
}
$divisorsCount = [];
for ($i = 1; $i < 20000; $i++) {
$divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;
}
ksort($divisorsCount);
echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n";
echo "They have ", key($divisorsCount), " divisors.\n";
|
Transform the following VB implementation into PHP, maintaining the same output and logic. | text = "I need more coffee!!!"
Set regex = New RegExp
regex.Global = True
regex.Pattern = "\s"
If regex.Test(text) Then
WScript.StdOut.Write regex.Replace(text,vbCrLf)
Else
WScript.StdOut.Write "No matching pattern"
End If
| $string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
|
Rewrite the snippet below in PHP so it works the same as the original VB code. | Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
dict.Add os(n), owner(n)
Next
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")
| $keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);
|
Convert the following code from VB to PHP, ensuring the logic remains intact. | Function Encoder(ByVal n)
Encoder = n Xor (n \ 2)
End Function
Function Decoder(ByVal n)
Dim g : g = 0
Do While n > 0
g = g Xor n
n = n \ 2
Loop
Decoder = g
End Function
Function Dec2bin(ByVal n, ByVal length)
Dim i, strbin : strbin = ""
For i = 1 to 5
strbin = (n Mod 2) & strbin
n = n \ 2
Next
Dec2Bin = strbin
End Function
WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary")
For i = 0 to 31
encoded = Encoder(i)
decoded = Decoder(encoded)
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next
| <?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
Preserve the algorithm and functionality while converting the code from VB to PHP. | Function Encoder(ByVal n)
Encoder = n Xor (n \ 2)
End Function
Function Decoder(ByVal n)
Dim g : g = 0
Do While n > 0
g = g Xor n
n = n \ 2
Loop
Decoder = g
End Function
Function Dec2bin(ByVal n, ByVal length)
Dim i, strbin : strbin = ""
For i = 1 to 5
strbin = (n Mod 2) & strbin
n = n \ 2
Next
Dec2Bin = strbin
End Function
WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary")
For i = 0 to 31
encoded = Encoder(i)
decoded = Decoder(encoded)
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next
| <?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
Generate a PHP translation of this VB snippet without changing its computational steps. | suite$ = "CDHS" #Club, Diamond, Heart, Spade
card$ = "A23456789TJQK" #Cards Ace to King
card = 0
dim n(55) #make ordered deck
for i = 1 to 52 # of 52 cards
n[i] = i
next i
for i = 1 to 52 * 3 #shuffle deck 3 times
i1 = int(rand * 52) + 1
i2 = int(rand * 52) + 1
h2 = n[i1]
n[i1] = n[i2]
n[i2] = h2
next i
for hand = 1 to 4 #4 hands
for deal = 1 to 13 #deal each 13 cards
card += 1 #next card in deck
s = (n[card] mod 4) + 1 #determine suite
c = (n[card] mod 13) + 1 #determine card
print mid(card$,c,1);mid(suite$,s,1);" "; #show the card
next deal
print
next hand
end
function word$(sr$, wn, delim$)
j = wn
if j = 0 then j += 1
res$ = "" : s$ = sr$ : d$ = delim$
if d$ = "" then d$ = " "
sd = length(d$) : sl = length(s$)
while true
n = instr(s$,d$) : j -= 1
if j = 0 then
if n=0 then res$=s$ else res$=mid(s$,1,n-1)
return res$
end if
if n = 0 then return res$
if n = sl - sd then res$ = "" : return res$
sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2
end while
return res$
end function
| class Card
{
protected static $suits = array( '♠', '♥', '♦', '♣' );
protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );
protected $suit;
protected $suitOrder;
protected $pip;
protected $pipOrder;
protected $order;
public function __construct( $suit, $pip )
{
if( !in_array( $suit, self::$suits ) )
{
throw new InvalidArgumentException( 'Invalid suit' );
}
if( !in_array( $pip, self::$pips ) )
{
throw new InvalidArgumentException( 'Invalid pip' );
}
$this->suit = $suit;
$this->pip = $pip;
}
public function getSuit()
{
return $this->suit;
}
public function getPip()
{
return $this->pip;
}
public function getSuitOrder()
{
if( !isset( $this->suitOrder ) )
{
$this->suitOrder = array_search( $this->suit, self::$suits );
}
return $this->suitOrder;
}
public function getPipOrder()
{
if( !isset( $this->pipOrder ) )
{
$this->pipOrder = array_search( $this->pip, self::$pips );
}
return $this->pipOrder;
}
public function getOrder()
{
if( !isset( $this->order ) )
{
$suitOrder = $this->getSuitOrder();
$pipOrder = $this->getPipOrder();
$this->order = $pipOrder * count( self::$suits ) + $suitOrder;
}
return $this->order;
}
public function compareSuit( Card $other )
{
return $this->getSuitOrder() - $other->getSuitOrder();
}
public function comparePip( Card $other )
{
return $this->getPipOrder() - $other->getPipOrder();
}
public function compare( Card $other )
{
return $this->getOrder() - $other->getOrder();
}
public function __toString()
{
return $this->suit . $this->pip;
}
public static function getSuits()
{
return self::$suits;
}
public static function getPips()
{
return self::$pips;
}
}
class CardCollection
implements Countable, Iterator
{
protected $cards = array();
protected function __construct( array $cards = array() )
{
foreach( $cards as $card )
{
$this->addCard( $card );
}
}
public function count()
{
return count( $this->cards );
}
public function key()
{
return key( $this->cards );
}
public function valid()
{
return null !== $this->key();
}
public function next()
{
next( $this->cards );
}
public function current()
{
return current( $this->cards );
}
public function rewind()
{
reset( $this->cards );
}
public function sort( $comparer = null )
{
$comparer = $comparer ?: function( $a, $b ) {
return $a->compare( $b );
};
if( !is_callable( $comparer ) )
{
throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );
}
usort( $this->cards, $comparer );
return $this;
}
public function toString()
{
return implode( ' ', $this->cards );
}
public function __toString()
{
return $this->toString();
}
protected function addCard( Card $card )
{
if( in_array( $card, $this->cards ) )
{
throw new DomainException( 'Card is already present in this collection' );
}
$this->cards[] = $card;
}
}
class Deck
extends CardCollection
{
public function __construct( $shuffled = false )
{
foreach( Card::getSuits() as $suit )
{
foreach( Card::getPips() as $pip )
{
$this->addCard( new Card( $suit, $pip ) );
}
}
if( $shuffled )
{
$this->shuffle();
}
}
public function deal( $amount = 1, CardCollection $cardCollection = null )
{
if( !is_int( $amount ) || $amount < 1 )
{
throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );
}
if( $amount > count( $this->cards ) )
{
throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );
}
$cards = array_splice( $this->cards, 0, $amount );
$cardCollection = $cardCollection ?: new CardCollection;
foreach( $cards as $card )
{
$cardCollection->addCard( $card );
}
return $cardCollection;
}
public function shuffle()
{
shuffle( $this->cards );
}
}
class Hand
extends CardCollection
{
public function __construct() {}
public function play( $position )
{
if( !isset( $this->cards[ $position ] ) )
{
throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );
}
$result = array_splice( $this->cards, $position, 1 );
return $result[ 0 ];
}
}
|
Write a version of this VB function in PHP with identical behavior. | Option Base {0|1}
| $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];
|
Translate the given VB code snippet into PHP without altering its behavior. | Const Order = 4
Function InCarpet(ByVal x As Integer, ByVal y As Integer)
Do While x <> 0 And y <> 0
If x Mod 3 = 1 And y Mod 3 = 1 Then
InCarpet = " "
Exit Function
End If
x = x \ 3
y = y \ 3
Loop
InCarpet = "#"
End Function
Public Sub sierpinski_carpet()
Dim i As Integer, j As Integer
For i = 0 To 3 ^ Order - 1
For j = 0 To 3 ^ Order - 1
Debug.Print InCarpet(i, j);
Next j
Debug.Print
Next i
End Sub
| <?php
function isSierpinskiCarpetPixelFilled($x, $y) {
while (($x > 0) or ($y > 0)) {
if (($x % 3 == 1) and ($y % 3 == 1)) {
return false;
}
$x /= 3;
$y /= 3;
}
return true;
}
function sierpinskiCarpet($order) {
$size = pow(3, $order);
for ($y = 0 ; $y < $size ; $y++) {
for ($x = 0 ; $x < $size ; $x++) {
echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
}
echo PHP_EOL;
}
}
for ($order = 0 ; $order <= 3 ; $order++) {
echo 'N=', $order, PHP_EOL;
sierpinskiCarpet($order);
echo PHP_EOL;
}
|
Translate the given VB code snippet into PHP without altering its behavior. | Private Function Knuth(a As Variant) As Variant
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
For i = UBound(a) To LBound(a) + 1 Step -1
j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
End If
Knuth = a
End Function
Private Function inOrder(s As Variant)
i = 2
Do While i <= UBound(s)
If s(i) < s(i - 1) Then
inOrder = False
Exit Function
End If
i = i + 1
Loop
inOrder = True
End Function
Private Function bogosort(ByVal s As Variant) As Variant
Do While Not inOrder(s)
Debug.Print Join(s, ", ")
s = Knuth(s)
Loop
bogosort = s
End Function
Public Sub main()
Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ")
End Sub
| function bogosort($l) {
while (!in_order($l))
shuffle($l);
return $l;
}
function in_order($l) {
for ($i = 1; $i < count($l); $i++)
if ($l[$i] < $l[$i-1])
return FALSE;
return TRUE;
}
|
Write a version of this VB function in PHP with identical behavior. | Sub Main()
Dim i&, c&, j#, s$
Const N& = 1000000
s = "values for n in the range 1 to 22 : "
For i = 1 To 22
s = s & ns(i) & ", "
Next
For i = 1 To N
j = Sqr(ns(i))
If j = CInt(j) Then c = c + 1
Next
Debug.Print s
Debug.Print c & " squares less than " & N
End Sub
Private Function ns(l As Long) As Long
ns = l + Int(1 / 2 + Sqr(l))
End Function
| <?php
for($i=1;$i<=22;$i++){
echo($i + floor(1/2 + sqrt($i)) . "\n");
}
$found_square=False;
for($i=1;$i<=1000000;$i++){
$non_square=$i + floor(1/2 + sqrt($i));
if(sqrt($non_square)==intval(sqrt($non_square))){
$found_square=True;
}
}
echo("\n");
if($found_square){
echo("Found a square number, so the formula does not always work.");
} else {
echo("Up to 1000000, found no square number in the sequence!");
}
?>
|
Convert this VB snippet to PHP and keep its semantics consistent. | Public Sub substring()
sentence = "the last thing the man said was the"
n = 10: m = 5
Debug.Print Mid(sentence, n, 5)
Debug.Print Right(sentence, Len(sentence) - n + 1)
Debug.Print Left(sentence, Len(sentence) - 1)
k = InStr(1, sentence, "m")
Debug.Print Mid(sentence, k, 5)
k = InStr(1, sentence, "aid")
Debug.Print Mid(sentence, k, 5)
End Sub
| <?php
$str = 'abcdefgh';
$n = 2;
$m = 3;
echo substr($str, $n, $m), "\n"; //cde
echo substr($str, $n), "\n"; //cdefgh
echo substr($str, 0, -1), "\n"; //abcdefg
echo substr($str, strpos($str, 'd'), $m), "\n"; //def
echo substr($str, strpos($str, 'de'), $m), "\n"; //def
?>
|
Change the programming language of this snippet from VB to PHP without modifying what it does. | Public Function Leap_year(year As Integer) As Boolean
Leap_year = (Month(DateSerial(year, 2, 29)) = 2)
End Function
| <?php
function isLeapYear($year) {
if ($year % 100 == 0) {
return ($year % 400 == 0);
}
return ($year % 4 == 0);
}
|
Generate an equivalent PHP version of this VB code. | Public twenties As Variant
Public decades As Variant
Public orders As Variant
Private Sub init()
twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}]
decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}]
orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}]
End Sub
Private Function Twenty(N As Variant)
Twenty = twenties(N Mod 20 + 1)
End Function
Private Function Decade(N As Variant)
Decade = decades(N Mod 10 - 1)
End Function
Private Function Hundred(N As Variant)
If N < 20 Then
Hundred = Twenty(N)
Exit Function
Else
If N Mod 10 = 0 Then
Hundred = Decade((N \ 10) Mod 10)
Exit Function
End If
End If
Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10)
End Function
Private Function Thousand(N As Variant, withand As String)
If N < 100 Then
Thousand = withand & Hundred(N)
Exit Function
Else
If N Mod 100 = 0 Then
Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred"
Exit Function
End If
End If
Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100)
End Function
Private Function Triplet(N As Variant)
Dim Order, High As Variant, Low As Variant
Dim Name As String, res As String
For i = 1 To UBound(orders)
Order = orders(i, 1)
Name = orders(i, 2)
High = WorksheetFunction.Floor_Precise(N / Order)
Low = N - High * Order
If High <> 0 Then
res = res & Thousand(High, "") & " " & Name
End If
N = Low
If Low = 0 Then Exit For
If Len(res) And High <> 0 Then
res = res & ", "
End If
Next i
If N <> 0 Or res = "" Then
res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and "))
N = N - Int(N)
If N > 0.000001 Then
res = res & " point"
For i = 1 To 10
n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)
res = res & " " & twenties(n_ + 1)
N = N * 10 - n_
If Abs(N) < 0.000001 Then Exit For
Next i
End If
End If
Triplet = res
End Function
Private Function spell(N As Variant)
Dim res As String
If N < 0 Then
res = "minus "
N = -N
End If
res = res & Triplet(N)
spell = res
End Function
Private Function smartp(N As Variant)
Dim res As String
If N = WorksheetFunction.Floor_Precise(N) Then
smartp = CStr(N)
Exit Function
End If
res = CStr(N)
If InStr(1, res, ".") Then
res = Left(res, InStr(1, res, "."))
End If
smartp = res
End Function
Sub Main()
Dim si As Variant
init
Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]
Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]
For i = 1 To UBound(Samples1)
si = Samples1(i)
Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
Next i
For i = 1 To UBound(Samples2)
si = Samples2(i)
Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
Next i
End Sub
| $orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');
$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
function NumberToEnglish($num, $count = 0){
global $orderOfMag, $smallNumbers, $decades;
$isLast = true;
$str = '';
if ($num < 0){
$str = 'Negative ';
$num = abs($num);
}
(int) $thisPart = substr((string) $num, -3);
if (strlen((string) $num) > 3){
$str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);
$isLast = false;
}
if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))
$and = '';
else
$and = ' and ';
if ($thisPart > 99){
$str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}";
if(($thisPart %= 100) == 0){
$str .= " {$orderOfMag[$count]}";
return $str;
}
$and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk
}
if ($thisPart >= 20){
$str .= "{$and}{$decades[$thisPart /10]}";
$and = ' '; // Make sure we don't have any extranious "and"s
if(($thisPart %= 10) == 0)
return $str . ($count != 0 ? " {$orderOfMag[$count]}" : '');
}
if ($thisPart < 20 && $thisPart > 0)
return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : '');
elseif ($thisPart == 0 && strlen($thisPart) == 1)
return $str . "{$smallNumbers[(int)$thisPart]}";
}
|
Transform the following VB implementation into PHP, maintaining the same output and logic. | Sub arrShellSort(ByVal arrData As Variant)
Dim lngHold, lngGap As Long
Dim lngCount, lngMin, lngMax As Long
Dim varItem As Variant
lngMin = LBound(arrData)
lngMax = UBound(arrData)
lngGap = lngMin
Do While (lngGap < lngMax)
lngGap = 3 * lngGap + 1
Loop
Do While (lngGap > 1)
lngGap = lngGap \ 3
For lngCount = lngGap + lngMin To lngMax
varItem = arrData(lngCount)
lngHold = lngCount
Do While ((arrData(lngHold - lngGap) > varItem))
arrData(lngHold) = arrData(lngHold - lngGap)
lngHold = lngHold - lngGap
If (lngHold < lngMin + lngGap) Then Exit Do
Loop
arrData(lngHold) = varItem
Next
Loop
arrShellSort = arrData
End Sub
| function shellSort($arr)
{
$inc = round(count($arr)/2);
while($inc > 0)
{
for($i = $inc; $i < count($arr);$i++){
$temp = $arr[$i];
$j = $i;
while($j >= $inc && $arr[$j-$inc] > $temp)
{
$arr[$j] = $arr[$j - $inc];
$j -= $inc;
}
$arr[$j] = $temp;
}
$inc = round($inc/2.2);
}
return $arr;
}
|
Produce a language-to-language conversion: from VB to PHP, same semantics. |
TYPE regChar
Character AS STRING * 3
Count AS LONG
END TYPE
DIM iChar AS INTEGER
DIM iCL AS INTEGER
DIM iCountChars AS INTEGER
DIM iFile AS INTEGER
DIM i AS INTEGER
DIM lMUC AS LONG
DIM iMUI AS INTEGER
DIM lLUC AS LONG
DIM iLUI AS INTEGER
DIM iMaxIdx AS INTEGER
DIM iP AS INTEGER
DIM iPause AS INTEGER
DIM iPMI AS INTEGER
DIM iPrint AS INTEGER
DIM lHowMany AS LONG
DIM lTotChars AS LONG
DIM sTime AS SINGLE
DIM strFile AS STRING
DIM strTxt AS STRING
DIM strDate AS STRING
DIM strTime AS STRING
DIM strKey AS STRING
CONST LngReg = 256
CONST Letters = 1
CONST FALSE = 0
CONST TRUE = NOT FALSE
strDate = DATE$
strTime = TIME$
iFile = FREEFILE
DO
CLS
PRINT "This program counts letters or characters in a text file."
PRINT
INPUT "File to open: ", strFile
OPEN strFile FOR BINARY AS #iFile
IF LOF(iFile) > 0 THEN
PRINT "Count: 1) Letters 2) Characters (1 or 2)";
DO
strKey = INKEY$
LOOP UNTIL strKey = "1" OR strKey = "2"
PRINT ". Option selected: "; strKey
iCL = VAL(strKey)
sTime = TIMER
iP = POS(0)
lHowMany = LOF(iFile)
strTxt = SPACE$(LngReg)
IF iCL = Letters THEN
iMaxIdx = 26
ELSE
iMaxIdx = 255
END IF
IF iMaxIdx <> iPMI THEN
iPMI = iMaxIdx
REDIM rChar(0 TO iMaxIdx) AS regChar
FOR i = 0 TO iMaxIdx
IF iCL = Letters THEN
strTxt = CHR$(i + 65)
IF i = 26 THEN strTxt = CHR$(165)
ELSE
SELECT CASE i
CASE 0: strTxt = "nul"
CASE 7: strTxt = "bel"
CASE 9: strTxt = "tab"
CASE 10: strTxt = "lf"
CASE 11: strTxt = "vt"
CASE 12: strTxt = "ff"
CASE 13: strTxt = "cr"
CASE 28: strTxt = "fs"
CASE 29: strTxt = "gs"
CASE 30: strTxt = "rs"
CASE 31: strTxt = "us"
CASE 32: strTxt = "sp"
CASE ELSE: strTxt = CHR$(i)
END SELECT
END IF
rChar(i).Character = strTxt
NEXT i
ELSE
FOR i = 0 TO iMaxIdx
rChar(i).Count = 0
NEXT i
END IF
PRINT "Looking for ";
IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters.";
PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7)
DO WHILE LOC(iFile) < LOF(iFile)
IF LOC(iFile) + LngReg > LOF(iFile) THEN
strTxt = SPACE$(LOF(iFile) - LOC(iFile))
END IF
GET #iFile, , strTxt
FOR i = 1 TO LEN(strTxt)
IF iCL = Letters THEN
iChar = ASC(UCASE$(MID$(strTxt, i, 1)))
SELECT CASE iChar
CASE 164: iChar = 165
CASE 160: iChar = 65
CASE 130, 144: iChar = 69
CASE 161: iChar = 73
CASE 162: iChar = 79
CASE 163, 129: iChar = 85
END SELECT
iChar = iChar - 65
IF iChar >= 0 AND iChar <= 25 THEN
rChar(iChar).Count = rChar(iChar).Count + 1
ELSEIF iChar = 100 THEN
rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1
END IF
ELSE
iChar = ASC(MID$(strTxt, i, 1))
rChar(iChar).Count = rChar(iChar).Count + 1
END IF
NEXT i
LOOP
CLOSE #iFile
lMUC = 0
iMUI = 0
lLUC = 2147483647
iLUI = 0
iPrint = FALSE
lTotChars = 0
iCountChars = 0
iPause = FALSE
CLS
IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: ";
FOR i = 0 TO iMaxIdx
IF lMUC < rChar(i).Count THEN
lMUC = rChar(i).Count
iMUI = i
END IF
IF rChar(i).Count > 0 THEN
strTxt = ""
IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE
strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))
strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count))
iP = POS(0)
IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN
PRINT ","
IF CSRLIN >= 23 AND NOT iPause THEN
iPause = TRUE
PRINT "Press a key to continue..."
DO
strKey = INKEY$
LOOP UNTIL strKey <> ""
END IF
strTxt = MID$(strTxt, 3)
END IF
PRINT strTxt;
lTotChars = lTotChars + rChar(i).Count
iCountChars = iCountChars + 1
IF lLUC > rChar(i).Count THEN
lLUC = rChar(i).Count
iLUI = i
END IF
END IF
NEXT i
PRINT "."
PRINT
PRINT "File analyzed....................: "; strFile
PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters"
PRINT "Total characters in file.........:"; lHowMany
PRINT "Total characters counted.........:"; lTotChars
IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars
PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1
PRINT "Most used character was..........: ";
iPrint = FALSE
FOR i = 0 TO iMaxIdx
IF rChar(i).Count = lMUC THEN
IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE
PRINT RTRIM$(LTRIM$(rChar(i).Character));
END IF
NEXT i
PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)"
PRINT "Least used character was.........: ";
iPrint = FALSE
FOR i = 0 TO iMaxIdx
IF rChar(i).Count = lLUC THEN
IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE
PRINT RTRIM$(LTRIM$(rChar(i).Character));
END IF
NEXT i
PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)"
PRINT "Time spent in the process........:"; TIMER - sTime; "seconds"
ELSE
CLOSE #iFile
KILL strFile
PRINT
PRINT "File does not exist."
END IF
PRINT
PRINT "Again? (Y/n)"
DO
strTxt = UCASE$(INKEY$)
LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27)
LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27)
CLS
PRINT "End of execution."
PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "."
END
| <?php
print_r(array_count_values(str_split(file_get_contents($argv[1]))));
?>
|
Change the programming language of this snippet from VB to PHP without modifying what it does. | Dim s As String = "123"
s = CStr(CInt("123") + 1)
s = (CInt("123") + 1).ToString
| $s = "12345";
$s++;
|
Rewrite the snippet below in PHP so it works the same as the original VB code. | Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)
Dim i As Integer, stReplace As String
If bSpace = True Then
stReplace = " "
Else
stReplace = ""
End If
For i = 1 To Len(stStripChars)
stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)
Next i
StripChars = stString
End Function
| <?php
function stripchars($s, $chars) {
return str_replace(str_split($chars), "", $s);
}
echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
?>
|
Write the same code in PHP as shown below in VB. | Private Function mean(v() As Double, ByVal leng As Integer) As Variant
Dim sum As Double, i As Integer
sum = 0: i = 0
For i = 0 To leng - 1
sum = sum + vv
Next i
If leng = 0 Then
mean = CVErr(xlErrDiv0)
Else
mean = sum / leng
End If
End Function
Public Sub main()
Dim v(4) As Double
Dim i As Integer, leng As Integer
v(0) = 1#
v(1) = 2#
v(2) = 2.178
v(3) = 3#
v(4) = 3.142
For leng = 5 To 0 Step -1
Debug.Print "mean[";
For i = 0 To leng - 1
Debug.Print IIf(i, "; " & v(i), "" & v(i));
Next i
Debug.Print "] = "; mean(v, leng)
Next leng
End Sub
| $nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";
|
Please provide an equivalent version of this VB code in PHP. | Module ForwardDifference
Sub Main()
Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})
For i As UInteger = 0 To 9
Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray()))
Next
Console.ReadKey()
End Sub
Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)
If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers")
For i As Integer = 1 To Level
Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _
Select Numbers(n + 1) - Numbers(n)).ToList()
Next
Return Numbers
End Function
End Module
| <?php
function forwardDiff($anArray, $times = 1) {
if ($times <= 0) { return $anArray; }
for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) {
$accumilation[] = $anArray[$i] - $anArray[$i - 1];
}
if ($times === 1) { return $accumilation; }
return forwardDiff($accumilation, $times - 1);
}
class ForwardDiffExample extends PweExample {
function _should_run_empty_array_for_single_elem() {
$expected = array($this->rand()->int());
$this->spec(forwardDiff($expected))->shouldEqual(array());
}
function _should_give_diff_of_two_elem_as_single_elem() {
$twoNums = array($this->rand()->int(), $this->rand()->int());
$expected = array($twoNums[1] - $twoNums[0]);
$this->spec(forwardDiff($twoNums))->shouldEqual($expected);
}
function _should_compute_correct_forward_diff_for_longer_arrays() {
$diffInput = array(10, 2, 9, 6, 5);
$expected = array(-8, 7, -3, -1);
$this->spec(forwardDiff($diffInput))->shouldEqual($expected);
}
function _should_apply_more_than_once_if_specified() {
$diffInput = array(4, 6, 9, 3, 4);
$expectedAfter1 = array(2, 3, -6, 1);
$expectedAfter2 = array(1, -9, 7);
$this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);
$this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);
}
function _should_return_array_unaltered_if_no_times() {
$this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);
}
}
|
Convert this VB block to PHP, preserving its control flow and logic. | Option Explicit
Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
Do
i = i + 1
If IsPrime(i) Then
t(count) = i
count = count + 1
End If
Loop While count <= UBound(t)
Debug.Print Join(t, ", ")
End Sub
Function IsPrime(Nb As Long) As Boolean
If Nb = 2 Then
IsPrime = True
ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
Exit Function
Else
Dim i As Long
For i = 3 To Sqr(Nb) Step 2
If Nb Mod i = 0 Then Exit Function
Next
IsPrime = True
End If
End Function
| <?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
return false;
$limit = sqrt($a);
for ($i = 2; $i <= $limit; $i++)
if ($a % $i == 0)
return false;
return true;
}
foreach (range(1, 100) as $x)
if (prime($x)) echo "$x\n";
?>
|
Translate the given VB code snippet into PHP without altering its behavior. | Function binomial(n,k)
binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function
Function factorial(n)
If n = 0 Then
factorial = 1
Else
For i = n To 1 Step -1
If i = n Then
factorial = n
Else
factorial = factorial * i
End If
Next
End If
End Function
WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3)
WScript.StdOut.WriteLine
| <?php
$n=5;
$k=3;
function factorial($val){
for($f=2;$val-1>1;$f*=$val--);
return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>
|
Translate the given VB code snippet into PHP without altering its behavior. | Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Can you help me rewrite this code in C# instead of Java, keeping it the same logically? | module BitwiseOps
{
@Inject Console console;
void run()
{
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])
{
static String hex(Int64 n)
{
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}
| static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Console.WriteLine("a or b is {0}", a | b);
Console.WriteLine("a xor b is {0}", a ^ b);
Console.WriteLine("not a is {0}", ~a);
Console.WriteLine("a lshift b is {0}", a << b);
Console.WriteLine("a arshift b is {0}", a >> b);
uint c = (uint)a;
Console.WriteLine("c rshift b is {0}", c >> b);
}
|
Produce a language-to-language conversion: from Java to C#, same semantics. | import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
import javax.swing.JFrame;
public class DragonCurve extends JFrame {
private List<Integer> turns;
private double startingAngle, side;
public DragonCurve(int iter) {
super("Dragon Curve");
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
turns = getSequence(iter);
startingAngle = -iter * (Math.PI / 4);
side = 400 / Math.pow(2, iter / 2.);
}
public List<Integer> getSequence(int iterations) {
List<Integer> turnSequence = new ArrayList<Integer>();
for (int i = 0; i < iterations; i++) {
List<Integer> copy = new ArrayList<Integer>(turnSequence);
Collections.reverse(copy);
turnSequence.add(1);
for (Integer turn : copy) {
turnSequence.add(-turn);
}
}
return turnSequence;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
double angle = startingAngle;
int x1 = 230, y1 = 350;
int x2 = x1 + (int) (Math.cos(angle) * side);
int y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
for (Integer turn : turns) {
angle += turn * (Math.PI / 2);
x2 = x1 + (int) (Math.cos(angle) * side);
y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
}
public static void main(String[] args) {
new DragonCurve(14).setVisible(true);
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class DragonCurve : Form
{
private List<int> turns;
private double startingAngle, side;
public DragonCurve(int iter)
{
Size = new Size(800, 600);
StartPosition = FormStartPosition.CenterScreen;
DoubleBuffered = true;
BackColor = Color.White;
startingAngle = -iter * (Math.PI / 4);
side = 400 / Math.Pow(2, iter / 2.0);
turns = getSequence(iter);
}
private List<int> getSequence(int iter)
{
var turnSequence = new List<int>();
for (int i = 0; i < iter; i++)
{
var copy = new List<int>(turnSequence);
copy.Reverse();
turnSequence.Add(1);
foreach (int turn in copy)
{
turnSequence.Add(-turn);
}
}
return turnSequence;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
double angle = startingAngle;
int x1 = 230, y1 = 350;
int x2 = x1 + (int)(Math.Cos(angle) * side);
int y2 = y1 + (int)(Math.Sin(angle) * side);
e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
x1 = x2;
y1 = y2;
foreach (int turn in turns)
{
angle += turn * (Math.PI / 2);
x2 = x1 + (int)(Math.Cos(angle) * side);
y2 = y1 + (int)(Math.Sin(angle) * side);
e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
}
[STAThread]
static void Main()
{
Application.Run(new DragonCurve(14));
}
}
|
Write the same code in C# as shown below in Java. | import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
}
public static void main(String[] args) {
for (String filename : args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
processLine(++lineNo, line);
}
}
catch (Exception x) {
x.printStackTrace();
}
finally {
if (fr != null) {
try {br.close();} catch (Exception ignoreMe) {}
try {fr.close();} catch (Exception ignoreMe) {}
}
}
}
}
}
| foreach (string readLine in File.ReadLines("FileName"))
DoSomething(readLine);
|
Maintain the same structure and functionality when rewriting this code in C#. | import java.util.LinkedList;
@SuppressWarnings("serial")
public class DoublyLinkedListInsertion<T> extends LinkedList<T> {
public static void main(String[] args) {
DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();
list.addFirst("Add First 1");
list.addFirst("Add First 2");
list.addFirst("Add First 3");
list.addFirst("Add First 4");
list.addFirst("Add First 5");
traverseList(list);
list.addAfter("Add First 3", "Add New");
traverseList(list);
}
public void addAfter(T after, T element) {
int index = indexOf(after);
if ( index >= 0 ) {
add(index + 1, element);
}
else {
addLast(element);
}
}
private static void traverseList(LinkedList<String> list) {
System.out.println("Traverse List:");
for ( int i = 0 ; i < list.size() ; i++ ) {
System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
}
System.out.println();
}
}
| static void InsertAfter(Link prev, int i)
{
if (prev.next != null)
{
prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };
prev.next = prev.next.prev;
}
else
prev.next = new Link() { item = i, prev = prev };
}
|
Convert this Java block to C#, preserving its control flow and logic. | import java.util.Random;
public class QuickSelect {
private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
E pivotVal = arr[pivot];
swap(arr, pivot, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i].compareTo(pivotVal) < 0) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, right, storeIndex);
return storeIndex;
}
private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (right >= left) {
int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
if (pivotIndex == n) {
return arr[pivotIndex];
} else if (pivotIndex < n) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return null;
}
private static void swap(Object[] arr, int i1, int i2) {
if (i1 != i2) {
Object temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
System.out.print(select(input, i));
if (i < 9) System.out.print(", ");
}
System.out.println();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuickSelect
{
internal static class Program
{
#region Static Members
private static void Main()
{
var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
Console.WriteLine( "Loop quick select 10 times." );
for( var i = 0 ; i < 10 ; i++ )
{
Console.Write( inputArray.NthSmallestElement( i ) );
if( i < 9 )
Console.Write( ", " );
}
Console.WriteLine();
Console.WriteLine( "Just sort 10 elements." );
Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
Console.WriteLine( "Get 4 smallest and sort them." );
Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
Console.WriteLine( "< Press any key >" );
Console.ReadKey();
}
#endregion
}
internal static class ArrayExtension
{
#region Static Members
public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>
{
if( count < 0 )
throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." );
if( count == 0 )
return new T[0];
if( array.Length <= count )
return array;
return QuickSelectSmallest( array, count - 1 ).Take( count );
}
public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>
{
if( n < 0 || n > array.Length - 1 )
throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) );
if( array.Length == 0 )
throw new ArgumentException( "Array is empty.", "array" );
if( array.Length == 1 )
return array[ 0 ];
return QuickSelectSmallest( array, n )[ n ];
}
private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>
{
var partiallySortedArray = (T[]) input.Clone();
var startIndex = 0;
var endIndex = input.Length - 1;
var pivotIndex = n;
var r = new Random();
while( endIndex > startIndex )
{
pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );
if( pivotIndex == n )
break;
if( pivotIndex > n )
endIndex = pivotIndex - 1;
else
startIndex = pivotIndex + 1;
pivotIndex = r.Next( startIndex, endIndex );
}
return partiallySortedArray;
}
private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>
{
var pivotValue = array[ pivotIndex ];
array.Swap( pivotIndex, endIndex );
for( var i = startIndex ; i < endIndex ; i++ )
{
if( array[ i ].CompareTo( pivotValue ) > 0 )
continue;
array.Swap( i, startIndex );
startIndex++;
}
array.Swap( endIndex, startIndex );
return startIndex;
}
private static void Swap<T>( this T[] array, int index1, int index2 )
{
if( index1 == index2 )
return;
var temp = array[ index1 ];
array[ index1 ] = array[ index2 ];
array[ index2 ] = temp;
}
#endregion
}
}
|
Port the provided Java code into C# while preserving the original functionality. | public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase);
}
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);
}
| public static class BaseConverter {
public static long stringToLong(string s, int b) {
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
checked {
int slen = s.Length;
long result = 0;
bool isNegative = false;
for ( int i = 0; i < slen; i++ ) {
char c = s[i];
int num;
if ( c == '-' ) {
if ( i != 0 )
throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s");
isNegative = true;
continue;
}
if ( c > 0x2F && c < 0x3A )
num = c - 0x30;
else if ( c > 0x40 && c < 0x5B )
num = c - 0x37;
else if ( c > 0x60 && c < 0x7B )
num = c - 0x57;
else
throw new ArgumentException("The string contains an invalid character '" + c + "'", "s");
if ( num >= b )
throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s");
result *= b;
result += num;
}
if ( isNegative )
result = -result;
return result;
}
}
public static string longToString(long n, int b) {
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
if ( b == 10 )
return n.ToString();
checked {
long longBase = b;
StringBuilder sb = new StringBuilder();
if ( n < 0 ) {
n = -n;
sb.Append('-');
}
long div = 1;
while ( n / div >= b )
div *= b;
while ( true ) {
byte digit = (byte) (n / div);
if ( digit < 10 )
sb.Append((char) (digit + 0x30));
else
sb.Append((char) (digit + 0x57));
if ( div == 1 )
break;
n %= div;
div /= b;
}
return sb.ToString();
}
}
}
|
Generate a C# translation of this Java snippet without changing its computational steps. | import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Port the following code from Java to C# with equivalent syntax and logic. | import java.util.zip.* ;
public class CRCMaker {
public static void main( String[ ] args ) {
String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
CRC32 myCRC = new CRC32( ) ;
myCRC.update( toBeEncoded.getBytes( ) ) ;
System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ;
}
}
|
public class Crc32
{
#region Constants
private const UInt32 s_generator = 0xEDB88320;
#endregion
#region Constructors
public Crc32()
{
m_checksumTable = Enumerable.Range(0, 256).Select(i =>
{
var tableEntry = (uint)i;
for (var j = 0; j < 8; ++j)
{
tableEntry = ((tableEntry & 1) != 0)
? (s_generator ^ (tableEntry >> 1))
: (tableEntry >> 1);
}
return tableEntry;
}).ToArray();
}
#endregion
#region Methods
public UInt32 Get<T>(IEnumerable<T> byteStream)
{
try
{
return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) =>
(m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));
}
catch (FormatException e)
{
throw new CrcException("Could not read the stream out as bytes.", e);
}
catch (InvalidCastException e)
{
throw new CrcException("Could not read the stream out as bytes.", e);
}
catch (OverflowException e)
{
throw new CrcException("Could not read the stream out as bytes.", e);
}
}
#endregion
#region Fields
private readonly UInt32[] m_checksumTable;
#endregion
}
|
Change the following Java code into C# without altering its purpose. | public class MyClass{
private int variable;
public MyClass(){
}
public void someMethod(){
this.variable = 1;
}
}
| public class MyClass
{
public MyClass()
{
}
public void SomeMethod()
{
}
private int _variable;
public int Variable
{
get { return _variable; }
set { _variable = value; }
}
public static void Main()
{
MyClass instance = new MyClass();
instance.SomeMethod();
instance.Variable = 99;
System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
}
}
|
Write a version of this Java function in C# with identical behavior. | public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
| using System;
using System.Collections.Generic;
public class KaprekarNumbers {
public static void Main() {
int count = 0;
foreach ( ulong i in _kaprekarGenerator(999999) ) {
Console.WriteLine(i);
count++;
}
Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
}
private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {
ulong next = 1;
yield return next;
for ( next = 2; next <= max; next++ ) {
ulong square = next * next;
for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
if ( square <= check )
break;
ulong r = square % check;
ulong q = (square - r) / check;
if ( r != 0 && q + r == next ) {
yield return next;
break;
}
}
}
}
}
|
Change the programming language of this snippet from Java to C# without modifying what it does. | public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
| using System;
using System.Collections.Generic;
public class KaprekarNumbers {
public static void Main() {
int count = 0;
foreach ( ulong i in _kaprekarGenerator(999999) ) {
Console.WriteLine(i);
count++;
}
Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
}
private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {
ulong next = 1;
yield return next;
for ( next = 2; next <= max; next++ ) {
ulong square = next * next;
for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
if ( square <= check )
break;
ulong r = square % check;
ulong q = (square - r) / check;
if ( r != 0 && q + r == next ) {
yield return next;
break;
}
}
}
}
}
|
Port the provided Java code into C# while preserving the original functionality. | import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace HofstadterFigureFigure
{
class HofstadterFigureFigure
{
readonly List<int> _r = new List<int>() {1};
readonly List<int> _s = new List<int>();
public IEnumerable<int> R()
{
int iR = 0;
while (true)
{
if (iR >= _r.Count)
{
Advance();
}
yield return _r[iR++];
}
}
public IEnumerable<int> S()
{
int iS = 0;
while (true)
{
if (iS >= _s.Count)
{
Advance();
}
yield return _s[iS++];
}
}
private void Advance()
{
int rCount = _r.Count;
int oldR = _r[rCount - 1];
int sVal;
switch (rCount)
{
case 1:
sVal = 2;
break;
case 2:
sVal = 4;
break;
default:
sVal = _s[rCount - 1];
break;
}
_r.Add(_r[rCount - 1] + sVal);
int newR = _r[rCount];
for (int iS = oldR + 1; iS < newR; iS++)
{
_s.Add(iS);
}
}
}
class Program
{
static void Main()
{
var hff = new HofstadterFigureFigure();
var rs = hff.R();
var arr = rs.Take(40).ToList();
foreach(var v in arr.Take(10))
{
Console.WriteLine("{0}", v);
}
var hs = new HashSet<int>(arr);
hs.UnionWith(hff.S().Take(960));
Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!");
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace HofstadterFigureFigure
{
class HofstadterFigureFigure
{
readonly List<int> _r = new List<int>() {1};
readonly List<int> _s = new List<int>();
public IEnumerable<int> R()
{
int iR = 0;
while (true)
{
if (iR >= _r.Count)
{
Advance();
}
yield return _r[iR++];
}
}
public IEnumerable<int> S()
{
int iS = 0;
while (true)
{
if (iS >= _s.Count)
{
Advance();
}
yield return _s[iS++];
}
}
private void Advance()
{
int rCount = _r.Count;
int oldR = _r[rCount - 1];
int sVal;
switch (rCount)
{
case 1:
sVal = 2;
break;
case 2:
sVal = 4;
break;
default:
sVal = _s[rCount - 1];
break;
}
_r.Add(_r[rCount - 1] + sVal);
int newR = _r[rCount];
for (int iS = oldR + 1; iS < newR; iS++)
{
_s.Add(iS);
}
}
}
class Program
{
static void Main()
{
var hff = new HofstadterFigureFigure();
var rs = hff.R();
var arr = rs.Take(40).ToList();
foreach(var v in arr.Take(10))
{
Console.WriteLine("{0}", v);
}
var hs = new HashSet<int>(arr);
hs.UnionWith(hff.S().Take(960));
Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!");
}
}
}
|
Ensure the translated C# code behaves exactly like the original Java snippet. | public static long fib(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
return new Object() {
private long fibInner(int n) {
return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
}
}.fibInner(n);
}
| static int Fib(int n)
{
if (n < 0) throw new ArgumentException("Must be non negativ", "n");
Func<int, int> fib = null;
fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;
return fib(n);
}
|
Generate an equivalent C# version of this Java code. | import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
| using System;
using System.IO;
class Program {
static void Main(string[] args) {
File.Create("output.txt");
File.Create(@"\output.txt");
Directory.CreateDirectory("docs");
Directory.CreateDirectory(@"\docs");
}
}
|
Generate a C# translation of this Java snippet without changing its computational steps. | interface Thingable {
String thing();
}
class Delegator {
public Thingable delegate;
public String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
class Delegate implements Thingable {
public String thing() {
return "delegate implementation";
}
}
public class DelegateExample {
public static void main(String[] args) {
Delegator a = new Delegator();
assert a.operation().equals("default implementation");
Delegate d = new Delegate();
a.delegate = d;
assert a.operation().equals("delegate implementation");
a.delegate = new Thingable() {
public String thing() {
return "anonymous delegate implementation";
}
};
assert a.operation().equals("anonymous delegate implementation");
}
}
| using System;
interface IOperable
{
string Operate();
}
class Inoperable
{
}
class Operable : IOperable
{
public string Operate()
{
return "Delegate implementation.";
}
}
class Delegator : IOperable
{
object Delegate;
public string Operate()
{
var operable = Delegate as IOperable;
return operable != null ? operable.Operate() : "Default implementation.";
}
static void Main()
{
var delegator = new Delegator();
foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
{
delegator.Delegate = @delegate;
Console.WriteLine(delegator.Operate());
}
}
}
|
Write the same algorithm in C# as shown in this Java implementation. | import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BaconCipher {
class Program {
private static Dictionary<char, string> codes = new Dictionary<char, string> {
{'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" },
{'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" },
{'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" },
{'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" },
{'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" },
{'z', "BBAAB" }, {' ', "BBBAA" },
};
private static string Encode(string plainText, string message) {
string pt = plainText.ToLower();
StringBuilder sb = new StringBuilder();
foreach (char c in pt) {
if ('a' <= c && c <= 'z') sb.Append(codes[c]);
else sb.Append(codes[' ']);
}
string et = sb.ToString();
string mg = message.ToLower();
sb.Length = 0;
int count = 0;
foreach (char c in mg) {
if ('a' <= c && c <= 'z') {
if (et[count] == 'A') sb.Append(c);
else sb.Append((char)(c - 32));
count++;
if (count == et.Length) break;
}
else sb.Append(c);
}
return sb.ToString();
}
private static string Decode(string message) {
StringBuilder sb = new StringBuilder();
foreach (char c in message) {
if ('a' <= c && c <= 'z') sb.Append('A');
else if ('A' <= c && c <= 'Z') sb.Append('B');
}
string et = sb.ToString();
sb.Length = 0;
for (int i = 0; i < et.Length; i += 5) {
string quintet = et.Substring(i, 5);
char key = codes.Where(a => a.Value == quintet).First().Key;
sb.Append(key);
}
return sb.ToString();
}
static void Main(string[] args) {
string plainText = "the quick brown fox jumps over the lazy dog";
string message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
string cipherText = Encode(plainText, message);
Console.WriteLine("Cipher text ->\n{0}", cipherText);
string decodedText = Decode(cipherText);
Console.WriteLine("\nHidden text ->\n{0}", decodedText);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BaconCipher {
class Program {
private static Dictionary<char, string> codes = new Dictionary<char, string> {
{'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" },
{'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" },
{'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" },
{'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" },
{'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" },
{'z', "BBAAB" }, {' ', "BBBAA" },
};
private static string Encode(string plainText, string message) {
string pt = plainText.ToLower();
StringBuilder sb = new StringBuilder();
foreach (char c in pt) {
if ('a' <= c && c <= 'z') sb.Append(codes[c]);
else sb.Append(codes[' ']);
}
string et = sb.ToString();
string mg = message.ToLower();
sb.Length = 0;
int count = 0;
foreach (char c in mg) {
if ('a' <= c && c <= 'z') {
if (et[count] == 'A') sb.Append(c);
else sb.Append((char)(c - 32));
count++;
if (count == et.Length) break;
}
else sb.Append(c);
}
return sb.ToString();
}
private static string Decode(string message) {
StringBuilder sb = new StringBuilder();
foreach (char c in message) {
if ('a' <= c && c <= 'z') sb.Append('A');
else if ('A' <= c && c <= 'Z') sb.Append('B');
}
string et = sb.ToString();
sb.Length = 0;
for (int i = 0; i < et.Length; i += 5) {
string quintet = et.Substring(i, 5);
char key = codes.Where(a => a.Value == quintet).First().Key;
sb.Append(key);
}
return sb.ToString();
}
static void Main(string[] args) {
string plainText = "the quick brown fox jumps over the lazy dog";
string message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
string cipherText = Encode(plainText, message);
Console.WriteLine("Cipher text ->\n{0}", cipherText);
string decodedText = Decode(cipherText);
Console.WriteLine("\nHidden text ->\n{0}", decodedText);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | public class Blah {
public static void main(String[] args) {
print2dArray(getSpiralArray(5));
}
public static int[][] getSpiralArray(int dimension) {
int[][] spiralArray = new int[dimension][dimension];
int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);
int j;
int sideLen = dimension;
int currNum = 0;
for (int i = 0; i < numConcentricSquares; i++) {
for (j = 0; j < sideLen; j++) {
spiralArray[i][i + j] = currNum++;
}
for (j = 1; j < sideLen; j++) {
spiralArray[i + j][dimension - 1 - i] = currNum++;
}
for (j = sideLen - 2; j > -1; j--) {
spiralArray[dimension - 1 - i][i + j] = currNum++;
}
for (j = sideLen - 2; j > 0; j--) {
spiralArray[i + j][i] = currNum++;
}
sideLen -= 2;
}
return spiralArray;
}
public static void print2dArray(int[][] array) {
for (int[] row : array) {
for (int elem : row) {
System.out.printf("%3d", elem);
}
System.out.println();
}
}
}
| public int[,] Spiral(int n) {
int[,] result = new int[n, n];
int pos = 0;
int count = n;
int value = -n;
int sum = -1;
do {
value = -1 * value / n;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
value *= n;
count--;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
} while (count > 0);
return result;
}
public void PrintArray(int[,] array) {
int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
Console.Write(array[i, j].ToString().PadLeft(n, ' '));
}
Console.WriteLine();
}
}
|
Ensure the translated C# code behaves exactly like the original Java snippet. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.stream.LongStream;
public class FaulhabersTriangle {
private static final MathContext MC = new MathContext(256);
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
private long denom;
public static final Frac ZERO = new Frac(0, 1);
public Frac(long n, long d) {
if (d == 0) throw new IllegalArgumentException("d must not be zero");
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.abs(gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
public Frac plus(Frac rhs) {
return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);
}
public Frac unaryMinus() {
return new Frac(-num, denom);
}
public Frac minus(Frac rhs) {
return this.plus(rhs.unaryMinus());
}
public Frac times(Frac rhs) {
return new Frac(this.num * rhs.num, this.denom * rhs.denom);
}
@Override
public int compareTo(Frac o) {
double diff = toDouble() - o.toDouble();
return Double.compare(diff, 0.0);
}
@Override
public boolean equals(Object obj) {
return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;
}
@Override
public String toString() {
if (denom == 1) {
return Long.toString(num);
}
return String.format("%d/%d", num, denom);
}
public double toDouble() {
return (double) num / denom;
}
public BigDecimal toBigDecimal() {
return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);
}
}
private static Frac bernoulli(int n) {
if (n < 0) throw new IllegalArgumentException("n may not be negative or zero");
Frac[] a = new Frac[n + 1];
Arrays.fill(a, Frac.ZERO);
for (int m = 0; m <= n; ++m) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; --j) {
a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));
}
}
if (n != 1) return a[0];
return a[0].unaryMinus();
}
private static long binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();
if (n == 0 || k == 0) return 1;
long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);
long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);
return num / den;
}
private static Frac[] faulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
Arrays.fill(coeffs, Frac.ZERO);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; ++j) {
sign *= -1;
coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));
}
return coeffs;
}
public static void main(String[] args) {
for (int i = 0; i <= 9; ++i) {
Frac[] coeffs = faulhaberTriangle(i);
for (Frac coeff : coeffs) {
System.out.printf("%5s ", coeff);
}
System.out.println();
}
System.out.println();
int k = 17;
Frac[] cc = faulhaberTriangle(k);
int n = 1000;
BigDecimal nn = BigDecimal.valueOf(n);
BigDecimal np = BigDecimal.ONE;
BigDecimal sum = BigDecimal.ZERO;
for (Frac c : cc) {
np = np.multiply(nn);
sum = sum.add(np.multiply(c.toBigDecimal()));
}
System.out.println(sum.toBigInteger());
}
}
| using System;
namespace FaulhabersTriangle {
internal class Frac {
private long num;
private long denom;
public static readonly Frac ZERO = new Frac(0, 1);
public static readonly Frac ONE = new Frac(1, 1);
public Frac(long n, long d) {
if (d == 0) {
throw new ArgumentException("d must not be zero");
}
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
}
else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.Abs(Gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
private static long Gcd(long a, long b) {
if (b == 0) {
return a;
}
return Gcd(b, a % b);
}
public static Frac operator -(Frac self) {
return new Frac(-self.num, self.denom);
}
public static Frac operator +(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
public static Frac operator -(Frac lhs, Frac rhs) {
return lhs + -rhs;
}
public static Frac operator *(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
public static bool operator <(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x < y;
}
public static bool operator >(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x > y;
}
public static bool operator ==(Frac lhs, Frac rhs) {
return lhs.num == rhs.num && lhs.denom == rhs.denom;
}
public static bool operator !=(Frac lhs, Frac rhs) {
return lhs.num != rhs.num || lhs.denom != rhs.denom;
}
public override string ToString() {
if (denom == 1) {
return num.ToString();
}
return string.Format("{0}/{1}", num, denom);
}
public override bool Equals(object obj) {
var frac = obj as Frac;
return frac != null &&
num == frac.num &&
denom == frac.denom;
}
public override int GetHashCode() {
var hashCode = 1317992671;
hashCode = hashCode * -1521134295 + num.GetHashCode();
hashCode = hashCode * -1521134295 + denom.GetHashCode();
return hashCode;
}
}
class Program {
static Frac Bernoulli(int n) {
if (n < 0) {
throw new ArgumentException("n may not be negative or zero");
}
Frac[] a = new Frac[n + 1];
for (int m = 0; m <= n; m++) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);
}
}
if (n != 1) return a[0];
return -a[0];
}
static int Binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw new ArgumentException();
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num = num * i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom = denom * i;
}
return num / denom;
}
static Frac[] FaulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
for (int i = 0; i < p + 1; i++) {
coeffs[i] = Frac.ZERO;
}
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);
}
return coeffs;
}
static void Main(string[] args) {
for (int i = 0; i < 10; i++) {
Frac[] coeffs = FaulhaberTriangle(i);
foreach (Frac coeff in coeffs) {
Console.Write("{0,5} ", coeff);
}
Console.WriteLine();
}
}
}
}
|
Ensure the translated C# code behaves exactly like the original Java snippet. | public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
| using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
for (int i = 0; i < args.Length; i++)
Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));
}
}
}
|
Transform the following Java implementation into C#, maintaining the same output and logic. | public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
| using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
for (int i = 0; i < args.Length; i++)
Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));
}
}
}
|
Generate a C# translation of this Java snippet without changing its computational steps. | String[] fruits = ["apples", "oranges"];
String[] grains = ["wheat", "corn"];
String[] all = fruits + grains;
| using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = new int[a.Length + b.Length];
a.CopyTo(c, 0);
b.CopyTo(c, a.Length);
foreach(int n in c)
{
Console.WriteLine(n.ToString());
}
}
}
}
|
Port the provided Java code into C# while preserving the original functionality. | import java.util.Scanner;
public class GetInput {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = s.nextLine();
System.out.print("Enter an integer: ");
int i = Integer.parseInt(s.next());
}
}
| using System;
namespace C_Sharp_Console {
class example {
static void Main() {
string word;
int num;
Console.Write("Enter an integer: ");
num = Console.Read();
Console.Write("Enter a String: ");
word = Console.ReadLine();
}
}
}
|
Ensure the translated C# code behaves exactly like the original Java snippet. | package hu.pj.alg.test;
import hu.pj.alg.ZeroOneKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;
public class ZeroOneKnapsackForTourists {
public ZeroOneKnapsackForTourists() {
ZeroOneKnapsack zok = new ZeroOneKnapsack(400);
zok.add("map", 9, 150);
zok.add("compass", 13, 35);
zok.add("water", 153, 200);
zok.add("sandwich", 50, 160);
zok.add("glucose", 15, 60);
zok.add("tin", 68, 45);
zok.add("banana", 27, 60);
zok.add("apple", 39, 40);
zok.add("cheese", 23, 30);
zok.add("beer", 52, 10);
zok.add("suntan cream", 11, 70);
zok.add("camera", 32, 30);
zok.add("t-shirt", 24, 15);
zok.add("trousers", 48, 10);
zok.add("umbrella", 73, 40);
zok.add("waterproof trousers", 42, 70);
zok.add("waterproof overclothes", 43, 75);
zok.add("note-case", 22, 80);
zok.add("sunglasses", 7, 20);
zok.add("towel", 18, 12);
zok.add("socks", 4, 50);
zok.add("book", 30, 10);
List<Item> itemList = zok.calcSolution();
if (zok.isCalculated()) {
NumberFormat nf = NumberFormat.getInstance();
System.out.println(
"Maximal weight = " +
nf.format(zok.getMaxWeight() / 100.0) + " kg"
);
System.out.println(
"Total weight of solution = " +
nf.format(zok.getSolutionWeight() / 100.0) + " kg"
);
System.out.println(
"Total value = " +
zok.getProfit()
);
System.out.println();
System.out.println(
"You can carry the following materials " +
"in the knapsack:"
);
for (Item item : itemList) {
if (item.getInKnapsack() == 1) {
System.out.format(
"%1$-23s %2$-3s %3$-5s %4$-15s \n",
item.getName(),
item.getWeight(), "dag ",
"(value = " + item.getValue() + ")"
);
}
}
} else {
System.out.println(
"The problem is not solved. " +
"Maybe you gave wrong data."
);
}
}
public static void main(String[] args) {
new ZeroOneKnapsackForTourists();
}
}
| using System;
using System.Collections.Generic;
namespace Tests_With_Framework_4
{
class Bag : IEnumerable<Bag.Item>
{
List<Item> items;
const int MaxWeightAllowed = 400;
public Bag()
{
items = new List<Item>();
}
void AddItem(Item i)
{
if ((TotalWeight + i.Weight) <= MaxWeightAllowed)
items.Add(i);
}
public void Calculate(List<Item> items)
{
foreach (Item i in Sorte(items))
{
AddItem(i);
}
}
List<Item> Sorte(List<Item> inputItems)
{
List<Item> choosenItems = new List<Item>();
for (int i = 0; i < inputItems.Count; i++)
{
int j = -1;
if (i == 0)
{
choosenItems.Add(inputItems[i]);
}
if (i > 0)
{
if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))
{
choosenItems.Add(inputItems[i]);
}
}
}
return choosenItems;
}
bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)
{
if (!(lastBound < 0))
{
if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )
{
indxToAdd = lastBound;
}
return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);
}
if (indxToAdd > -1)
{
choosenItems.Insert(indxToAdd, knapsackItems[i]);
return true;
}
return false;
}
#region IEnumerable<Item> Members
IEnumerator<Item> IEnumerable<Item>.GetEnumerator()
{
foreach (Item i in items)
yield return i;
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
public int TotalWeight
{
get
{
var sum = 0;
foreach (Item i in this)
{
sum += i.Weight;
}
return sum;
}
}
public class Item
{
public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } }
public override string ToString()
{
return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV;
}
}
}
class Program
{
static void Main(string[] args)
{List<Bag.Item> knapsackItems = new List<Bag.Item>();
knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 });
knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 });
knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 });
knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 });
knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 });
knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 });
knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 });
knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 });
knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 });
knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 });
knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 });
knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 });
knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 });
knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 });
knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 });
knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 });
knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 });
knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 });
knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 });
Bag b = new Bag();
b.Calculate(knapsackItems);
b.All(x => { Console.WriteLine(x); return true; });
Console.WriteLine(b.Sum(x => x.Weight));
Console.ReadKey();
}
}
}
|
Convert this Java block to C#, preserving its control flow and logic. | import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
| using System;
public class Program
{
public static void Main()
{
int[] empty = new int[0];
int[] list1 = { 1, 2 };
int[] list2 = { 3, 4 };
int[] list3 = { 1776, 1789 };
int[] list4 = { 7, 12 };
int[] list5 = { 4, 14, 23 };
int[] list6 = { 0, 1 };
int[] list7 = { 1, 2, 3 };
int[] list8 = { 30 };
int[] list9 = { 500, 100 };
foreach (var sequenceList in new [] {
new [] { list1, list2 },
new [] { list2, list1 },
new [] { list1, empty },
new [] { empty, list1 },
new [] { list3, list4, list5, list6 },
new [] { list7, list8, list9 },
new [] { list7, empty, list9 }
}) {
var cart = sequenceList.CartesianProduct()
.Select(tuple => $"({string.Join(", ", tuple)})");
Console.WriteLine($"{{{string.Join(", ", cart)}}}");
}
}
}
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
}
|
Translate the given Java code snippet into C# without altering its behavior. | import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
| using System;
public class Program
{
public static void Main()
{
int[] empty = new int[0];
int[] list1 = { 1, 2 };
int[] list2 = { 3, 4 };
int[] list3 = { 1776, 1789 };
int[] list4 = { 7, 12 };
int[] list5 = { 4, 14, 23 };
int[] list6 = { 0, 1 };
int[] list7 = { 1, 2, 3 };
int[] list8 = { 30 };
int[] list9 = { 500, 100 };
foreach (var sequenceList in new [] {
new [] { list1, list2 },
new [] { list2, list1 },
new [] { list1, empty },
new [] { empty, list1 },
new [] { list3, list4, list5, list6 },
new [] { list7, list8, list9 },
new [] { list7, empty, list9 }
}) {
var cart = sequenceList.CartesianProduct()
.Select(tuple => $"({string.Join(", ", tuple)})");
Console.WriteLine($"{{{string.Join(", ", cart)}}}");
}
}
}
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
}
|
Convert this Java block to C#, preserving its control flow and logic. | import java.util.ArrayList;
public class FirstClass{
public interface Function<A,B>{
B apply(A x);
}
public static <A,B,C> Function<A, C> compose(
final Function<B, C> f, final Function<A, B> g) {
return new Function<A, C>() {
@Override public C apply(A x) {
return f.apply(g.apply(x));
}
};
}
public static void main(String[] args){
ArrayList<Function<Double, Double>> functions =
new ArrayList<Function<Double,Double>>();
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.cos(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.tan(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return x * x;
}
});
ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.acos(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.atan(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.sqrt(x);
}
});
System.out.println("Compositions:");
for(int i = 0; i < functions.size(); i++){
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
System.out.println("Hard-coded compositions:");
System.out.println(Math.cos(Math.acos(0.5)));
System.out.println(Math.tan(Math.atan(0.5)));
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}
| using System;
class Program
{
static void Main(string[] args)
{
var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));
var functionTuples = new[]
{
(forward: Math.Sin, backward: Math.Asin),
(forward: Math.Cos, backward: Math.Acos),
(forward: cube, backward: croot)
};
foreach (var ft in functionTuples)
{
Console.WriteLine(ft.backward(ft.forward(0.5)));
}
}
}
|
Write the same code in C# as shown below in Java. | import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Proper{
public static List<Integer> properDivs(int n){
List<Integer> divs = new LinkedList<Integer>();
if(n == 1) return divs;
divs.add(1);
for(int x = 2; x < n; x++){
if(n % x == 0) divs.add(x);
}
Collections.sort(divs);
return divs;
}
public static void main(String[] args){
for(int x = 1; x <= 10; x++){
System.out.println(x + ": " + properDivs(x));
}
int x = 0, count = 0;
for(int n = 1; n <= 20000; n++){
if(properDivs(n).size() > count){
x = n;
count = properDivs(n).size();
}
}
System.out.println(x + ": " + count);
}
}
| namespace RosettaCode.ProperDivisors
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
private static IEnumerable<int> ProperDivisors(int number)
{
return
Enumerable.Range(1, number / 2)
.Where(divisor => number % divisor == 0);
}
private static void Main()
{
foreach (var number in Enumerable.Range(1, 10))
{
Console.WriteLine("{0}: {{{1}}}", number,
string.Join(", ", ProperDivisors(number)));
}
var record = Enumerable.Range(1, 20000).Select(number => new
{
Number = number,
Count = ProperDivisors(number).Count()
}).OrderByDescending(currentRecord => currentRecord.Count).First();
Console.WriteLine("{0}: {1}", record.Number, record.Count);
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XmlCreation {
private static final String[] names = {"April", "Tam O'Shanter", "Emily"};
private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"};
public static void main(String[] args) {
try {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element root = doc.createElement("CharacterRemarks");
doc.appendChild(root);
for(int i = 0; i < names.length; i++) {
final Element character = doc.createElement("Character");
root.appendChild(character);
character.setAttribute("name", names[i]);
character.appendChild(doc.createTextNode(remarks[i]));
}
final Source source = new DOMSource(doc);
final StringWriter buffer = new StringWriter();
final Result result = new StreamResult(buffer);
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.transform(source, result);
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Program
{
static string CreateXML(Dictionary<string, string> characterRemarks)
{
var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key)));
var xml = new XElement("CharacterRemarks", remarks);
return xml.ToString();
}
static void Main(string[] args)
{
var characterRemarks = new Dictionary<string, string>
{
{ "April", "Bubbly: I'm > Tam and <= Emily" },
{ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" },
{ "Emily", "Short & shrift" }
};
string xml = CreateXML(characterRemarks);
Console.WriteLine(xml);
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | String str = "I am a string";
if (str.matches(".*string")) {
System.out.println("ends with 'string'");
}
| using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string str = "I am a string";
if (new Regex("string$").IsMatch(str)) {
Console.WriteLine("Ends with string.");
}
str = new Regex(" a ").Replace(str, " another ");
Console.WriteLine(str);
}
}
|
Write a version of this Java function in C# with identical behavior. | import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;
public class GuessNumber {
public static final int LOWER = 0, UPPER = 100;
public static void main(String[] args) {
System.out.printf("Instructions:\n" +
"Think of integer number from %d (inclusive) to %d (exclusive) and\n" +
"I will guess it. After each guess, you respond with L, H, or C depending\n" +
"on if my guess was too low, too high, or correct.\n",
LOWER, UPPER);
int result = Collections.binarySearch(new AbstractList<Integer>() {
private final Scanner in = new Scanner(System.in);
public int size() { return UPPER - LOWER; }
public Integer get(int i) {
System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i);
String s = in.nextLine();
assert s.length() > 0;
switch (Character.toLowerCase(s.charAt(0))) {
case 'l':
return -1;
case 'h':
return 1;
case 'c':
return 0;
}
return -1;
}
}, 0);
if (result < 0)
System.out.println("That is impossible.");
else
System.out.printf("Your number is %d.\n", result);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class RealisticGuess
{
private int max;
private int min;
private int guess;
public void Start()
{
Console.Clear();
string input;
try
{
Console.WriteLine("Please enter the lower boundary");
input = Console.ReadLine();
min = Convert.ToInt32(input);
Console.WriteLine("Please enter the upper boundary");
input = Console.ReadLine();
max = Convert.ToInt32(input);
}
catch (FormatException)
{
Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again.");
Console.ReadKey(true);
Start();
}
Console.WriteLine("Think of a number between {0} and {1}.", min, max);
Thread.Sleep(2500);
Console.WriteLine("Ready?");
Console.WriteLine("Press any key to begin.");
Console.ReadKey(true);
Guess(min, max);
}
public void Guess(int min, int max)
{
int counter = 1;
string userAnswer;
bool correct = false;
Random rand = new Random();
while (correct == false)
{
guess = rand.Next(min, max);
Console.Clear();
Console.WriteLine("{0}", guess);
Console.WriteLine("Is this number correct? {Y/N}");
userAnswer = Console.ReadLine();
if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N")
{
Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'");
Console.WriteLine("Is the number correct? {Y/N}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "y" || userAnswer == "Y")
{
correct = true;
}
if (userAnswer == "n" || userAnswer == "N")
{
counter++;
if (max == min)
{
Console.WriteLine("Error: Range Intersect. Press enter to restart the game.");
Console.ReadKey(true);
Guess(1, 101);
}
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H")
{
Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'");
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "l" || userAnswer == "L")
{
max = guess;
}
if (userAnswer == "h" || userAnswer == "H")
{
min = guess;
}
}
}
if (correct == true)
{
EndAndLoop(counter);
}
}
public void EndAndLoop(int iterations)
{
string userChoice;
bool loop = false;
Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations);
while (loop == false)
{
Console.WriteLine("Would you like to play again? {Y/N}");
userChoice = Console.ReadLine();
if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n")
{
Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.");
}
if (userChoice == "Y" || userChoice == "y")
{
Start();
}
if (userChoice == "N" || userChoice == "n")
{
Environment.Exit(1);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Title = "Random Number";
RealisticGuess game = new RealisticGuess();
game.Start();
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original Java code. | import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
}
| static class Program
{
static void Main()
{
System.Collections.Hashtable h = new System.Collections.Hashtable();
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");
for (int i = 0; i < keys.Length; i++)
{
h.Add(keys[i], values[i]);
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
| using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
| using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
|
Convert this Java block to C#, preserving its control flow and logic. | import java.awt.*;
import javax.swing.*;
public class Pendulum extends JPanel implements Runnable {
private double angle = Math.PI / 2;
private int length;
public Pendulum(int length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
int ballX = anchorX + (int) (Math.sin(angle) * length);
int ballY = anchorY + (int) (Math.cos(angle) * length);
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
public void run() {
double angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(2 * length + 50, length / 2 * 3);
}
public static void main(String[] args) {
JFrame f = new JFrame("Pendulum");
Pendulum p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
class CSharpPendulum
{
Form _form;
Timer _timer;
double _angle = Math.PI / 2,
_angleAccel,
_angleVelocity = 0,
_dt = 0.1;
int _length = 50;
[STAThread]
static void Main()
{
var p = new CSharpPendulum();
}
public CSharpPendulum()
{
_form = new Form() { Text = "Pendulum", Width = 200, Height = 200 };
_timer = new Timer() { Interval = 30 };
_timer.Tick += delegate(object sender, EventArgs e)
{
int anchorX = (_form.Width / 2) - 12,
anchorY = _form.Height / 4,
ballX = anchorX + (int)(Math.Sin(_angle) * _length),
ballY = anchorY + (int)(Math.Cos(_angle) * _length);
_angleAccel = -9.81 / _length * Math.Sin(_angle);
_angleVelocity += _angleAccel * _dt;
_angle += _angleVelocity * _dt;
Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);
Graphics g = Graphics.FromImage(dblBuffer);
Graphics f = Graphics.FromHwnd(_form.Handle);
g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));
g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);
g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);
f.Clear(Color.White);
f.DrawImage(dblBuffer, new Point(0, 0));
};
_timer.Start();
Application.Run(_form);
}
}
|
Write the same code in C# as shown below in Java. | public static void heapSort(int[] a){
int count = a.length;
heapify(a, count);
int end = count - 1;
while(end > 0){
int tmp = a[end];
a[end] = a[0];
a[0] = tmp;
siftDown(a, 0, end - 1);
end--;
}
}
public static void heapify(int[] a, int count){
int start = (count - 2) / 2;
while(start >= 0){
siftDown(a, start, count - 1);
start--;
}
}
public static void siftDown(int[] a, int start, int end){
int root = start;
while((root * 2 + 1) <= end){
int child = root * 2 + 1;
if(child + 1 <= end && a[child] < a[child + 1])
child = child + 1;
if(a[root] < a[child]){
int tmp = a[root];
a[root] = a[child];
a[child] = tmp;
root = child;
}else
return;
}
}
| using System;
using System.Collections.Generic;
using System.Text;
public class HeapSortClass
{
public static void HeapSort<T>(T[] array)
{
HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);
}
public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)
{
HeapSort<T>(array, offset, length, comparer.Compare);
}
public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)
{
for (int i = 0; i < length; i++)
{
int index = i;
T item = array[offset + i];
while (index > 0 &&
comparison(array[offset + (index - 1) / 2], item) < 0)
{
int top = (index - 1) / 2;
array[offset + index] = array[offset + top];
index = top;
}
array[offset + index] = item;
}
for (int i = length - 1; i > 0; i--)
{
T last = array[offset + i];
array[offset + i] = array[offset];
int index = 0;
while (index * 2 + 1 < i)
{
int left = index * 2 + 1, right = left + 1;
if (right < i && comparison(array[offset + left], array[offset + right]) < 0)
{
if (comparison(last, array[offset + right]) > 0) break;
array[offset + index] = array[offset + right];
index = right;
}
else
{
if (comparison(last, array[offset + left]) > 0) break;
array[offset + index] = array[offset + left];
index = left;
}
}
array[offset + index] = last;
}
}
static void Main()
{
byte[] r = {5, 4, 1, 2};
HeapSort(r);
string[] s = { "-", "D", "a", "33" };
HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);
}
}
|
Change the following Java code into C# without altering its purpose. | public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace }
| using System;
using System.Linq;
using System.Collections.Generic;
public struct Card
{
public Card(string rank, string suit) : this()
{
Rank = rank;
Suit = suit;
}
public string Rank { get; }
public string Suit { get; }
public override string ToString() => $"{Rank} of {Suit}";
}
public class Deck : IEnumerable<Card>
{
static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
readonly List<Card> cards;
public Deck() {
cards = (from suit in suits
from rank in ranks
select new Card(rank, suit)).ToList();
}
public int Count => cards.Count;
public void Shuffle() {
var random = new Random();
for (int i = 0; i < cards.Count; i++) {
int r = random.Next(i, cards.Count);
var temp = cards[i];
cards[i] = cards[r];
cards[r] = temp;
}
}
public Card Deal() {
int last = cards.Count - 1;
Card card = cards[last];
cards.RemoveAt(last);
return card;
}
public IEnumerator<Card> GetEnumerator() {
for (int i = cards.Count - 1; i >= 0; i--)
yield return cards[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
|
Translate this program into C# but keep the logic exactly as in Java. | Int[] literalArray = [1,2,3];
Int[] fixedLengthArray = new Int[10];
Int[] variableArray = new Int[];
assert literalArray.size == 3;
Int n = literalArray[2];
fixedLengthArray[4] = 12345;
fixedLengthArray += 6789;
variableArray += 6789;
| int[] numbers = new int[10];
|
Ensure the translated C# code behaves exactly like the original Java snippet. | public static boolean inCarpet(long x, long y) {
while (x!=0 && y!=0) {
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
public static void carpet(final int n) {
final double power = Math.pow(3,n);
for(long i = 0; i < power; i++) {
for(long j = 0; j < power; j++) {
System.out.print(inCarpet(i, j) ? "*" : " ");
}
System.out.println();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<string> NextCarpet(List<string> carpet)
{
return carpet.Select(x => x + x + x)
.Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
.Concat(carpet.Select(x => x + x + x)).ToList();
}
static List<string> SierpinskiCarpet(int n)
{
return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
}
static void Main(string[] args)
{
foreach (string s in SierpinskiCarpet(3))
Console.WriteLine(s);
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | public class BogoSort
{
public static void main(String[] args)
{
int[] arr={4,5,6,0,7,8,9,1,2,3};
BogoSort now=new BogoSort();
System.out.print("Unsorted: ");
now.display1D(arr);
now.bogo(arr);
System.out.print("Sorted: ");
now.display1D(arr);
}
void bogo(int[] arr)
{
int shuffle=1;
for(;!isSorted(arr);shuffle++)
shuffle(arr);
System.out.println("This took "+shuffle+" shuffles.");
}
void shuffle(int[] arr)
{
int i=arr.length-1;
while(i>0)
swap(arr,i--,(int)(Math.random()*i));
}
void swap(int[] arr,int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
boolean isSorted(int[] arr)
{
for(int i=1;i<arr.length;i++)
if(arr[i]<arr[i-1])
return false;
return true;
}
void display1D(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
| using System;
using System.Collections.Generic;
namespace RosettaCode.BogoSort
{
public static class BogoSorter
{
public static void Sort<T>(List<T> list) where T:IComparable
{
while (!list.isSorted())
{
list.Shuffle();
}
}
private static bool isSorted<T>(this IList<T> list) where T:IComparable
{
if(list.Count<=1)
return true;
for (int i = 1 ; i < list.Count; i++)
if(list[i].CompareTo(list[i-1])<0) return false;
return true;
}
private static void Shuffle<T>(this IList<T> list)
{
Random rand = new Random();
for (int i = 0; i < list.Count; i++)
{
int swapIndex = rand.Next(list.Count);
T temp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = temp;
}
}
}
class TestProgram
{
static void Main()
{
List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
BogoSorter.Sort(testList);
foreach (int i in testList) Console.Write(i + " ");
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | public class BogoSort
{
public static void main(String[] args)
{
int[] arr={4,5,6,0,7,8,9,1,2,3};
BogoSort now=new BogoSort();
System.out.print("Unsorted: ");
now.display1D(arr);
now.bogo(arr);
System.out.print("Sorted: ");
now.display1D(arr);
}
void bogo(int[] arr)
{
int shuffle=1;
for(;!isSorted(arr);shuffle++)
shuffle(arr);
System.out.println("This took "+shuffle+" shuffles.");
}
void shuffle(int[] arr)
{
int i=arr.length-1;
while(i>0)
swap(arr,i--,(int)(Math.random()*i));
}
void swap(int[] arr,int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
boolean isSorted(int[] arr)
{
for(int i=1;i<arr.length;i++)
if(arr[i]<arr[i-1])
return false;
return true;
}
void display1D(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
| using System;
using System.Collections.Generic;
namespace RosettaCode.BogoSort
{
public static class BogoSorter
{
public static void Sort<T>(List<T> list) where T:IComparable
{
while (!list.isSorted())
{
list.Shuffle();
}
}
private static bool isSorted<T>(this IList<T> list) where T:IComparable
{
if(list.Count<=1)
return true;
for (int i = 1 ; i < list.Count; i++)
if(list[i].CompareTo(list[i-1])<0) return false;
return true;
}
private static void Shuffle<T>(this IList<T> list)
{
Random rand = new Random();
for (int i = 0; i < list.Count; i++)
{
int swapIndex = rand.Next(list.Count);
T temp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = temp;
}
}
}
class TestProgram
{
static void Main()
{
List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
BogoSorter.Sort(testList);
foreach (int i in testList) Console.Write(i + " ");
}
}
}
|
Transform the following Java implementation into C#, maintaining the same output and logic. | public class Euler {
private static void euler (Callable f, double y0, int a, int b, int h) {
int t = a;
double y = y0;
while (t < b) {
System.out.println ("" + t + " " + y);
t += h;
y += h * f.compute (t, y);
}
System.out.println ("DONE");
}
public static void main (String[] args) {
Callable cooling = new Cooling ();
int[] steps = {2, 5, 10};
for (int stepSize : steps) {
System.out.println ("Step size: " + stepSize);
euler (cooling, 100.0, 0, 100, stepSize);
}
}
}
interface Callable {
public double compute (int time, double t);
}
class Cooling implements Callable {
public double compute (int time, double t) {
return -0.07 * (t - 20);
}
}
| using System;
namespace prog
{
class MainClass
{
const float T0 = 100f;
const float TR = 20f;
const float k = 0.07f;
readonly static float[] delta_t = {2.0f,5.0f,10.0f};
const int n = 100;
public delegate float func(float t);
static float NewtonCooling(float t)
{
return -k * (t-TR);
}
public static void Main (string[] args)
{
func f = new func(NewtonCooling);
for(int i=0; i<delta_t.Length; i++)
{
Console.WriteLine("delta_t = " + delta_t[i]);
Euler(f,T0,n,delta_t[i]);
}
}
public static void Euler(func f, float y, int n, float h)
{
for(float x=0; x<=n; x+=h)
{
Console.WriteLine("\t" + x + "\t" + y);
y += h * f(y);
}
}
}
}
|
Produce a functionally identical C# code for the snippet given in Java. | public class SeqNonSquares {
public static int nonsqr(int n) {
return n + (int)Math.round(Math.sqrt(n));
}
public static void main(String[] args) {
for (int i = 1; i < 23; i++)
System.out.print(nonsqr(i) + " ");
System.out.println();
for (int i = 1; i < 1000000; i++) {
double j = Math.sqrt(nonsqr(i));
assert j != Math.floor(j);
}
}
}
| using System;
using System.Diagnostics;
namespace sons
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 23; i++)
Console.WriteLine(nonsqr(i));
for (int i = 1; i < 1000000; i++)
{
double j = Math.Sqrt(nonsqr(i));
Debug.Assert(j != Math.Floor(j),"Square");
}
}
static int nonsqr(int i)
{
return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
}
}
}
|
Please provide an equivalent version of this Java code in C#. | public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
public static String Substring(String str, int n){
return str.substring(n);
}
public static String Substring(String str){
return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
| using System;
namespace SubString
{
class Program
{
static void Main(string[] args)
{
string s = "0123456789";
const int n = 3;
const int m = 2;
const char c = '3';
const string z = "345";
Console.WriteLine(s.Substring(n, m));
Console.WriteLine(s.Substring(n, s.Length - n));
Console.WriteLine(s.Substring(0, s.Length - 1));
Console.WriteLine(s.Substring(s.IndexOf(c), m));
Console.WriteLine(s.Substring(s.IndexOf(z), m));
}
}
}
|
Write the same code in C# as shown below in Java. | public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
public static String Substring(String str, int n){
return str.substring(n);
}
public static String Substring(String str){
return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
| using System;
namespace SubString
{
class Program
{
static void Main(string[] args)
{
string s = "0123456789";
const int n = 3;
const int m = 2;
const char c = '3';
const string z = "345";
Console.WriteLine(s.Substring(n, m));
Console.WriteLine(s.Substring(n, s.Length - n));
Console.WriteLine(s.Substring(0, s.Length - 1));
Console.WriteLine(s.Substring(s.IndexOf(c), m));
Console.WriteLine(s.Substring(s.IndexOf(z), m));
}
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. | public class JortSort {
public static void main(String[] args) {
System.out.println(jortSort(new int[]{1, 2, 3}));
}
static boolean jortSort(int[] arr) {
return true;
}
}
| using System;
class Program
{
public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>
{
T[] originalArray = (T[]) array.Clone();
Array.Sort(array);
for (var i = 0; i < originalArray.Length; i++)
{
if (!Equals(originalArray[i], array[i]))
{
return false;
}
}
return true;
}
}
|
Write a version of this Java function in C# with identical behavior. | import java.util.GregorianCalendar;
import java.text.MessageFormat;
public class Leapyear{
public static void main(String[] argv){
int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
GregorianCalendar cal = new GregorianCalendar();
for(int year : yrs){
System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
year, cal.isLeapYear(year), isLeapYear(year)));
}
}
public static boolean isLeapYear(int year){
return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
}
}
| using System;
class Program
{
static void Main()
{
foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })
{
Console.WriteLine("{0} is {1}a leap year.",
year,
DateTime.IsLeapYear(year) ? string.Empty : "not ");
}
}
}
|
Generate an equivalent C# version of this Java code. | import java.util.List;
import java.util.stream.*;
public class LexicographicalNumbers {
static List<Integer> lexOrder(int n) {
int first = 1, last = n;
if (n < 1) {
first = n;
last = 1;
}
return IntStream.rangeClosed(first, last)
.mapToObj(Integer::toString)
.sorted()
.map(Integer::valueOf)
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println("In lexicographical order:\n");
int[] ints = {0, 5, 13, 21, -22};
for (int n : ints) {
System.out.printf("%3d: %s\n", n, lexOrder(n));
}
}
}
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
public static void Main() {
foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}");
}
public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}
|
Change the programming language of this snippet from Java to C# without modifying what it does. | module NumberNames
{
void run()
{
@Inject Console console;
Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,
123456789000, 0x123456789ABCDEF];
for (Int test : tests)
{
console.print($"{test} = {toEnglish(test)}");
}
}
static String[] digits = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"];
static String[] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
static String[] tens = ["zero", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"];
static String[] ten3rd = ["?", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"];
static String toEnglish(Int n)
{
StringBuffer buf = new StringBuffer();
if (n < 0)
{
"negative ".appendTo(buf);
n = -n;
}
format3digits(n, buf);
return buf.toString();
}
static void format3digits(Int n, StringBuffer buf, Int nested=0)
{
(Int left, Int right) = n /% 1000;
if (left != 0)
{
format3digits(left, buf, nested+1);
}
if (right != 0 || (left == 0 && nested==0))
{
if (right >= 100)
{
(left, right) = (right /% 100);
digits[left].appendTo(buf);
" hundred ".appendTo(buf);
if (right != 0)
{
format2digits(right, buf);
}
}
else
{
format2digits(right, buf);
}
if (nested > 0)
{
ten3rd[nested].appendTo(buf).add(' ');
}
}
}
static void format2digits(Int n, StringBuffer buf)
{
switch (n)
{
case 0..9:
digits[n].appendTo(buf).add(' ');
break;
case 10..19:
teens[n-10].appendTo(buf).add(' ');
break;
default:
(Int left, Int right) = n /% 10;
tens[left].appendTo(buf);
if (right == 0)
{
buf.add(' ');
}
else
{
buf.add('-');
digits[right].appendTo(buf).add(' ');
}
break;
}
}
}
| using System;
class NumberNamer {
static readonly string[] incrementsOfOne =
{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
static readonly string[] incrementsOfTen =
{ "", "", "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
const string millionName = "million",
thousandName = "thousand",
hundredName = "hundred",
andName = "and";
public static string GetName( int i ) {
string output = "";
if( i >= 1000000 ) {
output += ParseTriplet( i / 1000000 ) + " " + millionName;
i %= 1000000;
if( i == 0 ) return output;
}
if( i >= 1000 ) {
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i / 1000 ) + " " + thousandName;
i %= 1000;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i );
return output;
}
static string ParseTriplet( int i ) {
string output = "";
if( i >= 100 ) {
output += incrementsOfOne[i / 100] + " " + hundredName;
i %= 100;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " " + andName + " ";
}
if( i >= 20 ) {
output += incrementsOfTen[i / 10];
i %= 10;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " ";
}
output += incrementsOfOne[i];
return output;
}
}
class Program {
static void Main( string[] args ) {
Console.WriteLine( NumberNamer.GetName( 1 ) );
Console.WriteLine( NumberNamer.GetName( 234 ) );
Console.WriteLine( NumberNamer.GetName( 31337 ) );
Console.WriteLine( NumberNamer.GetName( 987654321 ) );
}
}
|
Rewrite the snippet below in C# so it works the same as the original Java code. | package stringlensort;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
public class ReportStringLengths {
public static void main(String[] args) {
String[] list = {"abcd", "123456789", "abcdef", "1234567"};
String[] strings = args.length > 0 ? args : list;
compareAndReportStringsLength(strings);
}
public static void compareAndReportStringsLength(String[] strings) {
compareAndReportStringsLength(strings, System.out);
}
public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
if (strings.length > 0) {
strings = strings.clone();
final String QUOTE = "\"";
Arrays.sort(strings, Comparator.comparing(String::length));
int min = strings[0].length();
int max = strings[strings.length - 1].length();
for (int i = strings.length - 1; i >= 0; i--) {
int length = strings[i].length();
String predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
}
stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
+ " and " + predicate);
}
}
}
}
| using System;
using System.Collections.Generic;
namespace example
{
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(strings);
}
private static void compareAndReportStringsLength(string[] strings)
{
if (strings.Length > 0)
{
char Q = '"';
string hasLength = " has length ";
string predicateMax = " and is the longest string";
string predicateMin = " and is the shortest string";
string predicateAve = " and is neither the longest nor the shortest string";
string predicate;
(int, int)[] li = new (int, int)[strings.Length];
for (int i = 0; i < strings.Length; i++)
li[i] = (strings[i].Length, i);
Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
int maxLength = li[0].Item1;
int minLength = li[strings.Length - 1].Item1;
for (int i = 0; i < strings.Length; i++)
{
int length = li[i].Item1;
string str = strings[li[i].Item2];
if (length == maxLength)
predicate = predicateMax;
else if (length == minLength)
predicate = predicateMin;
else
predicate = predicateAve;
Console.WriteLine(Q + str + Q + hasLength + length + predicate);
}
}
}
}
}
|
Generate an equivalent C# version of this Java code. | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LetterFreq {
public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine()) != null){
line = line.toUpperCase();
for(char ch:line.toCharArray()){
if(Character.isLetter(ch)){
freqs[ch - 'A']++;
}
}
}
in.close();
return freqs;
}
public static void main(String[] args) throws IOException{
System.out.println(Arrays.toString(countLetters("filename.txt")));
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
{
var dictionary = new SortedDictionary<TItem, int>();
foreach (var item in items)
{
if (dictionary.ContainsKey(item))
{
dictionary[item]++;
}
else
{
dictionary[item] = 1;
}
}
return dictionary;
}
static void Main(string[] arguments)
{
var file = arguments.FirstOrDefault();
if (File.Exists(file))
{
var text = File.ReadAllText(file);
foreach (var entry in GetFrequencies(text))
{
Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | String s = "12345";
IntLiteral lit1 = new IntLiteral(s);
IntLiteral lit2 = 6789;
++lit1;
++lit2;
| string s = "12345";
s = (int.Parse(s) + 1).ToString();
using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.