Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in Java as shown below in Racket. | #lang racket
(define a 3+4i)
(define b 8+0i)
(+ a b)
(- a b)
(/ a b)
(* a b)
(- a)
(/ 1 a)
(conjugate a)
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Write a version of this Racket function in Python with identical behavior. | #lang racket
(define a 3+4i)
(define b 8+0i)
(+ a b)
(- a b)
(/ a b)
(* a b)
(- a)
(/ 1 a)
(conjugate a)
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Write the same code in Go as shown below in Racket. | #lang racket
(define a 3+4i)
(define b 8+0i)
(+ a b)
(- a b)
(/ a b)
(* a b)
(- a)
(/ 1 a)
(conjugate a)
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Transform the following COBOL implementation into C, maintaining the same output and logic. | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Translate this program into C# but keep the logic exactly as in COBOL. | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Convert the following code from COBOL to C++, ensuring the logic remains intact. | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Change the following COBOL code into Java without altering its purpose. | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Convert the following code from COBOL to Python, ensuring the logic remains intact. | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Port the provided COBOL code into Go while preserving the original functionality. | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Translate the given REXX code snippet into C without altering its behavior. | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Can you help me rewrite this code in C# instead of REXX, keeping it the same logically? | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Produce a functionally identical C++ code for the snippet given in REXX. | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Generate an equivalent Java version of this REXX code. | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Produce a language-to-language conversion: from REXX to Python, same semantics. | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Transform the following REXX implementation into Go, maintaining the same output and logic. | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Produce a language-to-language conversion: from Ruby to C, same semantics. |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Transform the following Ruby implementation into C#, maintaining the same output and logic. |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Change the following Ruby code into C++ without altering its purpose. |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Change the programming language of this snippet from Ruby to Java without modifying what it does. |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Generate a Python translation of this Ruby snippet without changing its computational steps. |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Convert this Ruby block to Go, preserving its control flow and logic. |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Ensure the translated C code behaves exactly like the original Scala snippet. | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Produce a language-to-language conversion: from Scala to C#, same semantics. | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Convert this Scala block to C++, preserving its control flow and logic. | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Write a version of this Scala function in Java with identical behavior. | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Ensure the translated Python code behaves exactly like the original Scala snippet. | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Preserve the algorithm and functionality while converting the code from Scala to Go. | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Port the following code from Swift to C with equivalent syntax and logic. | public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Complex = Complex(real: 0, imaginary: 0)
public var negate : Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert : Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate : Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
}
extension Complex : Equatable {}
public func == (left:Complex, right:Complex) -> Bool {
return left.real == right.real && left.imaginary == right.imaginary
}
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Write the same algorithm in C# as shown in this Swift implementation. | public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Complex = Complex(real: 0, imaginary: 0)
public var negate : Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert : Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate : Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
}
extension Complex : Equatable {}
public func == (left:Complex, right:Complex) -> Bool {
return left.real == right.real && left.imaginary == right.imaginary
}
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Please provide an equivalent version of this Swift code in C++. | public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Complex = Complex(real: 0, imaginary: 0)
public var negate : Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert : Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate : Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
}
extension Complex : Equatable {}
public func == (left:Complex, right:Complex) -> Bool {
return left.real == right.real && left.imaginary == right.imaginary
}
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Write the same code in Java as shown below in Swift. | public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Complex = Complex(real: 0, imaginary: 0)
public var negate : Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert : Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate : Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
}
extension Complex : Equatable {}
public func == (left:Complex, right:Complex) -> Bool {
return left.real == right.real && left.imaginary == right.imaginary
}
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Port the provided Swift code into Python while preserving the original functionality. | public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Complex = Complex(real: 0, imaginary: 0)
public var negate : Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert : Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate : Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
}
extension Complex : Equatable {}
public func == (left:Complex, right:Complex) -> Bool {
return left.real == right.real && left.imaginary == right.imaginary
}
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Produce a functionally identical Go code for the snippet given in Swift. | public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Complex = Complex(real: 0, imaginary: 0)
public var negate : Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert : Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate : Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
}
extension Complex : Equatable {}
public func == (left:Complex, right:Complex) -> Bool {
return left.real == right.real && left.imaginary == right.imaginary
}
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C. | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;
puts [tostring [* $a $b]] ;
puts [tostring [pow $a [complex -1 0]]] ;
puts [tostring [- $a]] ;
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Change the following Tcl code into C# without altering its purpose. | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;
puts [tostring [* $a $b]] ;
puts [tostring [pow $a [complex -1 0]]] ;
puts [tostring [- $a]] ;
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Translate the given Tcl code snippet into C++ without altering its behavior. | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;
puts [tostring [* $a $b]] ;
puts [tostring [pow $a [complex -1 0]]] ;
puts [tostring [- $a]] ;
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Convert this Tcl block to Java, preserving its control flow and logic. | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;
puts [tostring [* $a $b]] ;
puts [tostring [pow $a [complex -1 0]]] ;
puts [tostring [- $a]] ;
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Port the following code from Tcl to Python with equivalent syntax and logic. | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;
puts [tostring [* $a $b]] ;
puts [tostring [pow $a [complex -1 0]]] ;
puts [tostring [- $a]] ;
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Can you help me rewrite this code in Go instead of Tcl, keeping it the same logically? | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;
puts [tostring [* $a $b]] ;
puts [tostring [pow $a [complex -1 0]]] ;
puts [tostring [- $a]] ;
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Transform the following C implementation into Rust, maintaining the same output and logic. | #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
| extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
|
Port the following code from C# to Rust with equivalent syntax and logic. | namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
| extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
|
Keep all operations the same but rewrite the snippet in Rust. | public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
| extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
|
Change the programming language of this snippet from Rust to Python without modifying what it does. | extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Write the same code in Rust as shown below in C++. | #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
| extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
|
Port the following code from Go to Rust with equivalent syntax and logic. | package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
| extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
|
Preserve the algorithm and functionality while converting the code from Ada to C#. | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| 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.");
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C. | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Convert this Ada snippet to C++ and keep its semantics consistent. | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Rewrite the snippet below in Go so it works the same as the original Ada code. | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Generate an equivalent Java version of this Ada code. | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| 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());
}
}
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Can you help me rewrite this code in VB instead of Ada, keeping it the same logically? | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Directory_Entry_Type) is
begin
if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
Walk (Full_Name (Item), Pattern);
end if;
exception
when Name_Error => null;
end Walk;
begin
Search (Name, Pattern, (others => True), Print'Access);
Search (Name, "", (Directory => True, others => False), Walk'Access);
end Walk;
begin
Walk (".", "*.adb");
end Test_Directory_Walk;
| 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
|
Translate this program into C but keep the logic exactly as in Arturo. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Please provide an equivalent version of this Arturo code in C#. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| 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.");
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Write the same code in Java as shown below in Arturo. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| 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());
}
}
}
}
}
}
|
Convert this Arturo block to Python, preserving its control flow and logic. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Generate a VB translation of this Arturo snippet without changing its computational steps. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| 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
|
Generate a Go translation of this Arturo snippet without changing its computational steps. |
print list.recursive "."
select list.recursive "some/path"
=> [".md" = extract.extension]
select list.recursive "some/path"
=> [in? "test"]
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Change the following AutoHotKey code into C without altering its purpose. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Port the following code from AutoHotKey to C# with equivalent syntax and logic. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| 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.");
}
}
}
|
Write the same code in C++ as shown below in AutoHotKey. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Please provide an equivalent version of this AutoHotKey code in Java. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| 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());
}
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from AutoHotKey to Python. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Maintain the same structure and functionality when rewriting this code in VB. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| 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
|
Translate this program into Go but keep the logic exactly as in AutoHotKey. | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Preserve the algorithm and functionality while converting the code from BBC_Basic to C. | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Change the following BBC_Basic code into C# without altering its purpose. | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| 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.");
}
}
}
|
Ensure the translated C++ code behaves exactly like the original BBC_Basic snippet. | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Keep all operations the same but rewrite the snippet in Java. | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| 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());
}
}
}
}
}
}
|
Convert this BBC_Basic block to Python, preserving its control flow and logic. | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Write the same code in VB as shown below in BBC_Basic. | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| 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
|
Can you help me rewrite this code in Go instead of BBC_Basic, keeping it the same logically? | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
SYS "FindFirstFile", dir$ + "*", dir% TO sh%
IF sh% <> -1 THEN
REPEAT
IF (!dir% AND 16) IF dir%?44 <> &2E THEN
PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
ENDIF
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Write the same code in C as shown below in Clojure. | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| 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.");
}
}
}
|
Change the programming language of this snippet from Clojure to C++ without modifying what it does. | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Can you help me rewrite this code in Java instead of Clojure, keeping it the same logically? | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| 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());
}
}
}
}
}
}
|
Convert this Clojure block to Python, preserving its control flow and logic. | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Convert the following code from Clojure to VB, ensuring the logic remains intact. | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| 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
|
Port the provided Clojure code into Go while preserving the original functionality. | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Transform the following Common_Lisp implementation into C, maintaining the same output and logic. | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Common_Lisp. | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| 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.");
}
}
}
|
Write the same algorithm in C++ as shown in this Common_Lisp implementation. | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Write the same code in Java as shown below in Common_Lisp. | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| 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());
}
}
}
}
}
}
|
Can you help me rewrite this code in Python instead of Common_Lisp, keeping it the same logically? | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Convert the following code from Common_Lisp to VB, ensuring the logic remains intact. | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| 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
|
Keep all operations the same but rewrite the snippet in Go. | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn entry))))
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Produce a language-to-language conversion: from D to C, same semantics. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Ensure the translated C# code behaves exactly like the original D snippet. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| 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 provided D code into C++ while preserving the original functionality. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Write a version of this D function in Java with identical behavior. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| 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());
}
}
}
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the D version. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Generate a VB translation of this D snippet without changing its computational steps. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| 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
|
Translate the given D code snippet into Go without altering its behavior. | void main() {
import std.stdio, std.file;
dirEntries("", "*.d", SpanMode.breadth).writeln;
}
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Change the programming language of this snippet from Delphi to C without modifying what it does. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Write a version of this Delphi function in C# with identical behavior. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| 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.");
}
}
}
|
Please provide an equivalent version of this Delphi code in C++. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Convert this Delphi snippet to Java and keep its semantics consistent. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| 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());
}
}
}
}
}
}
|
Write a version of this Delphi function in Python with identical behavior. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Preserve the algorithm and functionality while converting the code from Delphi to VB. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.