Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, " : x y")
fmt.Printf("Mean : %7.4f, %7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
}
| import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, " : x y")
fmt.Printf("Mean : %7.4f, %7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
}
| import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import "fmt"
import "io/ioutil"
import "log"
import "os"
import "regexp"
import "strings"
func main() {
err := fix()
if err != nil {
log.Fatalln(err)
}
}
func fix() (err error) {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
out, err := Lang(string(buf))
if err != nil {
return err
}
fmt.Println(out)
return nil
}
func Lang(in string) (out string, err error) {
reg := regexp.MustCompile("<[^>]+>")
out = reg.ReplaceAllStringFunc(in, repl)
return out, nil
}
func repl(in string) (out string) {
if in == "</code>" {
return "</"+"lang>"
}
mid := in[1 : len(in)-1]
var langs = []string{
"abap", "actionscript", "actionscript3", "ada", "apache", "applescript",
"apt_sources", "asm", "asp", "autoit", "avisynth", "bash", "basic4gl",
"bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm",
"cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi",
"diff", "_div", "dos", "dot", "eiffel", "email", "fortran", "freebasic",
"genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell",
"hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java",
"java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
"lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k",
"make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis",
"objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal",
"per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql",
"povray", "powershell", "progress", "prolog", "providex", "python",
"qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme",
"scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog",
"vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch",
"xml", "xorg_conf", "xpp", "z80",
}
for _, lang := range langs {
if mid == lang {
return fmt.Sprintf("<lang %s>", lang)
}
if strings.HasPrefix(mid, "/") {
if mid[len("/"):] == lang {
return "</"+"lang>"
}
}
if strings.HasPrefix(mid, "code ") {
if mid[len("code "):] == lang {
return fmt.Sprintf("<lang %s>", lang)
}
}
}
return in
}
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FixCodeTags
{
public static void main(String[] args)
{
String sourcefile=args[0];
String convertedfile=args[1];
convert(sourcefile,convertedfile);
}
static String[] languages = {"abap", "actionscript", "actionscript3",
"ada", "apache", "applescript", "apt_sources", "asm", "asp",
"autoit", "avisynth", "bar", "bash", "basic4gl", "bf",
"blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg",
"cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css",
"d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email",
"foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml",
"gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict",
"idl", "ini", "inno", "intercal", "io", "java", "java5",
"javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
"lolcode", "lotusformulas", "lotusscript", "lscript", "lua",
"m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml",
"mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas",
"oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief",
"pic16", "pixelbender", "plsql", "povray", "powershell",
"progress", "prolog", "providex", "python", "qbasic", "rails",
"reg", "robots", "ruby", "sas", "scala", "scheme", "scilab",
"sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet",
"verilog", "vhdl", "vim", "visualfoxpro", "visualprolog",
"whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"};
static void convert(String sourcefile,String convertedfile)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(sourcefile));
StringBuffer sb=new StringBuffer("");
String line;
while((line=br.readLine())!=null)
{
for(int i=0;i<languages.length;i++)
{
String lang=languages[i];
line=line.replaceAll("<"+lang+">", "<lang "+lang+">");
line=line.replaceAll("</"+lang+">", "</"+"lang>");
line=line.replaceAll("<code "+lang+">", "<lang "+lang+">");
line=line.replaceAll("</code>", "</"+"lang>");
}
sb.append(line);
}
br.close();
FileWriter fw=new FileWriter(new File(convertedfile));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
| import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
| import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
|
Write a version of this Go function in Java with identical behavior. | package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
| import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"encoding/json"
"log"
"os"
"bytes"
"errors"
"strings"
)
type s1 struct {
A string
B string
C int
D string
}
type s2 struct {
A string
C intString
X string
}
type intString string
func (i *intString) UnmarshalJSON(b []byte) error {
if len(b) == 0 || bytes.IndexByte([]byte("0123456789-"), b[0]) < 0 {
return errors.New("Unmarshal intString expected JSON number")
}
*i = intString(b)
return nil
}
func NewS2() *s2 {
return &s2{X: "XXXXX"}
}
func main() {
o1, err := os.Create("o1.json")
if err != nil {
log.Fatal(err)
}
e := json.NewEncoder(o1)
for i := 1; i <= 5; i++ {
err := e.Encode(s1{
strings.Repeat("A", i),
strings.Repeat("B", i),
i,
strings.Repeat("D", i),
})
if err != nil {
log.Fatal(err)
}
}
o1.Close()
in, err := os.Open("o1.json")
if err != nil {
log.Fatal(err)
}
out, err := os.Create("out.json")
if err != nil {
log.Fatal(err)
}
d := json.NewDecoder(in)
e = json.NewEncoder(out)
for d.More() {
s := NewS2()
if err = d.Decode(s); err != nil {
log.Fatal(err)
}
if err = e.Encode(s); err != nil {
log.Fatal(err)
}
}
}
| import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class CopysJ {
public static void main(String[] args) {
String ddname_IN = "copys.in.txt";
String ddname_OUT = "copys.out.txt";
if (args.length >= 1) { ddname_IN = args[0].length() > 0 ? args[0] : ddname_IN; }
if (args.length >= 2) { ddname_OUT = args[1].length() > 0 ? args[1] : ddname_OUT; }
File dd_IN = new File(ddname_IN);
File dd_OUT = new File(ddname_OUT);
try (
Scanner scanner_IN = new Scanner(dd_IN);
BufferedWriter writer_OUT = new BufferedWriter(new FileWriter(dd_OUT))
) {
String a;
String b;
String c;
String d;
String c1;
String x = "XXXXX";
String data_IN;
String data_OUT;
int ib;
while (scanner_IN.hasNextLine()) {
data_IN = scanner_IN.nextLine();
ib = 0;
a = data_IN.substring(ib, ib += 5);
b = data_IN.substring(ib, ib += 5);
c = data_IN.substring(ib, ib += 4);
c1=Integer.toHexString(new Byte((c.getBytes())[0]).intValue());
if (c1.length()<2) { c1="0" + c1; }
data_OUT = a + c1 + x;
writer_OUT.write(data_OUT);
writer_OUT.newLine();
System.out.println(data_IN);
System.out.println(data_OUT);
System.out.println();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"fmt"
"go/ast"
"go/parser"
"strings"
"unicode"
)
func isValidIdentifier(identifier string) bool {
node, err := parser.ParseExpr(identifier)
if err != nil {
return false
}
ident, ok := node.(*ast.Ident)
return ok && ident.Name == identifier
}
type runeRanges struct {
ranges []string
hasStart bool
start rune
end rune
}
func (r *runeRanges) add(cp rune) {
if !r.hasStart {
r.hasStart = true
r.start = cp
r.end = cp
return
}
if cp == r.end+1 {
r.end = cp
return
}
r.writeTo(&r.ranges)
r.start = cp
r.end = cp
}
func (r *runeRanges) writeTo(ranges *[]string) {
if r.hasStart {
if r.start == r.end {
*ranges = append(*ranges, fmt.Sprintf("%U", r.end))
} else {
*ranges = append(*ranges, fmt.Sprintf("%U-%U", r.start, r.end))
}
}
}
func (r *runeRanges) String() string {
ranges := r.ranges
r.writeTo(&ranges)
return strings.Join(ranges, ", ")
}
func main() {
var validFirst runeRanges
var validFollow runeRanges
var validOnlyFollow runeRanges
for r := rune(0); r <= unicode.MaxRune; r++ {
first := isValidIdentifier(string([]rune{r}))
follow := isValidIdentifier(string([]rune{'_', r}))
if first {
validFirst.add(r)
}
if follow {
validFollow.add(r)
}
if follow && !first {
validOnlyFollow.add(r)
}
}
_, _ = fmt.Println("Valid first:", validFirst.String())
_, _ = fmt.Println("Valid follow:", validFollow.String())
_, _ = fmt.Println("Only follow:", validOnlyFollow.String())
}
| import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws Exception {
print("Java Identifier start: ", 0, 0x10FFFF, 72,
Character::isJavaIdentifierStart, "%c");
print("Java Identifier part: ", 0, 0x10FFFF, 25,
Character::isJavaIdentifierPart, "[%d]");
print("Identifier ignorable: ", 0, 0x10FFFF, 25,
Character::isIdentifierIgnorable, "[%d]");
print("Unicode Identifier start: ", 0, 0x10FFFF, 72,
Character::isUnicodeIdentifierStart, "%c");
print("Unicode Identifier part : ", 0, 0x10FFFF, 25,
Character::isUnicodeIdentifierPart, "[%d]");
}
static void print(String msg, int start, int end, int limit,
IntPredicate p, String fmt) {
System.out.print(msg);
IntStream.rangeClosed(start, end)
.filter(p)
.limit(limit)
.forEach(cp -> System.out.printf(fmt, cp));
System.out.println("...");
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
| (...)
int feedForward(double[] inputs) {
assert inputs.length == weights.length : "weights and input length mismatch";
double sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += inputs[i] * weights[i];
}
return activate(sum);
}
(...)
|
Ensure the translated Java code behaves exactly like the original Go snippet. | func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
| (...)
int feedForward(double[] inputs) {
assert inputs.length == weights.length : "weights and input length mismatch";
double sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += inputs[i] * weights[i];
}
return activate(sum);
}
(...)
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"os"
"regexp"
"strconv"
)
var (
rl1 = 'a'
rl2 = '\''
)
var (
is1 = "abc"
is2 = "\"ab\tc\""
)
var (
rs1 = `
first"
second'
third"
`
rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.`
rs3 = `\d+`
)
func main() {
fmt.Println(rl1, rl2)
fmt.Println(is1, is2)
fmt.Println(rs1)
fmt.Println(rs2)
re := regexp.MustCompile(rs3)
fmt.Println(re.FindString("abcd1234efgh"))
n := 3
fmt.Printf("\nThere are %d quoting constructs in Go.\n", n)
s := "constructs"
fmt.Println("There are", n, "quoting", s, "in Go.")
mapper := func(placeholder string) string {
switch placeholder {
case "NUMBER":
return strconv.Itoa(n)
case "TYPES":
return s
}
return ""
}
fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper))
}
| module test
{
@Inject Console console;
void run()
{
Char ch = 'x';
console.print( $"ch={ch.quoted()}");
String greeting = "Hello";
console.print( $"greeting={greeting.quoted()}");
String lines = \|first line
|second line\
| continued
;
console.print($|lines=
|{lines}
);
String name = "Bob";
String msg = $|{greeting} {name},
|Have a nice day!
|{ch}{ch}{ch}
;
console.print($|msg=
|{msg}
);
}
}
|
Ensure the translated C# code behaves exactly like the original Python snippet. |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
| using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
|
Translate this program into C# but keep the logic exactly as in Python. | def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0
| using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
|
Change the following Python code into C# without altering its purpose. | def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0
| using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| using System;
static class YCombinator<T, TResult>
{
private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);
public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}
static class Program
{
static void Main()
{
var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));
Console.WriteLine(fac(10));
Console.WriteLine(fib(10));
}
}
|
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
|
Generate an equivalent C# version of this Python code. | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
|
Write a version of this Python function in C# with identical behavior. | for i in range(1, 11):
if i % 5 == 0:
print(i)
continue
print(i, end=', ')
| using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
| using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. |
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:
| namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | s = "alphaBETA"
print s.upper()
print s.lower()
print s.swapcase()
print "fOo bAR".capitalize()
print "fOo bAR".title()
import string
print string.capwords("fOo bAR")
| using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
|
Produce a language-to-language conversion: from Python to C#, same semantics. | >>> import hashlib
>>>
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>
| using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
|
Translate this program into C# but keep the logic exactly as in Python. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
|
Produce a language-to-language conversion: from Python to C#, same semantics. | from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
if sleepsort(x) == sorted(x):
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. | from random import randint
def do_scan(mat):
for row in mat:
for item in row:
print item,
if item == 20:
print
return
print
print
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
| using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}
|
Produce a functionally identical C# code for the snippet given in Python. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
|
Change the programming language of this snippet from Python to C# without modifying what it does. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
|
Please provide an equivalent version of this Python code in C#. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
|
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek();
top = stack.Pop();
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek();
top = stack.Pop();
|
Write the same algorithm in C# as shown in this Python implementation. | from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
Ensure the translated C# code behaves exactly like the original Python snippet. | from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
Translate this program into C# but keep the logic exactly as in Python. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
|
Convert this Python snippet to C# and keep its semantics consistent. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. |
from math import log
def getDigit(num, base, digit_num):
return (num // base ** digit_num) % base
def makeBlanks(size):
return [ [] for i in range(size) ]
def split(a_list, base, digit_num):
buckets = makeBlanks(base)
for num in a_list:
buckets[getDigit(num, base, digit_num)].append(num)
return buckets
def merge(a_list):
new_list = []
for sublist in a_list:
new_list.extend(sublist)
return new_list
def maxAbs(a_list):
return max(abs(num) for num in a_list)
def split_by_sign(a_list):
buckets = [[], []]
for num in a_list:
if num < 0:
buckets[0].append(num)
else:
buckets[1].append(num)
return buckets
def radixSort(a_list, base):
passes = int(round(log(maxAbs(a_list), base)) + 1)
new_list = list(a_list)
for digit_num in range(passes):
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
| using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
|
Produce a functionally identical C# code for the snippet given in Python. | [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Convert this Python snippet to C# and keep its semantics consistent. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| class SelectionSort<T> where T : IComparable {
public T[] Sort(T[] list) {
int k;
T temp;
for (int i = 0; i < list.Length; i++) {
k = i;
for (int j=i + 1; j < list.Length; j++) {
if (list[j].CompareTo(list[k]) < 0) {
k = j;
}
}
temp = list[i];
list[i] = list[k];
list[k] = temp;
}
return list;
}
}
|
Please provide an equivalent version of this Python code in C#. | def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
| int[] intArray = { 1, 2, 3, 4, 5 };
int[] squares1 = intArray.Select(x => x * x).ToArray();
int[] squares2 = (from x in intArray
select x * x).ToArray();
foreach (var i in intArray)
Console.WriteLine(i * i);
|
Port the provided Python code into C# while preserving the original functionality. | >>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
| public sealed class Singleton1
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
| using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | for i in xrange(10, -1, -1):
print i
| for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
|
Generate an equivalent C# version of this Python code. | with open(filename, 'w') as f:
f.write(data)
| System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
|
Produce a language-to-language conversion: from Python to C#, same semantics. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| using System;
class Program {
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
|
Write a version of this Python function in C# with identical behavior. | def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main() {
var sequence = new[] { "A", "B", "C", "D" };
foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i])));
}
}
static IEnumerable<List<int>> Subsets(int length) {
int[] values = Enumerable.Range(0, length).ToArray();
var stack = new Stack<int>(length);
for (int i = 0; stack.Count > 0 || i < length; ) {
if (i < length) {
stack.Push(i++);
yield return (from index in stack.Reverse() select values[index]).ToList();
} else {
i = stack.Pop() + 1;
if (stack.Count > 0) i = stack.Pop() + 1;
}
}
}
static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main() {
var sequence = new[] { "A", "B", "C", "D" };
foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i])));
}
}
static IEnumerable<List<int>> Subsets(int length) {
int[] values = Enumerable.Range(0, length).ToArray();
var stack = new Stack<int>(length);
for (int i = 0; stack.Count > 0 || i < length; ) {
if (i < length) {
stack.Push(i++);
yield return (from index in stack.Reverse() select values[index]).ToList();
} else {
i = stack.Pop() + 1;
if (stack.Count > 0) i = stack.Pop() + 1;
}
}
}
static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;
}
|
Generate an equivalent C# version of this Python code. | primes = [2, 3, 5, 7, 11, 13, 17, 19]
def count_twin_primes(limit: int) -> int:
global primes
if limit > primes[-1]:
ram_limit = primes[-1] + 90000000 - len(primes)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1
while reasonable_limit < limit:
ram_limit = primes[-1] + 90000000 - len(primes)
if ram_limit > primes[-1]:
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
else:
reasonable_limit = min(limit, primes[-1] ** 2)
sieve = list({x for prime in primes for x in
range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})
primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]
count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])
return count
def test(limit: int):
count = count_twin_primes(limit)
print(f"Number of twin prime pairs less than {limit} is {count}\n")
test(10)
test(100)
test(1000)
test(10000)
test(100000)
test(1000000)
test(10000000)
test(100000000)
| using System;
class Program {
static uint[] res = new uint[10];
static uint ri = 1, p = 10, count = 0;
static void TabulateTwinPrimes(uint bound) {
if (bound < 5) return; count++;
uint cl = (bound - 1) >> 1, i = 1, j,
limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
var comp = new bool[cl]; bool lp;
for (j = 3; j < cl; j += 3) comp[j] = true;
while (i < limit) {
if (lp = !comp[i]) {
uint pr = (i << 1) + 3;
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
if (!comp[++i]) {
uint pr = (i << 1) + 3;
if (lp) {
if (pr > p) {
res[ri++] = count;
p *= 10;
}
count++;
i++;
}
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
}
cl--;
while (i < cl) {
lp = !comp[i++];
if (!comp[i] && lp) {
if ((i++ << 1) + 3 > p) {
res[ri++] = count;
p *= 10;
}
count++;
}
}
res[ri] = count;
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
TabulateTwinPrimes(1_000_000_000);
sw.Stop();
p = 1;
for (var j = 1; j <= ri; j++)
Console.WriteLine(fmt, res[j], p *= 10);
Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
}
}
|
Produce a functionally identical C# code for the snippet given in Python. | import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f' % self.real if not self.pureImag() else ''
ip = '%7.5fj' % self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.0' if (
self.pureImag() and self.pureReal()
) else rp + conj + ip
def pureImag(self):
return abs(self.real) < 0.000005
def pureReal(self):
return abs(self.imag) < 0.000005
def croots(n):
if n <= 0:
return None
return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
for nr in range(2, 11):
print(nr, list(croots(nr)))
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
class Program
{
static IEnumerable<Complex> RootsOfUnity(int degree)
{
return Enumerable
.Range(0, degree)
.Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
}
static void Main()
{
var degree = 3;
foreach (var root in RootsOfUnity(degree))
{
Console.WriteLine(root);
}
}
}
|
Translate this program into C# but keep the logic exactly as in Python. |
print 2**64*2**64
| using System;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static decimal mx = 1E28M, hm = 1E14M, a;
struct bi { public decimal hi, lo; }
static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }
static string toStr(bi a, bool comma = false) {
string r = a.hi == 0 ? string.Format("{0:0}", a.lo) :
string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo);
if (!comma) return r; string rc = "";
for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc;
return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }
static decimal Pow_dec(decimal bas, uint exp) {
if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
if ((exp & 1) == 0) return tmp; return tmp * bas; }
static void Main(string[] args) {
for (uint p = 64; p < 95; p += 30) {
bi x = set4sq(a = Pow_dec(2M, p)), y;
WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2);
y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;
a = x.hi * x.lo * 2M;
y.hi += Math.Floor(a / hm);
y.lo += (a % hm) * hm;
while (y.lo > mx) { y.lo -= mx; y.hi++; }
WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true),
BS.ToString() == toStr(y) ? "does" : "fails to"); } }
}
|
Ensure the translated C# code behaves exactly like the original Python snippet. | import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y) // z
r = (x + y) // z
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a - n * b * b == 1:
return a, b
for n in [61, 109, 181, 277]:
x, y = solvePell(n)
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
| using System;
using System.Numerics;
static class Program
{
static void Fun(ref BigInteger a, ref BigInteger b, int c)
{
BigInteger t = a; a = b; b = b * c + t;
}
static void SolvePell(int n, ref BigInteger a, ref BigInteger b)
{
int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;
BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;
while (true)
{
y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;
Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);
if (a * a - n * b * b == 1) return;
}
}
static void Main()
{
BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })
{
SolvePell(n, ref x, ref y);
Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y);
}
}
}
|
Translate the given Python code snippet into C# without altering its behavior. |
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
print % (size, size)
guesses = 0
while True:
guesses += 1
while True:
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)
| using System;
namespace BullsnCows
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
KnuthShuffle<int>(ref nums);
int[] chosenNum = new int[4];
Array.Copy(nums, chosenNum, 4);
Console.WriteLine("Your Guess ?");
while (!game(Console.ReadLine(), chosenNum))
{
Console.WriteLine("Your next Guess ?");
}
Console.ReadKey();
}
public static void KnuthShuffle<T>(ref T[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(array.Length);
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}
public static bool game(string guess, int[] num)
{
char[] guessed = guess.ToCharArray();
int bullsCount = 0, cowsCount = 0;
if (guessed.Length != 4)
{
Console.WriteLine("Not a valid guess.");
return false;
}
for (int i = 0; i < 4; i++)
{
int curguess = (int) char.GetNumericValue(guessed[i]);
if (curguess < 1 || curguess > 9)
{
Console.WriteLine("Digit must be ge greater 0 and lower 10.");
return false;
}
if (curguess == num[i])
{
bullsCount++;
}
else
{
for (int j = 0; j < 4; j++)
{
if (curguess == num[j])
cowsCount++;
}
}
}
if (bullsCount == 4)
{
Console.WriteLine("Congratulations! You have won!");
return true;
}
else
{
Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
return false;
}
}
}
}
|
Port the following code from Python to C# with equivalent syntax and logic. | def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
| using System;
using System.Collections.Generic;
namespace RosettaCode.BubbleSort
{
public static class BubbleSortMethods
{
public static void BubbleSort<T>(this List<T> list) where T : IComparable
{
bool madeChanges;
int itemCount = list.Count;
do
{
madeChanges = false;
itemCount--;
for (int i = 0; i < itemCount; i++)
{
if (list[i].CompareTo(list[i + 1]) > 0)
{
T temp = list[i + 1];
list[i + 1] = list[i];
list[i] = temp;
madeChanges = true;
}
}
} while (madeChanges);
}
}
class Program
{
static void Main()
{
List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
testList.BubbleSort();
foreach (var t in testList) Console.Write(t + " ");
}
}
}
|
Translate the given Python code snippet into C# without altering its behavior. | import shutil
shutil.copyfile('input.txt', 'output.txt')
| using System;
using System.IO;
namespace FileIO
{
class Program
{
static void Main()
{
String s = scope .();
File.ReadAllText("input.txt", s);
File.WriteAllText("output.txt", s);
}
}
}
|
Write a version of this Python function in C# with identical behavior. | x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)
print "Remainder: %d" % (x % y)
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
raw_input( )
| using System;
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(args[0]);
int b = Convert.ToInt32(args[1]);
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
Console.WriteLine("{0} % {1} = {2}", a, b, a % b);
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
| using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
double[,] t = Transpose( m );
for( int i=0; i<t.GetLength(0); i++ )
{
for( int j=0; j<t.GetLength(1); j++ )
Console.Write( t[i,j] + " " );
Console.WriteLine("");
}
}
public static double[,] Transpose( double[,] m )
{
double[,] t = new double[m.GetLength(1),m.GetLength(0)];
for( int i=0; i<m.GetLength(0); i++ )
for( int j=0; j<m.GetLength(1); j++ )
t[j,i] = m[i,j];
return t;
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. |
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Ensure the translated C# code behaves exactly like the original Python snippet. | >>> def a(answer):
print("
return answer
>>> def b(answer):
print("
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
| using System;
class Program
{
static bool a(bool value)
{
Console.WriteLine("a");
return value;
}
static bool b(bool value)
{
Console.WriteLine("b");
return value;
}
static void Main()
{
foreach (var i in new[] { false, true })
{
foreach (var j in new[] { false, true })
{
Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
Console.WriteLine();
Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
Console.WriteLine();
}
}
}
}
|
Port the following code from Python to C# with equivalent syntax and logic. | import sys
print(sys.getrecursionlimit())
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. | import sys
print(sys.getrecursionlimit())
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Write a version of this Python function in C# with identical behavior. | black = color(0)
white = color(255)
def setup():
size(320, 240)
def draw():
loadPixels()
for i in range(len(pixels)):
if random(1) < 0.5:
pixels[i] = black
else:
pixels[i] = white
updatePixels()
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frameRate, 5, 15)
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
static PictureBox pb;
static BackgroundWorker worker;
static double time = 0;
static double frames = 0;
static Random rand = new Random();
static byte tmp;
static byte white = 255;
static byte black = 0;
static int halfmax = int.MaxValue / 2;
static IEnumerable<byte> YieldVodoo()
{
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white;
yield return tmp;
yield return tmp;
yield return tmp;
}
}
static Image Randimg()
{
var bitmap = new Bitmap(size.Width, size.Height);
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(
YieldVodoo().ToArray<byte>(),
0,
data.Scan0,
numbytes);
bitmap.UnlockBits(data);
return bitmap;
}
[STAThread]
static void Main()
{
var form = new Form();
form.AutoSize = true;
form.Size = new Size(0, 0);
form.Text = "Test";
form.FormClosed += delegate
{
Application.Exit();
};
worker = new BackgroundWorker();
worker.DoWork += delegate
{
System.Threading.Thread.Sleep(500);
while (true)
{
var a = DateTime.Now;
pb.Image = Randimg();
var b = DateTime.Now;
time += (b - a).TotalSeconds;
frames += 1;
if (frames == 30)
{
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
time = 0;
frames = 0;
}
}
};
worker.RunWorkerAsync();
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
pb = new PictureBox();
pb.Size = size;
flp.AutoSize = true;
flp.Controls.Add(pb);
form.Show();
Application.Run();
}
}
|
Port the following code from Python to C# with equivalent syntax and logic. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| static void Main(string[] args)
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
for (int x = 0; x < 33550337; x++)
{
if (IsPerfect(x))
Console.WriteLine(x + " is perfect.");
}
Console.ReadLine();
}
static bool IsPerfect(int num)
{
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
sum += i;
}
return sum == num ;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | >>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
| using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
Console.WriteLine("n digits = {0}", result.Length);
}
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. |
from pprint import pprint as pp
from glob import glob
try: reduce
except: from functools import reduce
try: raw_input
except: raw_input = input
def parsetexts(fileglob='InvertedIndex/T*.txt'):
texts, words = {}, set()
for txtfile in glob(fileglob):
with open(txtfile, 'r') as f:
txt = f.read().split()
words |= set(txt)
texts[txtfile.split('\\')[-1]] = txt
return texts, words
def termsearch(terms):
return reduce(set.intersection,
(invindex[term] for term in terms),
set(texts.keys()))
texts, words = parsetexts()
print('\nTexts')
pp(texts)
print('\nWords')
pp(sorted(words))
invindex = {word:set(txt
for txt, wrds in texts.items() if word in wrds)
for word in words}
print('\nInverted Index')
pp({k:sorted(v) for k,v in invindex.items()})
terms = ["what", "is", "it"]
print('\nTerm Search for: ' + repr(terms))
pp(sorted(termsearch(terms)))
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class InvertedIndex
{
static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
{
return dictionary
.SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))
.GroupBy(keyValuePair => keyValuePair.Key)
.ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));
}
static void Main()
{
Console.Write("files: ");
var files = Console.ReadLine();
Console.Write("find: ");
var find = Console.ReadLine();
var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());
Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find]));
}
}
|
Generate an equivalent C# version of this Python code. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
|
Write the same algorithm in C# as shown in this Python implementation. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
|
Port the provided Python code into C# while preserving the original functionality. | from random import randrange
while True:
a = randrange(20)
print(a)
if a == 10:
break
b = randrange(20)
print(b)
| class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
}
|
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | def water_collected(tower):
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
for n in range(N)]
print("highest_left: ", highest_left)
print("highest_right: ", highest_right)
print("water_level: ", water_level)
print("tower_level: ", tower)
print("total_water: ", sum(water_level))
print("")
return sum(water_level)
towers = [[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
[water_collected(tower) for tower in towers]
| class Program
{
static void Main(string[] args)
{
int[][] wta = {
new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};
string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " ";
for (int i = 0; i < wta.Length; i++)
{
int bpf; blk = ""; do
{
string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
{
if (wta[i][j] > 0)
{ floor += tb; wta[i][j] -= 1; bpf += 1; }
else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
}
if (bpf > 0) blk = floor + lf + blk;
} while (bpf > 0);
while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
if (args.Length > 0) System.Console.Write("\n{0}", blk);
System.Console.WriteLine("Block {0} retains {1,2} water units.",
i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
}
}
}
|
Translate this program into C# but keep the logic exactly as in Python. | from sympy import isprime
def descending(xs=range(10)):
for x in xs:
yield x
yield from descending(x*10 + d for d in range(x%10))
for i, p in enumerate(sorted(filter(isprime, descending()))):
print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')
print()
| using System;
class Program {
static bool ispr(uint n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (uint j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
static void Main(string[] args) {
uint c = 0; int nc;
var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var nxt = new uint[128];
while (true) {
nc = 0;
foreach (var a in ps) {
if (ispr(a))
Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " ");
for (uint b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) {
Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }
else break;
}
Console.WriteLine("\n{0} descending primes found", c);
}
}
|
Produce a functionally identical C# code for the snippet given in Python. | from sympy import isprime
def descending(xs=range(10)):
for x in xs:
yield x
yield from descending(x*10 + d for d in range(x%10))
for i, p in enumerate(sorted(filter(isprime, descending()))):
print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')
print()
| using System;
class Program {
static bool ispr(uint n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (uint j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
static void Main(string[] args) {
uint c = 0; int nc;
var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var nxt = new uint[128];
while (true) {
nc = 0;
foreach (var a in ps) {
if (ispr(a))
Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " ");
for (uint b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) {
Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }
else break;
}
Console.WriteLine("\n{0} descending primes found", c);
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. |
from collections import Counter
def decompose_sum(s):
return [(a,s-a) for a in range(2,int(s/2+1))]
all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)
product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_pairs = [(a,b) for a,b in all_pairs if
all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]
product_counts = Counter(c*d for c,d in s_pairs)
p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]
sum_counts = Counter(c+d for c,d in p_pairs)
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]
print(final_pairs)
| using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const int maxSum = 100;
var pairs = (
from X in 2.To(maxSum / 2 - 1)
from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
select new { X, Y, S = X + Y, P = X * Y }
).ToHashSet();
Console.WriteLine(pairs.Count);
var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
foreach (var pair in pairs) Console.WriteLine(pair);
}
}
public static class Extensions
{
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i <= end; i++) yield return i;
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}
|
Translate this program into C# but keep the logic exactly as in Python. | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(prec=9, assoc=L),
')': OpInfo(prec=0, assoc=L),
}
NUM, LPAREN, RPAREN = 'NUMBER ( )'.split()
def get_input(inp = None):
'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
tokenvals = []
for token in tokens:
if token in ops:
tokenvals.append((token, ops[token]))
else:
tokenvals.append((NUM, token))
return tokenvals
def shunting(tokenvals):
outq, stack = [], []
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
for token, val in tokenvals:
note = action = ''
if token is NUM:
action = 'Add number to output'
outq.append(val)
table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
elif token in ops:
t1, (p1, a1) = token, val
v = t1
note = 'Pop ops from stack to output'
while stack:
t2, (p2, a2) = stack[-1]
if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):
if t1 != RPAREN:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
break
else:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
stack.pop()
action = '(Pop & discard "(")'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
break
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
else:
note = ''
break
note = ''
note = ''
if t1 != RPAREN:
stack.append((token, val))
action = 'Push op token to stack'
else:
action = 'Discard ")"'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
note = 'Drain stack to output'
while stack:
v = ''
t2, (p2, a2) = stack[-1]
action = '(Pop op)'
stack.pop()
outq.append(t2)
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
return table
if __name__ == '__main__':
infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print( 'For infix expression: %r\n' % infix )
rp = shunting(get_input(infix))
maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output RPN is: %r' % rp[-1][2])
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
Console.WriteLine(infix.ToPostfix());
}
}
public static class ShuntingYard
{
private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
= new (string symbol, int precedence, bool rightAssociative) [] {
("^", 4, true),
("*", 3, false),
("/", 3, false),
("+", 2, false),
("-", 2, false)
}.ToDictionary(op => op.symbol);
public static string ToPostfix(this string infix) {
string[] tokens = infix.Split(' ');
var stack = new Stack<string>();
var output = new List<string>();
foreach (string token in tokens) {
if (int.TryParse(token, out _)) {
output.Add(token);
Print(token);
} else if (operators.TryGetValue(token, out var op1)) {
while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
int c = op1.precedence.CompareTo(op2.precedence);
if (c < 0 || !op1.rightAssociative && c <= 0) {
output.Add(stack.Pop());
} else {
break;
}
}
stack.Push(token);
Print(token);
} else if (token == "(") {
stack.Push(token);
Print(token);
} else if (token == ")") {
string top = "";
while (stack.Count > 0 && (top = stack.Pop()) != "(") {
output.Add(top);
}
if (top != "(") throw new ArgumentException("No matching left parenthesis.");
Print(token);
}
}
while (stack.Count > 0) {
var top = stack.Pop();
if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
output.Add(top);
}
Print("pop");
return string.Join(" ", output);
void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
}
}
|
Write the same code in C# as shown below in Python. | >>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
mid = length // 2
return s[mid-1:mid+2]
>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x in passing + failing:
try:
answer = middle_three_digits(x)
except AssertionError as error:
answer = error
print("middle_three_digits(%s) returned: %r" % (x, answer))
middle_three_digits(123) returned: '123'
middle_three_digits(12345) returned: '234'
middle_three_digits(1234567) returned: '345'
middle_three_digits(987654321) returned: '654'
middle_three_digits(10001) returned: '000'
middle_three_digits(-10001) returned: '000'
middle_three_digits(-123) returned: '123'
middle_three_digits(-100) returned: '100'
middle_three_digits(100) returned: '100'
middle_three_digits(-12345) returned: '234'
middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>>
| using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
| using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static List<int> l = new List<int>() { 1, 1 };
static int gcd(int a, int b) {
return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }
static void Main(string[] args) {
int max = 1000; int take = 15; int i = 1;
int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
while (l.Count < max || l[l.Count - 2] != selection.Last());
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
foreach (int ii in selection) {
int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
Console.WriteLine(); bool good = true;
for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" +
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
}
|
Produce a language-to-language conversion: from Python to C#, same semantics. | def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
| using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static List<int> l = new List<int>() { 1, 1 };
static int gcd(int a, int b) {
return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }
static void Main(string[] args) {
int max = 1000; int take = 15; int i = 1;
int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
while (l.Count < max || l[l.Count - 2] != selection.Last());
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
foreach (int ii in selection) {
int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
Console.WriteLine(); bool good = true;
for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" +
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
}
|
Convert this Python block to C#, preserving its control flow and logic. | class Doc(object):
def method(self, num):
pass
|
public static class XMLSystem
{
static XMLSystem()
{
}
public static XmlDocument GetXML(string name)
{
return null;
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | from collections import namedtuple
import math
Circle = namedtuple('Circle', 'x, y, r')
def solveApollonius(c1, c2, c3, s1, s2, s3):
x1, y1, r1 = c1
x2, y2, r2 = c2
x3, y3, r3 = c3
v11 = 2*x2 - 2*x1
v12 = 2*y2 - 2*y1
v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2
v14 = 2*s2*r2 - 2*s1*r1
v21 = 2*x3 - 2*x2
v22 = 2*y3 - 2*y2
v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3
v24 = 2*s3*r3 - 2*s2*r2
w12 = v12/v11
w13 = v13/v11
w14 = v14/v11
w22 = v22/v21-w12
w23 = v23/v21-w13
w24 = v24/v21-w14
P = -w23/w22
Q = w24/w22
M = -w12*P-w13
N = w14 - w12*Q
a = N*N + Q*Q - 1
b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1
c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1
D = b*b-4*a*c
rs = (-b-math.sqrt(D))/(2*a)
xs = M+N*rs
ys = P+Q*rs
return Circle(xs, ys, rs)
if __name__ == '__main__':
c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)
print(solveApollonius(c1, c2, c3, 1, 1, 1))
print(solveApollonius(c1, c2, c3, -1, -1, -1))
| using System;
namespace ApolloniusProblemCalc
{
class Program
{
static float rs = 0;
static float xs = 0;
static float ys = 0;
public static void Main(string[] args)
{
float gx1;
float gy1;
float gr1;
float gx2;
float gy2;
float gr2;
float gx3;
float gy3;
float gr3;
gx1 = 0;
gy1 = 0;
gr1 = 1;
gx2 = 4;
gy2 = 0;
gr2 = 1;
gx3 = 2;
gy3 = 4;
gr3 = 2;
for (int i = 1; i <= 8; i++)
{
SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);
if (i == 1)
{
Console.WriteLine("X of point of the " + i + "st solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "st solution: " + ys.ToString());
Console.WriteLine(i + "st Solution circle's radius: " + rs.ToString());
}
else if (i == 2)
{
Console.WriteLine("X of point of the " + i + "ed solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "ed solution: " + ys.ToString());
Console.WriteLine(i + "ed Solution circle's radius: " + rs.ToString());
}
else if(i == 3)
{
Console.WriteLine("X of point of the " + i + "rd solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "rd solution: " + ys.ToString());
Console.WriteLine(i + "rd Solution circle's radius: " + rs.ToString());
}
else
{
Console.WriteLine("X of point of the " + i + "th solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "th solution: " + ys.ToString());
Console.WriteLine(i + "th Solution circle's radius: " + rs.ToString());
}
Console.WriteLine();
}
Console.ReadKey(true);
}
private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)
{
float s1 = 1;
float s2 = 1;
float s3 = 1;
if (calcCounter == 2)
{
s1 = -1;
s2 = -1;
s3 = -1;
}
else if (calcCounter == 3)
{
s1 = 1;
s2 = -1;
s3 = -1;
}
else if (calcCounter == 4)
{
s1 = -1;
s2 = 1;
s3 = -1;
}
else if (calcCounter == 5)
{
s1 = -1;
s2 = -1;
s3 = 1;
}
else if (calcCounter == 6)
{
s1 = 1;
s2 = 1;
s3 = -1;
}
else if (calcCounter == 7)
{
s1 = -1;
s2 = 1;
s3 = 1;
}
else if (calcCounter == 8)
{
s1 = 1;
s2 = -1;
s3 = 1;
}
float v11 = 2 * x2 - 2 * x1;
float v12 = 2 * y2 - 2 * y1;
float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;
float v14 = 2 * s2 * r2 - 2 * s1 * r1;
float v21 = 2 * x3 - 2 * x2;
float v22 = 2 * y3 - 2 * y2;
float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;
float v24 = 2 * s3 * r3 - 2 * s2 * r2;
float w12 = v12 / v11;
float w13 = v13 / v11;
float w14 = v14 / v11;
float w22 = v22 / v21 - w12;
float w23 = v23 / v21 - w13;
float w24 = v24 / v21 - w14;
float P = -w23 / w22;
float Q = w24 / w22;
float M = -w12 * P - w13;
float N = w14 - w12 * Q;
float a = N * N + Q * Q - 1;
float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;
float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;
float D = b * b - 4 * a * c;
rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));
xs = M + N * rs;
ys = P + Q * rs;
}
}
}
|
Produce a functionally identical C# code for the snippet given in Python. |
import socket
import thread
import time
HOST = ""
PORT = 4004
def accept(conn):
def threaded():
while True:
conn.send("Please enter your name: ")
try:
name = conn.recv(1024).strip()
except socket.error:
continue
if name in users:
conn.send("Name entered is already in use.\n")
elif name:
conn.setblocking(False)
users[name] = conn
broadcast(name, "+++ %s arrived +++" % name)
break
thread.start_new_thread(threaded, ())
def broadcast(name, message):
print message
for to_name, conn in users.items():
if to_name != name:
try:
conn.send(message + "\n")
except socket.error:
pass
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((HOST, PORT))
server.listen(1)
print "Listening on %s" % ("%s:%s" % server.getsockname())
users = {}
while True:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
accept(conn)
for name, conn in users.items():
try:
message = conn.recv(1024)
except socket.error:
continue
if not message:
del users[name]
broadcast(name, "--- %s leaves ---" % name)
else:
broadcast(name, "%s> %s" % (name, message.strip()))
time.sleep(.1)
except (SystemExit, KeyboardInterrupt):
break
| using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ChatServer {
class State {
private TcpClient client;
private StringBuilder sb = new StringBuilder();
public string Name { get; }
public State(string name, TcpClient client) {
Name = name;
this.client = client;
}
public void Add(byte b) {
sb.Append((char)b);
}
public void Send(string text) {
var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text));
client.GetStream().Write(bytes, 0, bytes.Length);
}
}
class Program {
static TcpListener listen;
static Thread serverthread;
static Dictionary<int, State> connections = new Dictionary<int, State>();
static void Main(string[] args) {
listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004);
serverthread = new Thread(new ThreadStart(DoListen));
serverthread.Start();
}
private static void DoListen() {
listen.Start();
Console.WriteLine("Server: Started server");
while (true) {
Console.WriteLine("Server: Waiting...");
TcpClient client = listen.AcceptTcpClient();
Console.WriteLine("Server: Waited");
Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
clientThread.Start(client);
}
}
private static void DoClient(object client) {
TcpClient tClient = (TcpClient)client;
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
byte[] bytes = Encoding.ASCII.GetBytes("Enter name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
string name = string.Empty;
bool done = false;
do {
if (!tClient.Connected) {
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
name = Receive(tClient);
done = true;
if (done) {
foreach (var cl in connections) {
var state = cl.Value;
if (state.Name == name) {
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
done = false;
}
}
}
} while (!done);
connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));
Console.WriteLine("\tTotal connections: {0}", connections.Count);
Broadcast(string.Format("+++ {0} arrived +++", name));
do {
string text = Receive(tClient);
if (text == "/quit") {
Broadcast(string.Format("Connection from {0} closed.", name));
connections.Remove(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("\tTotal connections: {0}", connections.Count);
break;
}
if (!tClient.Connected) {
break;
}
Broadcast(string.Format("{0}> {1}", name, text));
} while (true);
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
private static string Receive(TcpClient client) {
StringBuilder sb = new StringBuilder();
do {
if (client.Available > 0) {
while (client.Available > 0) {
char ch = (char)client.GetStream().ReadByte();
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.ToString();
}
sb.Append(ch);
}
}
Thread.Sleep(100);
} while (true);
}
private static void Broadcast(string text) {
Console.WriteLine(text);
foreach (var oClient in connections) {
if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {
State state = oClient.Value;
state.Send(text);
}
}
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | import io
FASTA=
infile = io.StringIO(FASTA)
def fasta_parse(infile):
key = ''
for line in infile:
if line.startswith('>'):
if key:
yield key, val
key, val = line[1:].rstrip().split()[0], ''
elif key:
val += line.rstrip()
if key:
yield key, val
print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
| using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Program
{
public class FastaEntry
{
public string Name { get; set; }
public StringBuilder Sequence { get; set; }
}
static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
{
FastaEntry f = null;
string line;
while ((line = fastaFile.ReadLine()) != null)
{
if (line.StartsWith(";"))
continue;
if (line.StartsWith(">"))
{
if (f != null)
yield return f;
f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
}
else if (f != null)
f.Sequence.Append(line);
}
yield return f;
}
static void Main(string[] args)
{
try
{
using (var fastaFile = new StreamReader("fasta.txt"))
{
foreach (FastaEntry f in ParseFasta(fastaFile))
Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
}
}
catch (FileNotFoundException e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
|
Please provide an equivalent version of this Python code in C#. | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
|
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
| static void Main(string[] args)
{
int bufferHeight = Console.BufferHeight;
int bufferWidth = Console.BufferWidth;
int windowHeight = Console.WindowHeight;
int windowWidth = Console.WindowWidth;
Console.Write("Buffer Height: ");
Console.WriteLine(bufferHeight);
Console.Write("Buffer Width: ");
Console.WriteLine(bufferWidth);
Console.Write("Window Height: ");
Console.WriteLine(windowHeight);
Console.Write("Window Width: ");
Console.WriteLine(windowWidth);
Console.ReadLine();
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| using System;
using System.Numerics;
namespace CipollaAlgorithm {
class Program {
static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;
private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {
BigInteger n = BigInteger.Parse(ns);
BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;
BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);
if (ls(n) != 1) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
BigInteger a = 0;
BigInteger omega2;
while (true) {
omega2 = (a * a + p - n) % p;
if (ls(omega2) == p - 1) {
break;
}
a += 1;
}
BigInteger finalOmega = omega2;
Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {
return new Tuple<BigInteger, BigInteger>(
(aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,
(aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p
);
}
Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);
Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);
BigInteger nn = ((p + 1) >> 1) % p;
while (nn > 0) {
if ((nn & 1) == 1) {
r = mul(r, s);
}
s = mul(s, s);
nn >>= 1;
}
if (r.Item2 != 0) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
if (r.Item1 * r.Item1 % p != n) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);
}
static void Main(string[] args) {
Console.WriteLine(C("10", "13"));
Console.WriteLine(C("56", "101"));
Console.WriteLine(C("8218", "10007"));
Console.WriteLine(C("8219", "10007"));
Console.WriteLine(C("331575", "1000003"));
Console.WriteLine(C("665165880", "1000000007"));
Console.WriteLine(C("881398088036", "1000000000039"));
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""));
}
}
}
|
Convert this Python block to C#, preserving its control flow and logic. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| using System;
using System.Numerics;
namespace CipollaAlgorithm {
class Program {
static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;
private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {
BigInteger n = BigInteger.Parse(ns);
BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;
BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);
if (ls(n) != 1) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
BigInteger a = 0;
BigInteger omega2;
while (true) {
omega2 = (a * a + p - n) % p;
if (ls(omega2) == p - 1) {
break;
}
a += 1;
}
BigInteger finalOmega = omega2;
Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {
return new Tuple<BigInteger, BigInteger>(
(aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,
(aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p
);
}
Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);
Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);
BigInteger nn = ((p + 1) >> 1) % p;
while (nn > 0) {
if ((nn & 1) == 1) {
r = mul(r, s);
}
s = mul(s, s);
nn >>= 1;
}
if (r.Item2 != 0) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
if (r.Item1 * r.Item1 % p != n) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);
}
static void Main(string[] args) {
Console.WriteLine(C("10", "13"));
Console.WriteLine(C("56", "101"));
Console.WriteLine(C("8218", "10007"));
Console.WriteLine(C("8219", "10007"));
Console.WriteLine(C("331575", "1000003"));
Console.WriteLine(C("665165880", "1000000007"));
Console.WriteLine(C("881398088036", "1000000000039"));
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""));
}
}
}
|
Write the same algorithm in C# as shown in this Python implementation. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| using System;
using System.Numerics;
namespace CipollaAlgorithm {
class Program {
static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;
private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {
BigInteger n = BigInteger.Parse(ns);
BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;
BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);
if (ls(n) != 1) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
BigInteger a = 0;
BigInteger omega2;
while (true) {
omega2 = (a * a + p - n) % p;
if (ls(omega2) == p - 1) {
break;
}
a += 1;
}
BigInteger finalOmega = omega2;
Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {
return new Tuple<BigInteger, BigInteger>(
(aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,
(aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p
);
}
Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);
Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);
BigInteger nn = ((p + 1) >> 1) % p;
while (nn > 0) {
if ((nn & 1) == 1) {
r = mul(r, s);
}
s = mul(s, s);
nn >>= 1;
}
if (r.Item2 != 0) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
if (r.Item1 * r.Item1 % p != n) {
return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
}
return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);
}
static void Main(string[] args) {
Console.WriteLine(C("10", "13"));
Console.WriteLine(C("56", "101"));
Console.WriteLine(C("8218", "10007"));
Console.WriteLine(C("8219", "10007"));
Console.WriteLine(C("331575", "1000003"));
Console.WriteLine(C("665165880", "1000000007"));
Console.WriteLine(C("881398088036", "1000000000039"));
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""));
}
}
}
|
Translate this program into C# but keep the logic exactly as in Python. | 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
| string path = @"C:\Windows\System32";
string multiline = @"Line 1.
Line 2.
Line 3.";
|
Ensure the translated C# code behaves exactly like the original Python snippet. |
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
| using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Rectangle bounds = Screen.PrimaryScreen.Bounds;
Console.WriteLine($"Primary screen bounds: {bounds.Width}x{bounds.Height}");
Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
Console.WriteLine($"Primary screen working area: {workingArea.Width}x{workingArea.Height}");
}
}
|
Change the following Python code into C# without altering its purpose. | >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
| enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits : int { apple = 0, banana = 1, cherry = 2 }
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
|
Convert this Python block to C#, preserving its control flow and logic. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| using System;
using System.Collections.Generic;
namespace A_star
{
class A_star
{
public class Coordinates : IEquatable<Coordinates>
{
public int row;
public int col;
public Coordinates() { this.row = -1; this.col = -1; }
public Coordinates(int row, int col) { this.row = row; this.col = col; }
public Boolean Equals(Coordinates c)
{
if (this.row == c.row && this.col == c.col)
return true;
else
return false;
}
}
public class Cell
{
public int cost;
public int g;
public int f;
public Coordinates parent;
}
public class Astar
{
public Cell[,] cells = new Cell[8, 8];
public List<Coordinates> path = new List<Coordinates>();
public List<Coordinates> opened = new List<Coordinates>();
public List<Coordinates> closed = new List<Coordinates>();
public Coordinates startCell = new Coordinates(0, 0);
public Coordinates finishCell = new Coordinates(7, 7);
public Astar()
{
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
{
cells[i, j] = new Cell();
cells[i, j].parent = new Coordinates();
if (IsAWall(i, j))
cells[i, j].cost = 100;
else
cells[i, j].cost = 1;
}
opened.Add(startCell);
Boolean pathFound = false;
do
{
List<Coordinates> neighbors = new List<Coordinates>();
Coordinates currentCell = ShorterExpectedPath();
neighbors = neighborsCells(currentCell);
foreach (Coordinates newCell in neighbors)
{
if (newCell.row == finishCell.row && newCell.col == finishCell.col)
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
pathFound = true;
break;
}
else if (!opened.Contains(newCell) && !closed.Contains(newCell))
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].f =
cells[newCell.row, newCell.col].g + Heuristic(newCell);
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
SetCell(newCell, opened);
}
else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost)
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].f =
cells[newCell.row, newCell.col].g + Heuristic(newCell);
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
SetCell(newCell, opened);
ResetCell(newCell, closed);
}
}
SetCell(currentCell, closed);
ResetCell(currentCell, opened);
} while (opened.Count > 0 && pathFound == false);
if (pathFound)
{
path.Add(finishCell);
Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);
while (cells[currentCell.row, currentCell.col].parent.row >= 0)
{
path.Add(cells[currentCell.row, currentCell.col].parent);
int tmp_row = cells[currentCell.row, currentCell.col].parent.row;
currentCell.col = cells[currentCell.row, currentCell.col].parent.col;
currentCell.row = tmp_row;
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
char gr = '.';
if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }
else if (cells[i, j].cost > 1) { gr = '\u2588'; }
System.Console.Write(gr);
}
System.Console.WriteLine();
}
System.Console.Write("\nPath: ");
for (int i = path.Count - 1; i >= 0; i--)
{
System.Console.Write("({0},{1})", path[i].row, path[i].col);
}
System.Console.WriteLine("\nPath cost: {0}", path.Count - 1);
String wt = System.Console.ReadLine();
}
}
public Coordinates ShorterExpectedPath()
{
int sep = 0;
if (opened.Count > 1)
{
for (int i = 1; i < opened.Count; i++)
{
if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,
opened[sep].col].f)
{
sep = i;
}
}
}
return opened[sep];
}
public List<Coordinates> neighborsCells(Coordinates c)
{
List<Coordinates> lc = new List<Coordinates>();
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&
(i != 0 || j != 0))
{
lc.Add(new Coordinates(c.row + i, c.col + j));
}
return lc;
}
public bool IsAWall(int row, int col)
{
int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },
{ 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };
bool found = false;
for (int i = 0; i < walls.GetLength(0); i++)
if (walls[i,0] == row && walls[i,1] == col)
found = true;
return found;
}
public int Heuristic(Coordinates cell)
{
int dRow = Math.Abs(finishCell.row - cell.row);
int dCol = Math.Abs(finishCell.col - cell.col);
return Math.Max(dRow, dCol);
}
public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)
{
if (coordinatesList.Contains(cell) == false)
{
coordinatesList.Add(cell);
}
}
public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)
{
if (coordinatesList.Contains(cell))
{
coordinatesList.Remove(cell);
}
}
}
static void Main(string[] args)
{
Astar astar = new Astar();
}
}
}
|
Port the provided Python code into C# while preserving the original functionality. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| using System;
using System.Collections.Generic;
namespace A_star
{
class A_star
{
public class Coordinates : IEquatable<Coordinates>
{
public int row;
public int col;
public Coordinates() { this.row = -1; this.col = -1; }
public Coordinates(int row, int col) { this.row = row; this.col = col; }
public Boolean Equals(Coordinates c)
{
if (this.row == c.row && this.col == c.col)
return true;
else
return false;
}
}
public class Cell
{
public int cost;
public int g;
public int f;
public Coordinates parent;
}
public class Astar
{
public Cell[,] cells = new Cell[8, 8];
public List<Coordinates> path = new List<Coordinates>();
public List<Coordinates> opened = new List<Coordinates>();
public List<Coordinates> closed = new List<Coordinates>();
public Coordinates startCell = new Coordinates(0, 0);
public Coordinates finishCell = new Coordinates(7, 7);
public Astar()
{
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
{
cells[i, j] = new Cell();
cells[i, j].parent = new Coordinates();
if (IsAWall(i, j))
cells[i, j].cost = 100;
else
cells[i, j].cost = 1;
}
opened.Add(startCell);
Boolean pathFound = false;
do
{
List<Coordinates> neighbors = new List<Coordinates>();
Coordinates currentCell = ShorterExpectedPath();
neighbors = neighborsCells(currentCell);
foreach (Coordinates newCell in neighbors)
{
if (newCell.row == finishCell.row && newCell.col == finishCell.col)
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
pathFound = true;
break;
}
else if (!opened.Contains(newCell) && !closed.Contains(newCell))
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].f =
cells[newCell.row, newCell.col].g + Heuristic(newCell);
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
SetCell(newCell, opened);
}
else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost)
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].f =
cells[newCell.row, newCell.col].g + Heuristic(newCell);
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
SetCell(newCell, opened);
ResetCell(newCell, closed);
}
}
SetCell(currentCell, closed);
ResetCell(currentCell, opened);
} while (opened.Count > 0 && pathFound == false);
if (pathFound)
{
path.Add(finishCell);
Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);
while (cells[currentCell.row, currentCell.col].parent.row >= 0)
{
path.Add(cells[currentCell.row, currentCell.col].parent);
int tmp_row = cells[currentCell.row, currentCell.col].parent.row;
currentCell.col = cells[currentCell.row, currentCell.col].parent.col;
currentCell.row = tmp_row;
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
char gr = '.';
if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }
else if (cells[i, j].cost > 1) { gr = '\u2588'; }
System.Console.Write(gr);
}
System.Console.WriteLine();
}
System.Console.Write("\nPath: ");
for (int i = path.Count - 1; i >= 0; i--)
{
System.Console.Write("({0},{1})", path[i].row, path[i].col);
}
System.Console.WriteLine("\nPath cost: {0}", path.Count - 1);
String wt = System.Console.ReadLine();
}
}
public Coordinates ShorterExpectedPath()
{
int sep = 0;
if (opened.Count > 1)
{
for (int i = 1; i < opened.Count; i++)
{
if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,
opened[sep].col].f)
{
sep = i;
}
}
}
return opened[sep];
}
public List<Coordinates> neighborsCells(Coordinates c)
{
List<Coordinates> lc = new List<Coordinates>();
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&
(i != 0 || j != 0))
{
lc.Add(new Coordinates(c.row + i, c.col + j));
}
return lc;
}
public bool IsAWall(int row, int col)
{
int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },
{ 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };
bool found = false;
for (int i = 0; i < walls.GetLength(0); i++)
if (walls[i,0] == row && walls[i,1] == col)
found = true;
return found;
}
public int Heuristic(Coordinates cell)
{
int dRow = Math.Abs(finishCell.row - cell.row);
int dCol = Math.Abs(finishCell.col - cell.col);
return Math.Max(dRow, dCol);
}
public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)
{
if (coordinatesList.Contains(cell) == false)
{
coordinatesList.Add(cell);
}
}
public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)
{
if (coordinatesList.Contains(cell))
{
coordinatesList.Remove(cell);
}
}
}
static void Main(string[] args)
{
Astar astar = new Astar();
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| using System;
using System.Collections.Generic;
namespace A_star
{
class A_star
{
public class Coordinates : IEquatable<Coordinates>
{
public int row;
public int col;
public Coordinates() { this.row = -1; this.col = -1; }
public Coordinates(int row, int col) { this.row = row; this.col = col; }
public Boolean Equals(Coordinates c)
{
if (this.row == c.row && this.col == c.col)
return true;
else
return false;
}
}
public class Cell
{
public int cost;
public int g;
public int f;
public Coordinates parent;
}
public class Astar
{
public Cell[,] cells = new Cell[8, 8];
public List<Coordinates> path = new List<Coordinates>();
public List<Coordinates> opened = new List<Coordinates>();
public List<Coordinates> closed = new List<Coordinates>();
public Coordinates startCell = new Coordinates(0, 0);
public Coordinates finishCell = new Coordinates(7, 7);
public Astar()
{
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
{
cells[i, j] = new Cell();
cells[i, j].parent = new Coordinates();
if (IsAWall(i, j))
cells[i, j].cost = 100;
else
cells[i, j].cost = 1;
}
opened.Add(startCell);
Boolean pathFound = false;
do
{
List<Coordinates> neighbors = new List<Coordinates>();
Coordinates currentCell = ShorterExpectedPath();
neighbors = neighborsCells(currentCell);
foreach (Coordinates newCell in neighbors)
{
if (newCell.row == finishCell.row && newCell.col == finishCell.col)
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
pathFound = true;
break;
}
else if (!opened.Contains(newCell) && !closed.Contains(newCell))
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].f =
cells[newCell.row, newCell.col].g + Heuristic(newCell);
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
SetCell(newCell, opened);
}
else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost)
{
cells[newCell.row, newCell.col].g = cells[currentCell.row,
currentCell.col].g + cells[newCell.row, newCell.col].cost;
cells[newCell.row, newCell.col].f =
cells[newCell.row, newCell.col].g + Heuristic(newCell);
cells[newCell.row, newCell.col].parent.row = currentCell.row;
cells[newCell.row, newCell.col].parent.col = currentCell.col;
SetCell(newCell, opened);
ResetCell(newCell, closed);
}
}
SetCell(currentCell, closed);
ResetCell(currentCell, opened);
} while (opened.Count > 0 && pathFound == false);
if (pathFound)
{
path.Add(finishCell);
Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);
while (cells[currentCell.row, currentCell.col].parent.row >= 0)
{
path.Add(cells[currentCell.row, currentCell.col].parent);
int tmp_row = cells[currentCell.row, currentCell.col].parent.row;
currentCell.col = cells[currentCell.row, currentCell.col].parent.col;
currentCell.row = tmp_row;
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
char gr = '.';
if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }
else if (cells[i, j].cost > 1) { gr = '\u2588'; }
System.Console.Write(gr);
}
System.Console.WriteLine();
}
System.Console.Write("\nPath: ");
for (int i = path.Count - 1; i >= 0; i--)
{
System.Console.Write("({0},{1})", path[i].row, path[i].col);
}
System.Console.WriteLine("\nPath cost: {0}", path.Count - 1);
String wt = System.Console.ReadLine();
}
}
public Coordinates ShorterExpectedPath()
{
int sep = 0;
if (opened.Count > 1)
{
for (int i = 1; i < opened.Count; i++)
{
if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,
opened[sep].col].f)
{
sep = i;
}
}
}
return opened[sep];
}
public List<Coordinates> neighborsCells(Coordinates c)
{
List<Coordinates> lc = new List<Coordinates>();
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&
(i != 0 || j != 0))
{
lc.Add(new Coordinates(c.row + i, c.col + j));
}
return lc;
}
public bool IsAWall(int row, int col)
{
int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },
{ 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };
bool found = false;
for (int i = 0; i < walls.GetLength(0); i++)
if (walls[i,0] == row && walls[i,1] == col)
found = true;
return found;
}
public int Heuristic(Coordinates cell)
{
int dRow = Math.Abs(finishCell.row - cell.row);
int dCol = Math.Abs(finishCell.col - cell.col);
return Math.Max(dRow, dCol);
}
public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)
{
if (coordinatesList.Contains(cell) == false)
{
coordinatesList.Add(cell);
}
}
public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)
{
if (coordinatesList.Contains(cell))
{
coordinatesList.Remove(cell);
}
}
}
static void Main(string[] args)
{
Astar astar = new Astar();
}
}
}
|
Change the following Python code into C# without altering its purpose. | def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
| using System;
using System.Collections.Generic;
using System.Linq;
class RangeExtraction
{
static void Main()
{
const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39";
var result = String.Join(",", RangesToStrings(GetRanges(testString)));
Console.Out.WriteLine(result);
}
public static IEnumerable<IEnumerable<int>> GetRanges(string testString)
{
var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));
var current = new List<int>();
foreach (var n in numbers)
{
if (current.Count == 0)
{
current.Add(n);
}
else
{
if (current.Max() + 1 == n)
{
current.Add(n);
}
else
{
yield return current;
current = new List<int> { n };
}
}
}
yield return current;
}
public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)
{
foreach (var range in ranges)
{
if (range.Count() == 1)
{
yield return range.Single().ToString();
}
else if (range.Count() == 2)
{
yield return range.Min() + "," + range.Max();
}
else
{
yield return range.Min() + "-" + range.Max();
}
}
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
| using System;
namespace RosetaCode
{
class MainClass
{
public static void Main (string[] args)
{
int[,] list = new int[18,19];
string input = @"55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93";
var charArray = input.Split ('\n');
for (int i=0; i < charArray.Length; i++) {
var numArr = charArray[i].Trim().Split(' ');
for (int j = 0; j<numArr.Length; j++)
{
int number = Convert.ToInt32 (numArr[j]);
list [i, j] = number;
}
}
for (int i = 16; i >= 0; i--) {
for (int j = 0; j < 18; j++) {
list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);
}
}
Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0]));
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import curses
scr = curses.initscr()
def move_left():
y,x = curses.getyx()
curses.move(y,x-1)
def move_right():
y,x = curses.getyx()
curses.move(y,x+1)
def move_up():
y,x = curses.getyx()
curses.move(y-1,x)
def move_down():
y,x = curses.getyx()
curses.move(y+1,x)
def move_line_home()
y,x = curses.getyx()
curses.move(y,0)
def move_line_end()
y,x = curses.getyx()
maxy,maxx = scr.getmaxyx()
curses.move(y,maxx)
def move_page_home():
curses.move(0,0)
def move_page_end():
y,x = scr.getmaxyx()
curses.move(y,x)
| static void Main(string[] args)
{
Console.Write("\n\n\n\n Cursor is here --> ");
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.CursorLeft - 1;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.CursorLeft + 1;
System.Threading.Thread.Sleep(3000);
Console.CursorTop = Console.CursorTop - 1;
System.Threading.Thread.Sleep(3000);
Console.CursorTop = Console.CursorTop + 1;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = 0;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.BufferWidth - 1;
System.Threading.Thread.Sleep(3000);
Console.SetCursorPosition(0,0);
System.Threading.Thread.Sleep(3000);
Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1);
System.Threading.Thread.Sleep(3000);
}
|
Produce a functionally identical C# code for the snippet given in Python. | import curses
scr = curses.initscr()
def move_left():
y,x = curses.getyx()
curses.move(y,x-1)
def move_right():
y,x = curses.getyx()
curses.move(y,x+1)
def move_up():
y,x = curses.getyx()
curses.move(y-1,x)
def move_down():
y,x = curses.getyx()
curses.move(y+1,x)
def move_line_home()
y,x = curses.getyx()
curses.move(y,0)
def move_line_end()
y,x = curses.getyx()
maxy,maxx = scr.getmaxyx()
curses.move(y,maxx)
def move_page_home():
curses.move(0,0)
def move_page_end():
y,x = scr.getmaxyx()
curses.move(y,x)
| static void Main(string[] args)
{
Console.Write("\n\n\n\n Cursor is here --> ");
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.CursorLeft - 1;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.CursorLeft + 1;
System.Threading.Thread.Sleep(3000);
Console.CursorTop = Console.CursorTop - 1;
System.Threading.Thread.Sleep(3000);
Console.CursorTop = Console.CursorTop + 1;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = 0;
System.Threading.Thread.Sleep(3000);
Console.CursorLeft = Console.BufferWidth - 1;
System.Threading.Thread.Sleep(3000);
Console.SetCursorPosition(0,0);
System.Threading.Thread.Sleep(3000);
Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1);
System.Threading.Thread.Sleep(3000);
}
|
Please provide an equivalent version of this Python code in C#. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks.FourBitAdder
{
public struct BitAdderOutput
{
public bool S { get; set; }
public bool C { get; set; }
public override string ToString ( )
{
return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" );
}
}
public struct Nibble
{
public bool _1 { get; set; }
public bool _2 { get; set; }
public bool _3 { get; set; }
public bool _4 { get; set; }
public override string ToString ( )
{
return ( _4 ? "1" : "0" )
+ ( _3 ? "1" : "0" )
+ ( _2 ? "1" : "0" )
+ ( _1 ? "1" : "0" );
}
}
public struct FourBitAdderOutput
{
public Nibble N { get; set; }
public bool C { get; set; }
public override string ToString ( )
{
return N.ToString ( ) + "c" + ( C ? "1" : "0" );
}
}
public static class LogicGates
{
public static bool Not ( bool A ) { return !A; }
public static bool And ( bool A, bool B ) { return A && B; }
public static bool Or ( bool A, bool B ) { return A || B; }
public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }
}
public static class ConstructiveBlocks
{
public static BitAdderOutput HalfAdder ( bool A, bool B )
{
return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };
}
public static BitAdderOutput FullAdder ( bool A, bool B, bool CI )
{
BitAdderOutput HA1 = HalfAdder ( CI, A );
BitAdderOutput HA2 = HalfAdder ( HA1.S, B );
return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };
}
public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )
{
BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );
BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );
BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );
BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );
return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };
}
public static void Test ( )
{
Console.WriteLine ( "Four Bit Adder" );
for ( int i = 0; i < 256; i++ )
{
Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
if ( (i & 1) == 1)
{
A._1 = true;
}
if ( ( i & 2 ) == 2 )
{
A._2 = true;
}
if ( ( i & 4 ) == 4 )
{
A._3 = true;
}
if ( ( i & 8 ) == 8 )
{
A._4 = true;
}
if ( ( i & 16 ) == 16 )
{
B._1 = true;
}
if ( ( i & 32 ) == 32)
{
B._2 = true;
}
if ( ( i & 64 ) == 64 )
{
B._3 = true;
}
if ( ( i & 128 ) == 128 )
{
B._4 = true;
}
Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );
}
Console.WriteLine ( );
}
}
}
|
Write a version of this Python function in C# with identical behavior. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks.FourBitAdder
{
public struct BitAdderOutput
{
public bool S { get; set; }
public bool C { get; set; }
public override string ToString ( )
{
return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" );
}
}
public struct Nibble
{
public bool _1 { get; set; }
public bool _2 { get; set; }
public bool _3 { get; set; }
public bool _4 { get; set; }
public override string ToString ( )
{
return ( _4 ? "1" : "0" )
+ ( _3 ? "1" : "0" )
+ ( _2 ? "1" : "0" )
+ ( _1 ? "1" : "0" );
}
}
public struct FourBitAdderOutput
{
public Nibble N { get; set; }
public bool C { get; set; }
public override string ToString ( )
{
return N.ToString ( ) + "c" + ( C ? "1" : "0" );
}
}
public static class LogicGates
{
public static bool Not ( bool A ) { return !A; }
public static bool And ( bool A, bool B ) { return A && B; }
public static bool Or ( bool A, bool B ) { return A || B; }
public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }
}
public static class ConstructiveBlocks
{
public static BitAdderOutput HalfAdder ( bool A, bool B )
{
return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };
}
public static BitAdderOutput FullAdder ( bool A, bool B, bool CI )
{
BitAdderOutput HA1 = HalfAdder ( CI, A );
BitAdderOutput HA2 = HalfAdder ( HA1.S, B );
return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };
}
public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )
{
BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );
BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );
BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );
BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );
return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };
}
public static void Test ( )
{
Console.WriteLine ( "Four Bit Adder" );
for ( int i = 0; i < 256; i++ )
{
Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
if ( (i & 1) == 1)
{
A._1 = true;
}
if ( ( i & 2 ) == 2 )
{
A._2 = true;
}
if ( ( i & 4 ) == 4 )
{
A._3 = true;
}
if ( ( i & 8 ) == 8 )
{
A._4 = true;
}
if ( ( i & 16 ) == 16 )
{
B._1 = true;
}
if ( ( i & 32 ) == 32)
{
B._2 = true;
}
if ( ( i & 64 ) == 64 )
{
B._3 = true;
}
if ( ( i & 128 ) == 128 )
{
B._4 = true;
}
Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );
}
Console.WriteLine ( );
}
}
}
|
Convert this Python snippet to C# and keep its semantics consistent. | >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Unix_ls
{
public class UnixLS
{
public static void Main(string[] args)
{
UnixLS ls = new UnixLS();
ls.list(args.Length.Equals(0) ? "." : args[0]);
}
private void list(string folder)
{
foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(fileSystemInfo.Name);
}
}
}
}
|
Port the following code from Python to C# with equivalent syntax and logic. | >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Unix_ls
{
public class UnixLS
{
public static void Main(string[] args)
{
UnixLS ls = new UnixLS();
ls.list(args.Length.Equals(0) ? "." : args[0]);
}
private void list(string folder)
{
foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(fileSystemInfo.Name);
}
}
}
}
|
Change the programming language of this snippet from Python to C# without modifying what it does. |
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == "__main__":
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
chars = ['A', 'ö', 'Ж', '€', '𝄞']
for char in chars:
print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
| using System;
using System.Text;
namespace Rosetta
{
class Program
{
static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));
static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})
{
byte[] asUtf8bytes = MyEncoder(unicodePoint);
string theCharacter = MyDecoder(asUtf8bytes);
Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.