Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the following Java code into C# without altering its purpose. | import java.util.HashMap;
import java.util.Map;
public class VanEckSequence {
public static void main(String[] args) {
System.out.println("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
System.out.println("");
System.out.println("Terms 991 to 1000 of Van Eck's sequence:");
vanEck(991, 1000);
}
private static void vanEck(int firstIndex, int lastIndex) {
Map<Integer,Integer> vanEckMap = new HashMap<>();
int last = 0;
if ( firstIndex == 1 ) {
System.out.printf("VanEck[%d] = %d%n", 1, 0);
}
for ( int n = 2 ; n <= lastIndex ; n++ ) {
int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
vanEckMap.put(last, n);
last = vanEck;
if ( n >= firstIndex ) {
System.out.printf("VanEck[%d] = %d%n", n, vanEck);
}
}
}
}
| 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); } }
|
Convert this Java block to C#, preserving its control flow and logic. | for(int i = 1;i <= 10; i++){
System.out.print(i);
if(i % 5 == 0){
System.out.println();
continue;
}
System.out.print(", ");
}
| 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(", ");
}
}
}
|
Transform the following Java implementation into C#, maintaining the same output and logic. | public class FizzBuzz {
public static void main(String[] args) {
Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")};
for (int i = 1; i <= 20; i++) {
StringBuilder sb = new StringBuilder();
for (Sound sound : sounds) {
sb.append(sound.generate(i));
}
System.out.println(sb.length() == 0 ? i : sb.toString());
}
}
private static class Sound {
private final int trigger;
private final String onomatopoeia;
public Sound(int trigger, String onomatopoeia) {
this.trigger = trigger;
this.onomatopoeia = onomatopoeia;
}
public String generate(int i) {
return i % trigger == 0 ? onomatopoeia : "";
}
}
}
| using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
|
Produce a language-to-language conversion: from Java to C#, same semantics. | public class FizzBuzz {
public static void main(String[] args) {
Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")};
for (int i = 1; i <= 20; i++) {
StringBuilder sb = new StringBuilder();
for (Sound sound : sounds) {
sb.append(sound.generate(i));
}
System.out.println(sb.length() == 0 ? i : sb.toString());
}
}
private static class Sound {
private final int trigger;
private final String onomatopoeia;
public Sound(int trigger, String onomatopoeia) {
this.trigger = trigger;
this.onomatopoeia = onomatopoeia;
}
public String generate(int i) {
return i % trigger == 0 ? onomatopoeia : "";
}
}
}
| 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();
}
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. | import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
| 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();
}
}
}
}
|
Write a version of this Java function in C# with identical behavior. | import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
| 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();
}
}
}
}
|
Convert this Java block to C#, preserving its control flow and logic. | public class VLQCode
{
public static byte[] encode(long n)
{
int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);
int numBytes = (numRelevantBits + 6) / 7;
if (numBytes == 0)
numBytes = 1;
byte[] output = new byte[numBytes];
for (int i = numBytes - 1; i >= 0; i--)
{
int curByte = (int)(n & 0x7F);
if (i != (numBytes - 1))
curByte |= 0x80;
output[i] = (byte)curByte;
n >>>= 7;
}
return output;
}
public static long decode(byte[] b)
{
long n = 0;
for (int i = 0; i < b.length; i++)
{
int curByte = b[i] & 0xFF;
n = (n << 7) | (curByte & 0x7F);
if ((curByte & 0x80) == 0)
break;
}
return n;
}
public static String byteArrayToString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
if (i > 0)
sb.append(", ");
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() < 2)
s = "0" + s;
sb.append(s);
}
return sb.toString();
}
public static void main(String[] args)
{
long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };
for (long n : testNumbers)
{
byte[] encoded = encode(n);
long decoded = decode(encoded);
System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL"));
}
}
}
| 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();
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
| using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
|
Translate the given Java code snippet into C# without altering its behavior. | import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Digester {
public static void main(String[] args) {
System.out.println(hexDigest("Rosetta code", "MD5"));
}
static String hexDigest(String str, String digestName) {
try {
MessageDigest md = MessageDigest.getInstance(digestName);
byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
char[] hex = new char[digest.length * 2];
for (int i = 0; i < digest.length; i++) {
hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4);
hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f);
}
return new String(hex);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
| 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());
|
Maintain the same structure and functionality when rewriting this code in C#. | import java.time.*;
import java.time.format.*;
class Main {
public static void main(String args[]) {
String dateStr = "March 7 2009 7:30pm EST";
DateTimeFormatter df = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM d yyyy h:mma zzz")
.toFormatter();
ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);
System.out.println("Date: " + dateStr);
System.out.println("+12h: " + after12Hours.format(df));
ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET"));
System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df));
}
}
| 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();
}
}
|
Can you help me rewrite this code in C# instead of Java, keeping it the same logically? | import java.util.concurrent.CountDownLatch;
public class SleepSort {
public static void sleepSortAndPrint(int[] nums) {
final CountDownLatch doneSignal = new CountDownLatch(nums.length);
for (final int num : nums) {
new Thread(new Runnable() {
public void run() {
doneSignal.countDown();
try {
doneSignal.await();
Thread.sleep(num * 1000);
System.out.println(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
public static void main(String[] args) {
int[] nums = new int[args.length];
for (int i = 0; i < args.length; i++)
nums[i] = Integer.parseInt(args[i]);
sleepSortAndPrint(nums);
}
}
| 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));
}
}
|
Write the same code in C# as shown below in Java. | import java.util.Random;
public class NestedLoopTest {
public static final Random gen = new Random();
public static void main(String[] args) {
int[][] a = new int[10][10];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
a[i][j] = gen.nextInt(20) + 1;
Outer:for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(" " + a[i][j]);
if (a[i][j] == 20)
break Outer;
}
System.out.println();
}
System.out.println();
}
}
| 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();
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Java version. | module RetainUniqueValues
{
@Inject Console console;
void run()
{
Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];
array = array.distinct().toArray();
console.print($"result={array}");
}
}
| 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);
|
Can you help me rewrite this code in C# instead of Java, keeping it the same logically? | public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
| 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);
}
}
}
|
Generate an equivalent C# version of this Java code. | import java.util.Stack;
public class StackTest {
public static void main( final String[] args ) {
final Stack<String> stack = new Stack<String>();
System.out.println( "New stack empty? " + stack.empty() );
stack.push( "There can be only one" );
System.out.println( "Pushed stack empty? " + stack.empty() );
System.out.println( "Popped single entry: " + stack.pop() );
stack.push( "First" );
stack.push( "Second" );
System.out.println( "Popped entry should be second: " + stack.pop() );
stack.pop();
stack.pop();
}
}
|
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();
|
Translate this program into C# but keep the logic exactly as in Java. | public class TotientFunction {
public static void main(String[] args) {
computePhi();
System.out.println("Compute and display phi for the first 25 integers.");
System.out.printf("n Phi IsPrime%n");
for ( int n = 1 ; n <= 25 ; n++ ) {
System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1));
}
for ( int i = 2 ; i < 8 ; i++ ) {
int max = (int) Math.pow(10, i);
System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max));
}
}
private static int countPrimes(int min, int max) {
int count = 0;
for ( int i = min ; i <= max ; i++ ) {
if ( phi[i] == i-1 ) {
count++;
}
}
return count;
}
private static final int max = 10000000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
| 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;
}
}
|
Generate an equivalent C# version of this Java code. | if (s == 'Hello World') {
foo();
} else if (s == 'Bye World') {
bar();
} else {
deusEx();
}
| if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | import java.util.Comparator;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
Arrays.sort(strings, new Comparator<String>() {
public int compare(String s1, String s2) {
int c = s2.length() - s1.length();
if (c == 0)
c = s1.compareToIgnoreCase(s2);
return c;
}
});
for (String s: strings)
System.out.print(s + " ");
}
}
| 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();
}
}
}
|
Port the provided Java code into C# while preserving the original functionality. | import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Rotate {
private static class State {
private final String text = "Hello World! ";
private int startIndex = 0;
private boolean rotateRight = true;
}
public static void main(String[] args) {
State state = new State();
JLabel label = new JLabel(state.text);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
state.rotateRight = !state.rotateRight;
}
});
TimerTask task = new TimerTask() {
public void run() {
int delta = state.rotateRight ? 1 : -1;
state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
label.setText(rotate(state.text, state.startIndex));
}
};
Timer timer = new Timer(false);
timer.schedule(task, 0, 500);
JFrame rot = new JFrame();
rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
rot.add(label);
rot.pack();
rot.setLocationRelativeTo(null);
rot.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
timer.cancel();
}
});
rot.setVisible(true);
}
private static String rotate(String text, int startIdx) {
char[] rotated = new char[text.length()];
for (int i = 0; i < text.length(); i++) {
rotated[i] = text.charAt((i + startIdx) % text.length());
}
return String.valueOf(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());
}
}
}
|
Port the following code from Java to C# with equivalent syntax and logic. | public static int[] sort(int[] old) {
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
int[] tmp = new int[old.length];
int j = 0;
for (int i = 0; i < old.length; i++) {
boolean move = old[i] << shift >= 0;
if (shift == 0 ? !move : move) {
tmp[j] = old[i];
j++;
} else {
old[i - j] = old[i];
}
}
for (int i = j; i < tmp.length; i++) {
tmp[i] = old[i - j];
}
old = tmp;
}
return old;
}
| 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();
}
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. |
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
| 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);
}
}
|
Produce a functionally identical C# code for the snippet given in Java. | public static void sort(int[] nums){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
int smallestAt = currentPlace+1;
for(int check = currentPlace; check<nums.length;check++){
if(nums[check]<smallest){
smallestAt = check;
smallest = nums[check];
}
}
int temp = nums[currentPlace];
nums[currentPlace] = nums[smallestAt];
nums[smallestAt] = temp;
}
}
| 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;
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
}
| 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);
|
Can you help me rewrite this code in C# instead of Java, keeping it the same logically? | class Singleton
{
private static Singleton myInstance;
public static Singleton getInstance()
{
if (myInstance == null)
{
synchronized(Singleton.class)
{
if (myInstance == null)
{
myInstance = new Singleton();
}
}
}
return myInstance;
}
protected Singleton()
{
}
}
| 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;
}
}
}
|
Generate a C# translation of this Java snippet without changing its computational steps. | public class SafeAddition {
private static double stepDown(double d) {
return Math.nextAfter(d, Double.NEGATIVE_INFINITY);
}
private static double stepUp(double d) {
return Math.nextUp(d);
}
private static double[] safeAdd(double a, double b) {
return new double[]{stepDown(a + b), stepUp(a + b)};
}
public static void main(String[] args) {
double a = 1.2;
double b = 0.03;
double[] result = safeAdd(a, b);
System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]);
}
}
| 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));
}
}
}
|
Port the following code from Java to C# with equivalent syntax and logic. | for (int i = 10; i >= 0; i--) {
System.out.println(i);
}
| for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
|
Port the following code from Java to C# with equivalent syntax and logic. | import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
bw.write("abc");
}
}
}
| System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
|
Port the provided Java code into C# while preserving the original functionality. | for (Integer i = 0; i < 5; i++) {
String line = '';
for (Integer j = 0; j < i; j++) {
line += '*';
}
System.debug(line);
}
List<String> lines = new List<String> {
'*',
'**',
'***',
'****',
'*****'
};
for (String line : lines) {
System.debug(line);
}
| 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();
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | public class NonContinuousSubsequences {
public static void main(String args[]) {
seqR("1234", "", 0, 0);
}
private static void seqR(String s, String c, int i, int added) {
if (i == s.length()) {
if (c.trim().length() > added)
System.out.println(c);
} else {
seqR(s, c + s.charAt(i), i + 1, added + 1);
seqR(s, c + ' ', i + 1, added);
}
}
}
| 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;
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.math.BigInteger;
import java.util.Scanner;
public class twinPrimes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Search Size: ");
BigInteger max = input.nextBigInteger();
int counter = 0;
for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
}
}
System.out.println(counter + " twin prime pairs.");
}
public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
return false;
}
}
return true;
}
}
| 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);
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. | import java.math.BigInteger;
import java.util.Scanner;
public class twinPrimes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Search Size: ");
BigInteger max = input.nextBigInteger();
int counter = 0;
for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
}
}
System.out.println(counter + " twin prime pairs.");
}
public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
return false;
}
}
return true;
}
}
| 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);
}
}
|
Translate the given Java code snippet into C# without altering its behavior. | import java.util.Locale;
public class Test {
public static void main(String[] a) {
for (int n = 2; n < 6; n++)
unity(n);
}
public static void unity(int n) {
System.out.printf("%n%d: ", n);
for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {
double real = Math.cos(angle);
if (Math.abs(real) < 1.0E-3)
real = 0.0;
double imag = Math.sin(angle);
if (Math.abs(imag) < 1.0E-3)
imag = 0.0;
System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
}
}
}
| 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);
}
}
}
|
Port the following code from Java to C# with equivalent syntax and logic. | public class LongMult {
private static byte[] stringToDigits(String num) {
byte[] result = new byte[num.length()];
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
if (c < '0' || c > '9') {
throw new IllegalArgumentException("Invalid digit " + c
+ " found at position " + i);
}
result[num.length() - 1 - i] = (byte) (c - '0');
}
return result;
}
public static String longMult(String num1, String num2) {
byte[] left = stringToDigits(num1);
byte[] right = stringToDigits(num2);
byte[] result = new byte[left.length + right.length];
for (int rightPos = 0; rightPos < right.length; rightPos++) {
byte rightDigit = right[rightPos];
byte temp = 0;
for (int leftPos = 0; leftPos < left.length; leftPos++) {
temp += result[leftPos + rightPos];
temp += rightDigit * left[leftPos];
result[leftPos + rightPos] = (byte) (temp % 10);
temp /= 10;
}
int destPos = rightPos + left.length;
while (temp != 0) {
temp += result[destPos] & 0xFFFFFFFFL;
result[destPos] = (byte) (temp % 10);
temp /= 10;
destPos++;
}
}
StringBuilder stringResultBuilder = new StringBuilder(result.length);
for (int i = result.length - 1; i >= 0; i--) {
byte digit = result[i];
if (digit != 0 || stringResultBuilder.length() > 0) {
stringResultBuilder.append((char) (digit + '0'));
}
}
return stringResultBuilder.toString();
}
public static void main(String[] args) {
System.out.println(longMult("18446744073709551616",
"18446744073709551616"));
}
}
| 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"); } }
}
|
Change the following Java code into C# without altering its purpose. | import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class PellsEquation {
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
for ( int n : new int[] {61, 109, 181, 277, 8941} ) {
BigInteger[] pell = pellsEquation(n);
System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1]));
}
}
private static final BigInteger[] pellsEquation(int n) {
int a0 = (int) Math.sqrt(n);
if ( a0*a0 == n ) {
throw new IllegalArgumentException("ERROR 102: Invalid n = " + n);
}
List<Integer> continuedFrac = continuedFraction(n);
int count = 0;
BigInteger ajm2 = BigInteger.ONE;
BigInteger ajm1 = new BigInteger(a0 + "");
BigInteger bjm2 = BigInteger.ZERO;
BigInteger bjm1 = BigInteger.ONE;
boolean stop = (continuedFrac.size() % 2 == 1);
if ( continuedFrac.size() == 2 ) {
stop = true;
}
while ( true ) {
count++;
BigInteger bn = new BigInteger(continuedFrac.get(count) + "");
BigInteger aj = bn.multiply(ajm1).add(ajm2);
BigInteger bj = bn.multiply(bjm1).add(bjm2);
if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {
return new BigInteger[] {aj, bj};
}
else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {
stop = true;
}
if ( count == continuedFrac.size()-1 ) {
count = 0;
}
ajm2 = ajm1;
ajm1 = aj;
bjm2 = bjm1;
bjm1 = bj;
}
}
private static final List<Integer> continuedFraction(int n) {
List<Integer> answer = new ArrayList<Integer>();
int a0 = (int) Math.sqrt(n);
answer.add(a0);
int a = -a0;
int aStart = a;
int b = 1;
int bStart = b;
while ( true ) {
int[] values = iterateFrac(n, a, b);
answer.add(values[0]);
a = values[1];
b = values[2];
if (a == aStart && b == bStart) break;
}
return answer;
}
private static final int[] iterateFrac(int n, int a, int b) {
int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));
int[] answer = new int[3];
answer[0] = x;
answer[1] = -(b * a + x *(n - a * a)) / b;
answer[2] = (n - a * a) / b;
return answer;
}
}
| 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);
}
}
}
|
Convert this Java block to C#, preserving its control flow and logic. | import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class BullsAndCows{
public static void main(String[] args){
Random gen= new Random();
int target;
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
String targetStr = target +"";
boolean guessed = false;
Scanner input = new Scanner(System.in);
int guesses = 0;
do{
int bulls = 0;
int cows = 0;
System.out.print("Guess a 4-digit number with no duplicate digits: ");
int guess;
try{
guess = input.nextInt();
if(hasDupes(guess) || guess < 1000) continue;
}catch(InputMismatchException e){
continue;
}
guesses++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}
}
if(bulls == 4){
guessed = true;
}else{
System.out.println(cows+" Cows and "+bulls+" Bulls.");
}
}while(!guessed);
System.out.println("You won after "+guesses+" guesses!");
}
public static boolean hasDupes(int num){
boolean[] digs = new boolean[10];
while(num > 0){
if(digs[num%10]) return true;
digs[num%10] = true;
num/= 10;
}
return false;
}
}
| 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;
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
boolean changed = false;
do {
changed = false;
for (int a = 0; a < comparable.length - 1; a++) {
if (comparable[a].compareTo(comparable[a + 1]) > 0) {
E tmp = comparable[a];
comparable[a] = comparable[a + 1];
comparable[a + 1] = tmp;
changed = true;
}
}
} while (changed);
}
| 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 + " ");
}
}
}
|
Produce a functionally identical C# code for the snippet given in Java. | import java.io.*;
public class FileIODemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("ouput.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
| 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 the same code in C# as shown below in Java. | import java.util.Scanner;
public class IntegerArithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;
int difference = a - b;
int product = a * b;
int division = a / b;
int remainder = a % b;
System.out.println("a + b = " + sum);
System.out.println("a - b = " + difference);
System.out.println("a * b = " + product);
System.out.println("quotient of a / b = " + division);
System.out.println("remainder of a / b = " + remainder);
}
}
| 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));
}
}
|
Can you help me rewrite this code in C# instead of Java, keeping it the same logically? | import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
double[][] m = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}};
double[][] ans = new double[m[0].length][m.length];
for(int rows = 0; rows < m.length; rows++){
for(int cols = 0; cols < m[0].length; cols++){
ans[cols][rows] = m[rows][cols];
}
}
for(double[] i:ans){
System.out.println(Arrays.toString(i));
}
}
}
| using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
double[,] t = Transpose( m );
for( int i=0; i<t.GetLength(0); i++ )
{
for( int j=0; j<t.GetLength(1); j++ )
Console.Write( t[i,j] + " " );
Console.WriteLine("");
}
}
public static double[,] Transpose( double[,] m )
{
double[,] t = new double[m.GetLength(1),m.GetLength(0)];
for( int i=0; i<m.GetLength(0); i++ )
for( int j=0; j<m.GetLength(1); j++ )
t[j,i] = m[i,j];
return t;
}
}
}
|
Can you help me rewrite this code in C# instead of Java, keeping it the same logically? | import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.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();
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | module test
{
@Inject Console console;
static Boolean show(String name, Boolean value)
{
console.print($"{name}()={value}");
return value;
}
void run()
{
val a = show("a", _);
val b = show("b", _);
for (Boolean v1 : False..True)
{
for (Boolean v2 : False..True)
{
console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}");
console.print();
console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}");
console.print();
}
}
}
}
| 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();
}
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Convert this Java block to C#, preserving its control flow and logic. | public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
| 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 Java to C#, ensuring the logic remains intact. | import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.Arrays;
import java.util.Random;
import javax.swing.*;
public class ImageNoise {
int framecount = 0;
int fps = 0;
BufferedImage image;
Kernel kernel;
ConvolveOp cop;
JFrame frame = new JFrame("Java Image Noise");
JPanel panel = new JPanel() {
private int show_fps = 0;
private MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
show_fps = (show_fps + 1) % 3;
}
};
{addMouseListener(ma);}
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
@Override
@SuppressWarnings("fallthrough")
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
drawNoise();
g.drawImage(image, 0, 0, null);
switch (show_fps) {
case 0:
int xblur = getWidth() - 130, yblur = getHeight() - 32;
BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);
BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
cop.filter(bc, bs);
g.drawImage(bs, xblur, yblur , null);
case 1:
g.setColor(Color.RED);
g.setFont(new Font("Monospaced", Font.BOLD, 20));
g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10);
}
framecount++;
}
};
Timer repainter = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
});
Timer framerateChecker = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fps = framecount;
framecount = 0;
}
});
public ImageNoise() {
float[] vals = new float[121];
Arrays.fill(vals, 1/121f);
kernel = new Kernel(11, 11, vals);
cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
repainter.start();
framerateChecker.start();
}
void drawNoise() {
int w = panel.getWidth(), h = panel.getHeight();
if (null == image || image.getWidth() != w || image.getHeight() != h) {
image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
}
Random rand = new Random();
int[] data = new int[w * h];
for (int x = 0; x < w * h / 32; x++) {
int r = rand.nextInt();
for (int i = 0; i < 32; i++) {
data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;
r >>>= 1;
}
}
image.getRaster().setPixels(0, 0, w, h, data);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ImageNoise i = new ImageNoise();
}
});
}
}
| 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();
}
}
|
Produce a language-to-language conversion: from Java to C#, same semantics. | public static boolean perf(int n){
int sum= 0;
for(int i= 1;i < n;i++){
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 ;
}
|
Keep all operations the same but rewrite the snippet in C#. | import java.math.BigInteger;
class IntegerPower {
public static void main(String[] args) {
BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());
String str = power.toString();
int len = str.length();
System.out.printf("5**4**3**2 = %s...%s and has %d digits%n",
str.substring(0, 20), str.substring(len - 20), len);
}
}
| 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 this Java snippet to C# and keep its semantics consistent. | package org.rosettacode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class InvertedIndex {
List<String> stopwords = Arrays.asList("a", "able", "about",
"across", "after", "all", "almost", "also", "am", "among", "an",
"and", "any", "are", "as", "at", "be", "because", "been", "but",
"by", "can", "cannot", "could", "dear", "did", "do", "does",
"either", "else", "ever", "every", "for", "from", "get", "got",
"had", "has", "have", "he", "her", "hers", "him", "his", "how",
"however", "i", "if", "in", "into", "is", "it", "its", "just",
"least", "let", "like", "likely", "may", "me", "might", "most",
"must", "my", "neither", "no", "nor", "not", "of", "off", "often",
"on", "only", "or", "other", "our", "own", "rather", "said", "say",
"says", "she", "should", "since", "so", "some", "than", "that",
"the", "their", "them", "then", "there", "these", "they", "this",
"tis", "to", "too", "twas", "us", "wants", "was", "we", "were",
"what", "when", "where", "which", "while", "who", "whom", "why",
"will", "with", "would", "yet", "you", "your");
Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();
List<String> files = new ArrayList<String>();
public void indexFile(File file) throws IOException {
int fileno = files.indexOf(file.getPath());
if (fileno == -1) {
files.add(file.getPath());
fileno = files.size() - 1;
}
int pos = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
for (String _word : line.split("\\W+")) {
String word = _word.toLowerCase();
pos++;
if (stopwords.contains(word))
continue;
List<Tuple> idx = index.get(word);
if (idx == null) {
idx = new LinkedList<Tuple>();
index.put(word, idx);
}
idx.add(new Tuple(fileno, pos));
}
}
System.out.println("indexed " + file.getPath() + " " + pos + " words");
}
public void search(List<String> words) {
for (String _word : words) {
Set<String> answer = new HashSet<String>();
String word = _word.toLowerCase();
List<Tuple> idx = index.get(word);
if (idx != null) {
for (Tuple t : idx) {
answer.add(files.get(t.fileno));
}
}
System.out.print(word);
for (String f : answer) {
System.out.print(" " + f);
}
System.out.println("");
}
}
public static void main(String[] args) {
try {
InvertedIndex idx = new InvertedIndex();
for (int i = 1; i < args.length; i++) {
idx.indexFile(new File(args[i]));
}
idx.search(Arrays.asList(args[0].split(",")));
} catch (Exception e) {
e.printStackTrace();
}
}
private class Tuple {
private int fileno;
private int position;
public Tuple(int fileno, int position) {
this.fileno = fileno;
this.position = position;
}
}
}
| 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]));
}
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | import java.util.Scanner;
public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
System.out.print("Enter the value of m:");
int m = aScanner.nextInt();
System.out.print("Enter the value of n:");
int n = aScanner.nextInt();
int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
if (lcm == 0) {
int mm = m, nn = n;
while (mm != nn) {
while (mm < nn) { mm += m; }
while (nn < mm) { nn += n; }
}
lcm = mm;
}
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}
| 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));
}
}
|
Please provide an equivalent version of this Java code in C#. | import java.util.Scanner;
public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
System.out.print("Enter the value of m:");
int m = aScanner.nextInt();
System.out.print("Enter the value of n:");
int n = aScanner.nextInt();
int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
if (lcm == 0) {
int mm = m, nn = n;
while (mm != nn) {
while (mm < nn) { mm += m; }
while (nn < mm) { nn += n; }
}
lcm = mm;
}
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}
| 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));
}
}
|
Please provide an equivalent version of this Java code in C#. | import java.util.Random;
Random rand = new Random();
while(true){
int a = rand.nextInt(20);
System.out.println(a);
if(a == 10) break;
int b = rand.nextInt(20);
System.out.println(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();
}
}
|
Please provide an equivalent version of this Java code in C#. | public class WaterBetweenTowers {
public static void main(String[] args) {
int i = 1;
int[][] tba = new int[][]{
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}
};
for (int[] tea : tba) {
int rht, wu = 0, bof;
do {
for (rht = tea.length - 1; rht >= 0; rht--) {
if (tea[rht] > 0) {
break;
}
}
if (rht < 0) {
break;
}
bof = 0;
for (int col = 0; col <= rht; col++) {
if (tea[col] > 0) {
tea[col]--;
bof += 1;
} else if (bof > 0) {
wu++;
}
}
if (bof < 2) {
break;
}
} while (true);
System.out.printf("Block %d", i++);
if (wu == 0) {
System.out.print(" does not hold any");
} else {
System.out.printf(" holds %d", wu);
}
System.out.println(" water units.");
}
}
}
| 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);
}
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. | package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
public class SumAndProductPuzzle {
private final long beginning;
private final int maxSum;
private static final int MIN_VALUE = 2;
private List<int[]> firstConditionExcludes = new ArrayList<>();
private List<int[]> secondConditionExcludes = new ArrayList<>();
public static void main(String... args){
if (args.length == 0){
new SumAndProductPuzzle(100).run();
new SumAndProductPuzzle(1684).run();
new SumAndProductPuzzle(1685).run();
} else {
for (String arg : args){
try{
new SumAndProductPuzzle(Integer.valueOf(arg)).run();
} catch (NumberFormatException e){
System.out.println("Please provide only integer arguments. " +
"Provided argument " + arg + " was not an integer. " +
"Alternatively, calling the program with no arguments " +
"will run the puzzle where maximum sum equals 100, 1684, and 1865.");
}
}
}
}
public SumAndProductPuzzle(int maxSum){
this.beginning = System.currentTimeMillis();
this.maxSum = maxSum;
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" started at " + String.valueOf(beginning) + ".");
}
public void run(){
for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){
for (int y = x + 1; y < maxSum - MIN_VALUE; y++){
if (isSumNoGreaterThanMax(x,y) &&
isSKnowsPCannotKnow(x,y) &&
isPKnowsNow(x,y) &&
isSKnowsNow(x,y)
){
System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) +
" in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
}
}
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
public boolean isSumNoGreaterThanMax(int x, int y){
return x + y <= maxSum;
}
public boolean isSKnowsPCannotKnow(int x, int y){
if (firstConditionExcludes.contains(new int[] {x, y})){
return false;
}
for (int[] addends : sumAddends(x, y)){
if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {
firstConditionExcludes.add(new int[] {x, y});
return false;
}
}
return true;
}
public boolean isPKnowsNow(int x, int y){
if (secondConditionExcludes.contains(new int[] {x, y})){
return false;
}
int countSolutions = 0;
for (int[] factors : productFactors(x, y)){
if (isSKnowsPCannotKnow(factors[0], factors[1])){
countSolutions++;
}
}
if (countSolutions == 1){
return true;
} else {
secondConditionExcludes.add(new int[] {x, y});
return false;
}
}
public boolean isSKnowsNow(int x, int y){
int countSolutions = 0;
for (int[] addends : sumAddends(x, y)){
if (isPKnowsNow(addends[0], addends[1])){
countSolutions++;
}
}
return countSolutions == 1;
}
public List<int[]> sumAddends(int x, int y){
List<int[]> list = new ArrayList<>();
int sum = x + y;
for (int addend = MIN_VALUE; addend < sum - addend; addend++){
if (isSumNoGreaterThanMax(addend, sum - addend)){
list.add(new int[]{addend, sum - addend});
}
}
return list;
}
public List<int[]> productFactors(int x, int y){
List<int[]> list = new ArrayList<>();
int product = x * y;
for (int factor = MIN_VALUE; factor < product / factor; factor++){
if (product % factor == 0){
if (isSumNoGreaterThanMax(factor, product / factor)){
list.add(new int[]{factor, product / factor});
}
}
}
return list;
}
}
| 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);
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Java version. | import java.util.Stack;
public class ShuntingYard {
public static void main(String[] args) {
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
System.out.printf("infix: %s%n", infix);
System.out.printf("postfix: %s%n", infixToPostfix(infix));
}
static String infixToPostfix(String infix) {
final String ops = "-+/*^";
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
for (String token : infix.split("\\s")) {
if (token.isEmpty())
continue;
char c = token.charAt(0);
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 > prec1 || (prec2 == prec1 && c != '^'))
sb.append(ops.charAt(s.pop())).append(' ');
else break;
}
s.push(idx);
}
}
else if (c == '(') {
s.push(-2);
}
else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop())).append(' ');
s.pop();
}
else {
sb.append(token).append(' ');
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop())).append(' ');
return sb.toString();
}
}
| 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)} ]");
}
}
|
Ensure the translated C# code behaves exactly like the original Java snippet. | import java.util.Stack;
public class ShuntingYard {
public static void main(String[] args) {
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
System.out.printf("infix: %s%n", infix);
System.out.printf("postfix: %s%n", infixToPostfix(infix));
}
static String infixToPostfix(String infix) {
final String ops = "-+/*^";
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
for (String token : infix.split("\\s")) {
if (token.isEmpty())
continue;
char c = token.charAt(0);
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 > prec1 || (prec2 == prec1 && c != '^'))
sb.append(ops.charAt(s.pop())).append(' ');
else break;
}
s.push(idx);
}
}
else if (c == '(') {
s.push(-2);
}
else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop())).append(' ');
s.pop();
}
else {
sb.append(token).append(' ');
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop())).append(' ');
return sb.toString();
}
}
| 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 a version of this Java function in C# with identical behavior. | public class MiddleThreeDigits {
public static void main(String[] args) {
final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};
final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,
Integer.MAX_VALUE};
for (long n : passing)
System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
for (int n : failing)
System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
}
public static <T> String middleThreeDigits(T n) {
String s = String.valueOf(n);
if (s.charAt(0) == '-')
s = s.substring(1);
int len = s.length();
if (len < 3 || len % 2 == 0)
return "Need odd and >= 3 digits";
int mid = len / 2;
return s.substring(mid - 1, mid + 2);
}
}
| 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));
}
}
}
|
Write the same algorithm in C# as shown in this Java implementation. | import java.math.BigInteger;
import java.util.LinkedList;
public class SternBrocot {
static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
add(1); add(1);
}};
private static void genSeq(int n){
for(int conIdx = 1; sequence.size() < n; conIdx++){
int consider = sequence.get(conIdx);
int pre = sequence.get(conIdx - 1);
sequence.add(consider + pre);
sequence.add(consider);
}
}
public static void main(String[] args){
genSeq(1200);
System.out.println("The first 15 elements are: " + sequence.subList(0, 15));
for(int i = 1; i <= 10; i++){
System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1));
}
System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1));
boolean failure = false;
for(int i = 0; i < 999; i++){
failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);
}
System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
}
}
| 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 ");
}
}
|
Translate the given Java code snippet into C# without altering its behavior. |
public class Doc{
private String field;
public int method(long num) throws BadException{
}
}
|
public static class XMLSystem
{
static XMLSystem()
{
}
public static XmlDocument GetXML(string name)
{
return null;
}
}
|
Please provide an equivalent version of this Java code in C#. |
public class Doc{
private String field;
public int method(long num) throws BadException{
}
}
|
public static class XMLSystem
{
static XMLSystem()
{
}
public static XmlDocument GetXML(string name)
{
return null;
}
}
|
Write the same code in C# as shown below in Java. | public class Circle
{
public double[] center;
public double radius;
public Circle(double[] center, double radius)
{
this.center = center;
this.radius = radius;
}
public String toString()
{
return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1],
radius);
}
}
public class ApolloniusSolver
{
public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,
int s2, int s3)
{
float x1 = c1.center[0];
float y1 = c1.center[1];
float r1 = c1.radius;
float x2 = c2.center[0];
float y2 = c2.center[1];
float r2 = c2.radius;
float x3 = c3.center[0];
float y3 = c3.center[1];
float r3 = c3.radius;
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;
float rs = (-b-Math.sqrt(D))/(2*a);
float xs = M + N * rs;
float ys = P + Q * rs;
return new Circle(new double[]{xs,ys}, rs);
}
public static void main(final String[] args)
{
Circle c1 = new Circle(new double[]{0,0}, 1);
Circle c2 = new Circle(new double[]{4,0}, 1);
Circle c3 = new Circle(new double[]{2,4}, 2);
System.out.println(solveApollonius(c1,c2,c3,1,1,1));
System.out.println(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;
}
}
}
|
Generate an equivalent C# version of this Java code. | import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
new Thread(new Client(s)).start();
}
}
catch (Exception e)
{ e.printStackTrace(); }
}
private synchronized boolean registerClient(Client client)
{
for (Client otherClient : clients)
if (otherClient.clientName.equalsIgnoreCase(client.clientName))
return false;
clients.add(client);
return true;
}
private void deregisterClient(Client client)
{
boolean wasRegistered = false;
synchronized (this)
{ wasRegistered = clients.remove(client); }
if (wasRegistered)
broadcast(client, "--- " + client.clientName + " left ---");
}
private synchronized String getOnlineListCSV()
{
StringBuilder sb = new StringBuilder();
sb.append(clients.size()).append(" user(s) online: ");
for (int i = 0; i < clients.size(); i++)
sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName);
return sb.toString();
}
private void broadcast(Client fromClient, String msg)
{
List<Client> clients = null;
synchronized (this)
{ clients = new ArrayList<Client>(this.clients); }
for (Client client : clients)
{
if (client.equals(fromClient))
continue;
try
{ client.write(msg + "\r\n"); }
catch (Exception e)
{ }
}
}
public class Client implements Runnable
{
private Socket socket = null;
private Writer output = null;
private String clientName = null;
public Client(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
socket.setSendBufferSize(16384);
socket.setTcpNoDelay(true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new OutputStreamWriter(socket.getOutputStream());
write("Please enter your name: ");
String line = null;
while ((line = input.readLine()) != null)
{
if (clientName == null)
{
line = line.trim();
if (line.isEmpty())
{
write("A name is required. Please enter your name: ");
continue;
}
clientName = line;
if (!registerClient(this))
{
clientName = null;
write("Name already registered. Please enter your name: ");
continue;
}
write(getOnlineListCSV() + "\r\n");
broadcast(this, "+++ " + clientName + " arrived +++");
continue;
}
if (line.equalsIgnoreCase("/quit"))
return;
broadcast(this, clientName + "> " + line);
}
}
catch (Exception e)
{ }
finally
{
deregisterClient(this);
output = null;
try
{ socket.close(); }
catch (Exception e)
{ }
socket = null;
}
}
public void write(String msg) throws IOException
{
output.write(msg);
output.flush();
}
public boolean equals(Client client)
{
return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);
}
}
public static void main(String[] args)
{
int port = 4004;
if (args.length > 0)
port = Integer.parseInt(args[0]);
new ChatServer(port).run();
}
}
| 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);
}
}
}
}
}
|
Write the same algorithm in C# as shown in this Java implementation. | import java.io.*;
import java.util.Scanner;
public class ReadFastaFile {
public static void main(String[] args) throws FileNotFoundException {
boolean first = true;
try (Scanner sc = new Scanner(new File("test.fasta"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.charAt(0) == '>') {
if (first)
first = false;
else
System.out.println();
System.out.printf("%s: ", line.substring(1));
} else {
System.out.print(line);
}
}
}
System.out.println();
}
}
| 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();
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
| 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;
}
}
|
Write the same algorithm in C# as shown in this Java implementation. | public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
| 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;
}
}
|
Change the programming language of this snippet from Java to C# without modifying what it does. | import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
| 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", ""));
}
}
}
|
Change the following Java code into C# without altering its purpose. | import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
| 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", ""));
}
}
}
|
Transform the following Java implementation into C#, maintaining the same output and logic. | char a = 'a';
String b = "abc";
char doubleQuote = '"';
char singleQuote = '\'';
String singleQuotes = "''";
String doubleQuotes = "\"\"";
| string path = @"C:\Windows\System32";
string multiline = @"Line 1.
Line 2.
Line 3.";
|
Translate the given Java code snippet into C# without altering its behavior. | import java.awt.*;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
Test() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
System.out.println("Physical screen size: " + screenSize);
Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());
System.out.println("Insets: " + insets);
screenSize.width -= (insets.left + insets.right);
screenSize.height -= (insets.top + insets.bottom);
System.out.println("Max available: " + screenSize);
}
}
| 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}");
}
}
|
Generate a C# translation of this Java snippet without changing its computational steps. | enum Fruits{
APPLE, BANANA, CHERRY
}
| 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 }
|
Translate the given Java code snippet into C# without altering its behavior. | package hu.pj.alg;
import hu.pj.obj.Item;
import java.text.*;
public class UnboundedKnapsack {
protected Item [] items = {
new Item("panacea", 3000, 0.3, 0.025),
new Item("ichor" , 1800, 0.2, 0.015),
new Item("gold" , 2500, 2.0, 0.002)
};
protected final int n = items.length;
protected Item sack = new Item("sack" , 0, 25.0, 0.250);
protected Item best = new Item("best" , 0, 0.0, 0.000);
protected int [] maxIt = new int [n];
protected int [] iIt = new int [n];
protected int [] bestAm = new int [n];
public UnboundedKnapsack() {
for (int i = 0; i < n; i++) {
maxIt [i] = Math.min(
(int)(sack.getWeight() / items[i].getWeight()),
(int)(sack.getVolume() / items[i].getVolume())
);
}
calcWithRecursion(0);
NumberFormat nf = NumberFormat.getInstance();
System.out.println("Maximum value achievable is: " + best.getValue());
System.out.print("This is achieved by carrying (one solution): ");
for (int i = 0; i < n; i++) {
System.out.print(bestAm[i] + " " + items[i].getName() + ", ");
}
System.out.println();
System.out.println("The weight to carry is: " + nf.format(best.getWeight()) +
" and the volume used is: " + nf.format(best.getVolume())
);
}
public void calcWithRecursion(int item) {
for (int i = 0; i <= maxIt[item]; i++) {
iIt[item] = i;
if (item < n-1) {
calcWithRecursion(item+1);
} else {
int currVal = 0;
double currWei = 0.0;
double currVol = 0.0;
for (int j = 0; j < n; j++) {
currVal += iIt[j] * items[j].getValue();
currWei += iIt[j] * items[j].getWeight();
currVol += iIt[j] * items[j].getVolume();
}
if (currVal > best.getValue()
&&
currWei <= sack.getWeight()
&&
currVol <= sack.getVolume()
)
{
best.setValue (currVal);
best.setWeight(currWei);
best.setVolume(currVol);
for (int j = 0; j < n; j++) bestAm[j] = iIt[j];
}
}
}
}
public static void main(String[] args) {
new UnboundedKnapsack();
}
}
|
using System;
class Program
{
static void Main()
{
uint[] r = items1();
Console.WriteLine(r[0] + " v " + r[1] + " a " + r[2] + " b");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 1000; i > 0; i--) items1();
Console.Write(sw.Elapsed); Console.Read();
}
static uint[] items0()
{
uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;
for (a = 0; a <= 10; a++)
for (b = 0; a * 5 + b * 3 <= 50; b++)
for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)
if (v0 < (v = a * 30 + b * 18 + c * 25))
{
v0 = v; a0 = a; b0 = b; c0 = c;
}
return new uint[] { a0, b0, c0 };
}
static uint[] items1()
{
uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;
for (a = 0; a <= 10; a++)
for (b = 0; a * 5 + b * 3 <= 50; b++)
{
c = (250 - a * 25 - b * 15) / 2;
if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;
if (v0 < (v = a * 30 + b * 18 + c * 25))
{ v0 = v; a0 = a; b0 = b; c0 = c; }
}
return new uint[] { a0, b0, c0 };
}
}
|
Write the same code in C# as shown below in Java. | public class RangeExtraction {
public static void main(String[] args) {
int[] arr = {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};
int len = arr.length;
int idx = 0, idx2 = 0;
while (idx < len) {
while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
if (idx2 - idx > 2) {
System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
idx = idx2;
} else {
for (; idx < idx2; idx++)
System.out.printf("%s,", arr[idx]);
}
}
}
}
| 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();
}
}
}
}
|
Port the provided Java code into C# while preserving the original functionality. | public class RangeExtraction {
public static void main(String[] args) {
int[] arr = {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};
int len = arr.length;
int idx = 0, idx2 = 0;
while (idx < len) {
while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
if (idx2 - idx > 2) {
System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
idx = idx2;
} else {
for (; idx < idx2; idx++)
System.out.printf("%s,", arr[idx]);
}
}
}
}
| 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();
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | public class TypeDetection {
private static void showType(Object a) {
if (a instanceof Integer) {
System.out.printf("'%s' is an integer\n", a);
} else if (a instanceof Double) {
System.out.printf("'%s' is a double\n", a);
} else if (a instanceof Character) {
System.out.printf("'%s' is a character\n", a);
} else {
System.out.printf("'%s' is some other type\n", a);
}
}
public static void main(String[] args) {
showType(5);
showType(7.5);
showType('d');
showType(true);
}
}
| using System;
namespace TypeDetection {
class C { }
struct S { }
enum E {
NONE,
}
class Program {
static void ShowType<T>(T t) {
Console.WriteLine("The type of '{0}' is {1}", t, t.GetType());
}
static void Main() {
ShowType(5);
ShowType(7.5);
ShowType('d');
ShowType(true);
ShowType("Rosetta");
ShowType(new C());
ShowType(new S());
ShowType(E.NONE);
ShowType(new int[] { 1, 2, 3 });
}
}
}
|
Write the same code in C# as shown below in Java. | import java.nio.file.*;
import static java.util.Arrays.stream;
public class MaxPathSum {
public static void main(String[] args) throws Exception {
int[][] data = Files.lines(Paths.get("triangle.txt"))
.map(s -> stream(s.trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
for (int r = data.length - 1; r > 0; r--)
for (int c = 0; c < data[r].length - 1; c++)
data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);
System.out.println(data[0][0]);
}
}
| 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]));
}
}
}
|
Change the following Java code into C# without altering its purpose. | public class GateLogic
{
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]),
AND.eval(inputs[0], inputs[1])
};
}
};
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0],
OR.eval(haOutputs1[1], haOutputs2[1])
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1];
faInputs[1] = inputs[i];
faInputs[2] = inputs[numBits + i];
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0];
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1];
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
| 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 the same algorithm in C# as shown in this Java implementation. | public class GateLogic
{
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]),
AND.eval(inputs[0], inputs[1])
};
}
};
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0],
OR.eval(haOutputs1[1], haOutputs2[1])
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1];
faInputs[1] = inputs[i];
faInputs[2] = inputs[numBits + i];
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0];
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1];
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
| 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 ( );
}
}
}
|
Produce a functionally identical C# code for the snippet given in Java. | package rosetta;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnixLS {
public static void main(String[] args) throws IOException {
Files.list(Path.of("")).sorted().forEach(System.out::println);
}
}
| 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);
}
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original Java code. | import java.nio.charset.StandardCharsets;
import java.util.Formatter;
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) {
return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}
public static int utf8decode(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}
public static void main(String[] args) {
System.out.printf("%-7s %-43s %7s\t%s\t%7s%n",
"Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
byte[] encoded = utf8encode(codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
formatter.format("%02X ", b);
}
String encodedHex = formatter.toString();
int decoded = utf8decode(encoded);
System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n",
codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
}
}
}
| 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));
}
}
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. | public class MagicSquareDoublyEven {
public static void main(String[] args) {
int n = 8;
for (int[] row : magicSquareDoublyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
static int[][] magicSquareDoublyEven(final int n) {
if (n < 4 || n % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4");
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4;
int[][] result = new int[n][n];
for (int r = 0, i = 0; r < n; r++) {
for (int c = 0; c < n; c++, i++) {
int bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
| using System;
namespace MagicSquareDoublyEven
{
class Program
{
static void Main(string[] args)
{
int n = 8;
var result = MagicSquareDoublyEven(n);
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write("{0,2} ", result[i, j]);
Console.WriteLine();
}
Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
Console.ReadLine();
}
private static int[,] MagicSquareDoublyEven(int n)
{
if (n < 4 || n % 4 != 0)
throw new ArgumentException("base must be a positive "
+ "multiple of 4");
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4;
int[,] result = new int[n, n];
for (int r = 0, i = 0; r < n; r++)
{
for (int c = 0; c < n; c++, i++)
{
int bitPos = c / mult + (r / mult) * 4;
result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.util.*;
class SameFringe
{
public interface Node<T extends Comparable<? super T>>
{
Node<T> getLeft();
Node<T> getRight();
boolean isLeaf();
T getData();
}
public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>
{
private final T data;
public SimpleNode<T> left;
public SimpleNode<T> right;
public SimpleNode(T data)
{ this(data, null, null); }
public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public Node<T> getLeft()
{ return left; }
public Node<T> getRight()
{ return right; }
public boolean isLeaf()
{ return ((left == null) && (right == null)); }
public T getData()
{ return data; }
public SimpleNode<T> addToTree(T data)
{
int cmp = data.compareTo(this.data);
if (cmp == 0)
throw new IllegalArgumentException("Same data!");
if (cmp < 0)
{
if (left == null)
return (left = new SimpleNode<T>(data));
return left.addToTree(data);
}
if (right == null)
return (right = new SimpleNode<T>(data));
return right.addToTree(data);
}
}
public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)
{
Stack<Node<T>> stack1 = new Stack<Node<T>>();
Stack<Node<T>> stack2 = new Stack<Node<T>>();
stack1.push(node1);
stack2.push(node2);
while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))
if (!node1.getData().equals(node2.getData()))
return false;
return (node1 == null) && (node2 == null);
}
private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)
{
while (!stack.isEmpty())
{
Node<T> node = stack.pop();
if (node.isLeaf())
return node;
Node<T> rightNode = node.getRight();
if (rightNode != null)
stack.push(rightNode);
Node<T> leftNode = node.getLeft();
if (leftNode != null)
stack.push(leftNode);
}
return null;
}
public static void main(String[] args)
{
SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));
SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));
SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));
System.out.print("Leaves for set 1: ");
simpleWalk(headNode1);
System.out.println();
System.out.print("Leaves for set 2: ");
simpleWalk(headNode2);
System.out.println();
System.out.print("Leaves for set 3: ");
simpleWalk(headNode3);
System.out.println();
System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2));
System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3));
}
public static void simpleWalk(Node<Integer> node)
{
if (node.isLeaf())
System.out.print(node.getData() + " ");
else
{
Node<Integer> left = node.getLeft();
if (left != null)
simpleWalk(left);
Node<Integer> right = node.getRight();
if (right != null)
simpleWalk(right);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Same_Fringe
{
class Program
{
static void Main()
{
var rnd = new Random(110456);
var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();
var bt1 = new BinTree<int>(randList);
Shuffle(randList, 428);
var bt2 = new BinTree<int>(randList);
Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed");
bt1.Insert(0);
Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked");
}
static void Shuffle<T>(List<T> values, int seed)
{
var rnd = new Random(seed);
for (var i = 0; i < values.Count - 2; i++)
{
var iSwap = rnd.Next(values.Count - i) + i;
var tmp = values[iSwap];
values[iSwap] = values[i];
values[i] = tmp;
}
}
}
class BinTree<T> where T:IComparable
{
private BinTree<T> _left;
private BinTree<T> _right;
private T _value;
private BinTree<T> Left
{
get { return _left; }
}
private BinTree<T> Right
{
get { return _right; }
}
private T Value
{
get { return _value; }
}
public bool IsLeaf { get { return Left == null; } }
private BinTree(BinTree<T> left, BinTree<T> right, T value)
{
_left = left;
_right = right;
_value = value;
}
public BinTree(T value) : this(null, null, value) { }
public BinTree(IEnumerable<T> values)
{
_value = values.First();
foreach (var value in values.Skip(1))
{
Insert(value);
}
}
public void Insert(T value)
{
if (IsLeaf)
{
if (value.CompareTo(Value) < 0)
{
_left = new BinTree<T>(value);
_right = new BinTree<T>(Value);
}
else
{
_left = new BinTree<T>(Value);
_right = new BinTree<T>(value);
_value = value;
}
}
else
{
if (value.CompareTo(Value) < 0)
{
Left.Insert(value);
}
else
{
Right.Insert(value);
}
}
}
public IEnumerable<T> GetLeaves()
{
if (IsLeaf)
{
yield return Value;
yield break;
}
foreach (var val in Left.GetLeaves())
{
yield return val;
}
foreach (var val in Right.GetLeaves())
{
yield return val;
}
}
internal bool CompareTo(BinTree<T> other)
{
return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position pos = (Position) obj;
return pos.x == x && pos.y == y;
}
return false;
}
}
private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
boolean placingBlack = true;
for (int i = 0; i < n; ++i) {
inner:
for (int j = 0; j < n; ++j) {
Position pos = new Position(i, j);
for (Position queen : pBlackQueens) {
if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
for (Position queen : pWhiteQueens) {
if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
if (placingBlack) {
pBlackQueens.add(pos);
placingBlack = false;
} else {
pWhiteQueens.add(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.remove(pBlackQueens.size() - 1);
pWhiteQueens.remove(pWhiteQueens.size() - 1);
placingBlack = true;
}
}
}
if (!placingBlack) {
pBlackQueens.remove(pBlackQueens.size() - 1);
}
return false;
}
private static boolean isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);
}
private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
Piece[] board = new Piece[n * n];
Arrays.fill(board, Piece.Empty);
for (Position queen : blackQueens) {
board[queen.x + n * queen.y] = Piece.Black;
}
for (Position queen : whiteQueens) {
board[queen.x + n * queen.y] = Piece.White;
}
for (int i = 0; i < board.length; ++i) {
if ((i != 0) && i % n == 0) {
System.out.println();
}
Piece b = board[i];
if (b == Piece.Black) {
System.out.print("B ");
} else if (b == Piece.White) {
System.out.print("W ");
} else {
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
System.out.print("• ");
} else {
System.out.print("◦ ");
}
}
}
System.out.println('\n');
}
public static void main(String[] args) {
List<Position> nms = List.of(
new Position(2, 1),
new Position(3, 1),
new Position(3, 2),
new Position(4, 1),
new Position(4, 2),
new Position(4, 3),
new Position(5, 1),
new Position(5, 2),
new Position(5, 3),
new Position(5, 4),
new Position(5, 5),
new Position(6, 1),
new Position(6, 2),
new Position(6, 3),
new Position(6, 4),
new Position(6, 5),
new Position(6, 6),
new Position(7, 1),
new Position(7, 2),
new Position(7, 3),
new Position(7, 4),
new Position(7, 5),
new Position(7, 6),
new Position(7, 7)
);
for (Position nm : nms) {
int m = nm.y;
int n = nm.x;
System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n);
List<Position> blackQueens = new ArrayList<>();
List<Position> whiteQueens = new ArrayList<>();
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens);
} else {
System.out.println("No solution exists.\n");
}
}
}
}
| using System;
using System.Collections.Generic;
namespace PeacefulChessQueenArmies {
using Position = Tuple<int, int>;
enum Piece {
Empty,
Black,
White
}
class Program {
static bool IsAttacking(Position queen, Position pos) {
return queen.Item1 == pos.Item1
|| queen.Item2 == pos.Item2
|| Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);
}
static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
bool placingBlack = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
var pos = new Position(i, j);
foreach (var queen in pBlackQueens) {
if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {
goto inner;
}
}
foreach (var queen in pWhiteQueens) {
if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {
goto inner;
}
}
if (placingBlack) {
pBlackQueens.Add(pos);
placingBlack = false;
} else {
pWhiteQueens.Add(pos);
if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.RemoveAt(pBlackQueens.Count - 1);
pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);
placingBlack = true;
}
inner: { }
}
}
if (!placingBlack) {
pBlackQueens.RemoveAt(pBlackQueens.Count - 1);
}
return false;
}
static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
var board = new Piece[n * n];
foreach (var queen in blackQueens) {
board[queen.Item1 * n + queen.Item2] = Piece.Black;
}
foreach (var queen in whiteQueens) {
board[queen.Item1 * n + queen.Item2] = Piece.White;
}
for (int i = 0; i < board.Length; i++) {
if (i != 0 && i % n == 0) {
Console.WriteLine();
}
switch (board[i]) {
case Piece.Black:
Console.Write("B ");
break;
case Piece.White:
Console.Write("W ");
break;
case Piece.Empty:
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
Console.Write(" ");
} else {
Console.Write("# ");
}
break;
}
}
Console.WriteLine("\n");
}
static void Main() {
var nms = new int[,] {
{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
{5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
{6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
{7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
};
for (int i = 0; i < nms.GetLength(0); i++) {
Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]);
List<Position> blackQueens = new List<Position>();
List<Position> whiteQueens = new List<Position>();
if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {
PrintBoard(nms[i, 0], blackQueens, whiteQueens);
} else {
Console.WriteLine("No solution exists.\n");
}
}
}
}
}
|
Change the following Java code into C# without altering its purpose. | import java.util.LinkedList;
import java.util.List;
public class MTF{
public static List<Integer> encode(String msg, String symTable){
List<Integer> output = new LinkedList<Integer>();
StringBuilder s = new StringBuilder(symTable);
for(char c : msg.toCharArray()){
int idx = s.indexOf("" + c);
output.add(idx);
s = s.deleteCharAt(idx).insert(0, c);
}
return output;
}
public static String decode(List<Integer> idxs, String symTable){
StringBuilder output = new StringBuilder();
StringBuilder s = new StringBuilder(symTable);
for(int idx : idxs){
char c = s.charAt(idx);
output = output.append(c);
s = s.deleteCharAt(idx).insert(0, c);
}
return output.toString();
}
private static void test(String toEncode, String symTable){
List<Integer> encoded = encode(toEncode, symTable);
System.out.println(toEncode + ": " + encoded);
String decoded = decode(encoded, symTable);
System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
}
public static void main(String[] args){
String symTable = "abcdefghijklmnopqrstuvwxyz";
test("broood", symTable);
test("bananaaa", symTable);
test("hiphophiphop", symTable);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace MoveToFront
{
class Program
{
private static char[] symbolTable;
private static void setSymbolTable()
{
symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
}
private static void moveToFront(int charIndex)
{
char toFront = symbolTable[charIndex];
for (int j = charIndex; j > 0; j--)
{
symbolTable[j] = symbolTable[j - 1];
}
symbolTable[0] = toFront;
}
public static int[] Encode(string input)
{
setSymbolTable();
var output = new List<int>();
foreach (char c in input)
{
for (int i = 0; i < 26; i++)
{
if (symbolTable[i] == c)
{
output.Add(i);
moveToFront(i);
break;
}
}
}
return output.ToArray();
}
public static string Decode(int[] input)
{
setSymbolTable();
var output = new StringBuilder(input.Length);
foreach (int n in input)
{
output.Append(symbolTable[n]);
moveToFront(n);
}
return output.ToString();
}
static void Main(string[] args)
{
string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" };
int[] encoding;
foreach (string s in testInputs)
{
Console.WriteLine($"Encoding for '{s}':");
encoding = Encode(s);
foreach (int i in encoding)
{
Console.Write($"{i} ");
}
Console.WriteLine($"\nDecoding for '{s}':");
Console.WriteLine($"{Decode(encoding)}\n");
}
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System.out.println(sc.nextLine());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
| using System.Diagnostics;
namespace Execute
{
class Program
{
static void Main(string[] args)
{
Process.Start("cmd.exe", "/c dir");
}
}
}
|
Port the provided Java code into C# while preserving the original functionality. | import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.ws.Holder;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XmlValidation {
public static void main(String... args) throws MalformedURLException {
URL schemaLocation = new URL("http:
URL documentLocation = new URL("http:
if (validate(schemaLocation, documentLocation)) {
System.out.println("document is valid");
} else {
System.out.println("document is invalid");
}
}
public static boolean minimalValidate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.validate(new StreamSource(documentLocation.toString()));
return true;
} catch (Exception e) {
return false;
}
}
public static boolean validate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
final Holder<Boolean> valid = new Holder<>(true);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.setErrorHandler(new ErrorHandler(){
@Override
public void warning(SAXParseException exception) {
System.out.println("warning: " + exception.getMessage());
}
@Override
public void error(SAXParseException exception) {
System.out.println("error: " + exception.getMessage());
valid.value = false;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatal error: " + exception.getMessage());
throw exception;
}});
validator.validate(new StreamSource(documentLocation.toString()));
return valid.value;
} catch (SAXException e) {
return false;
} catch (Exception e) {
System.err.println(e);
return false;
}
}
}
| using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class Test
{
public static void Main()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, "http:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
XmlReader reader = XmlReader.Create("http:
while (reader.Read());
Console.WriteLine("The XML file is valid for the given xsd file");
}
private static void ValidationCallBack(object sender, ValidationEventArgs e) {
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | import java.util.*;
public class LIS {
public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
List<Node<E>> pileTops = new ArrayList<Node<E>>();
for (E x : n) {
Node<E> node = new Node<E>();
node.value = x;
int i = Collections.binarySearch(pileTops, node);
if (i < 0) i = ~i;
if (i != 0)
node.pointer = pileTops.get(i-1);
if (i != pileTops.size())
pileTops.set(i, node);
else
pileTops.add(node);
}
List<E> result = new ArrayList<E>();
for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
node != null; node = node.pointer)
result.add(node.value);
Collections.reverse(result);
return result;
}
private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
public E value;
public Node<E> pointer;
public int compareTo(Node<E> y) { return value.compareTo(y.value); }
}
public static void main(String[] args) {
List<Integer> d = Arrays.asList(3,2,6,4,5,1);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class LIS
{
public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>
values == null ? throw new ArgumentNullException() :
FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();
private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {
if (index == values.Count) return current;
if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)
return FindRecImpl(values, current, index + 1, comparer);
return Max(
FindRecImpl(values, current, index + 1, comparer),
FindRecImpl(values, current + values[index], index + 1, comparer)
);
}
private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;
class Sequence<T> : IEnumerable<T>
{
public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);
public Sequence(T value, Sequence<T> tail)
{
Value = value;
Tail = tail;
Length = tail == null ? 0 : tail.Length + 1;
}
public T Value { get; }
public Sequence<T> Tail { get; }
public int Length { get; }
public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);
public IEnumerator<T> GetEnumerator()
{
for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
Please provide an equivalent version of this Java code in C#. | public
protected
private
static
public void function(int x){
int y;
{
int z;
}
}
| public
protected
internal
protected internal
private
private protected
|
Translate this program into C# but keep the logic exactly as in Java. | public class BraceExpansion {
public static void main(String[] args) {
for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) {
System.out.println();
expand(s);
}
}
public static void expand(String s) {
expandR("", s, "");
}
private static void expandR(String pre, String s, String suf) {
int i1 = -1, i2 = 0;
String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " ");
StringBuilder sb = null;
outer:
while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
i2 = i1 + 1;
sb = new StringBuilder(s);
for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
char c = noEscape.charAt(i2);
depth = (c == '{') ? ++depth : depth;
depth = (c == '}') ? --depth : depth;
if (c == ',' && depth == 1) {
sb.setCharAt(i2, '\u0000');
} else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1)
break outer;
}
}
if (i1 == -1) {
if (suf.length() > 0)
expandR(pre + s, suf, "");
else
System.out.printf("%s%s%s%n", pre, s, suf);
} else {
for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1))
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static System.Linq.Enumerable;
public static class BraceExpansion
{
enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }
const char L = '{', R = '}', S = ',';
public static void Main() {
string[] input = {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
@"{,{,gotta have{ ,\, again\, }}more }cowbell!",
@"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
};
foreach (string text in input) Expand(text);
}
static void Expand(string input) {
Token token = Tokenize(input);
foreach (string value in token) Console.WriteLine(value);
Console.WriteLine();
}
static Token Tokenize(string input) {
var tokens = new List<Token>();
var buffer = new StringBuilder();
bool escaping = false;
int level = 0;
foreach (char c in input) {
(escaping, level, tokens, buffer) = c switch {
_ when escaping => (false, level, tokens, buffer.Append(c)),
'\\' => (true, level, tokens, buffer.Append(c)),
L => (escaping, level + 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),
S when level > 0 => (escaping, level,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),
R when level > 0 => (escaping, level - 1,
tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),
_ => (escaping, level, tokens, buffer.Append(c))
};
}
if (buffer.Length > 0) tokens.Add(buffer.Flush());
for (int i = 0; i < tokens.Count; i++) {
if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {
tokens[i] = tokens[i].Value;
}
}
return new Token(tokens, TokenType.Concat);
}
static List<Token> Merge(this List<Token> list) {
int separators = 0;
int last = list.Count - 1;
for (int i = list.Count - 3; i >= 0; i--) {
if (list[i].Type == TokenType.Separator) {
separators++;
Concat(list, i + 1, last);
list.RemoveAt(i);
last = i;
} else if (list[i].Type == TokenType.OpenBrace) {
Concat(list, i + 1, last);
if (separators > 0) {
list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);
list.RemoveRange(i+1, list.Count - i - 1);
} else {
list[i] = L.ToString();
list[^1] = R.ToString();
Concat(list, i, list.Count);
}
break;
}
}
return list;
}
static void Concat(List<Token> list, int s, int e) {
for (int i = e - 2; i >= s; i--) {
(Token a, Token b) = (list[i], list[i+1]);
switch (a.Type, b.Type) {
case (TokenType.Text, TokenType.Text):
list[i] = a.Value + b.Value;
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Concat):
a.SubTokens.AddRange(b.SubTokens);
list.RemoveAt(i+1);
break;
case (TokenType.Concat, TokenType.Text) when b.Value == "":
list.RemoveAt(i+1);
break;
case (TokenType.Text, TokenType.Concat) when a.Value == "":
list.RemoveAt(i);
break;
default:
list[i] = new Token(new [] { a, b }, TokenType.Concat);
list.RemoveAt(i+1);
break;
}
}
}
private struct Token : IEnumerable<string>
{
private List<Token>? _subTokens;
public string Value { get; }
public TokenType Type { get; }
public List<Token> SubTokens => _subTokens ??= new List<Token>();
public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);
public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList());
public static implicit operator Token(string value) => new Token(value, TokenType.Text);
public IEnumerator<string> GetEnumerator() => (Type switch
{
TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)),
TokenType.Alternate => from t in SubTokens from s in t select s,
_ => Repeat(Value, 1)
}).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
static List<Token> With(this List<Token> list, Token token) {
list.Add(token);
return list;
}
static IEnumerable<Token> Range(this List<Token> list, Range range) {
int start = range.Start.GetOffset(list.Count);
int end = range.End.GetOffset(list.Count);
for (int i = start; i < end; i++) yield return list[i];
}
static string Flush(this StringBuilder builder) {
string result = builder.ToString();
builder.Clear();
return result;
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Interact extends JFrame{
final JTextField numberField;
final JButton incButton, randButton;
public Interact(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numberField = new JTextField();
incButton = new JButton("Increment");
randButton = new JButton("Random");
numberField.setText("0");
numberField.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {
if(!Character.isDigit(e.getKeyChar())){
e.consume();
}
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyPressed(KeyEvent e){}
});
incButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String text = numberField.getText();
if(text.isEmpty()){
numberField.setText("1");
}else{
numberField.setText((Long.valueOf(text) + 1) + "");
}
}
});
randButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(JOptionPane.showConfirmDialog(null, "Are you sure?") ==
JOptionPane.YES_OPTION){
numberField.setText(Long.toString((long)(Math.random()
* Long.MAX_VALUE)));
}
}
});
setLayout(new GridLayout(2, 1));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(incButton);
buttonPanel.add(randButton);
add(numberField);
add(buttonPanel);
pack();
}
public static void main(String[] args){
new Interact().setVisible(true);
}
}
| using System;
using System.ComponentModel;
using System.Windows.Forms;
class RosettaInteractionForm : Form
{
class NumberModel: INotifyPropertyChanged
{
Random rnd = new Random();
public event PropertyChangedEventHandler PropertyChanged = delegate {};
int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
public void ResetToRandom(){
Value = rnd.Next(5000);
}
}
NumberModel model = new NumberModel{ Value = 0};
RosettaInteractionForm()
{
var tbNumber = new MaskedTextBox
{
Mask="0000",
ResetOnSpace = false,
Dock = DockStyle.Top
};
tbNumber.DataBindings.Add("Text", model, "Value");
var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
btIncrement.Click += delegate
{
model.Value++;
};
var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
btDecrement.Click += delegate
{
model.Value--;
};
var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom };
btRandom.Click += delegate
{
if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
model.ResetToRandom();
};
Controls.Add(tbNumber);
Controls.Add(btIncrement);
Controls.Add(btDecrement);
Controls.Add(btRandom);
}
static void Main()
{
Application.Run(new RosettaInteractionForm());
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import java.util.Arrays;
import java.util.Random;
public class OneOfNLines {
static Random rand;
public static int oneOfN(int n) {
int choice = 0;
for(int i = 1; i < n; i++) {
if(rand.nextInt(i+1) == 0)
choice = i;
}
return choice;
}
public static void main(String[] args) {
int n = 10;
int trials = 1000000;
int[] bins = new int[n];
rand = new Random();
for(int i = 0; i < trials; i++)
bins[oneOfN(n)]++;
System.out.println(Arrays.toString(bins));
}
}
| class Program
{
private static Random rnd = new Random();
public static int one_of_n(int n)
{
int currentChoice = 1;
for (int i = 2; i <= n; i++)
{
double outerLimit = 1D / (double)i;
if (rnd.NextDouble() < outerLimit)
currentChoice = i;
}
return currentChoice;
}
static void Main(string[] args)
{
Dictionary<int, int> results = new Dictionary<int, int>();
for (int i = 1; i < 11; i++)
results.Add(i, 0);
for (int i = 0; i < 1000000; i++)
{
int result = one_of_n(10);
results[result] = results[result] + 1;
}
for (int i = 1; i < 11; i++)
Console.WriteLine("{0}\t{1}", i, results[i]);
Console.ReadLine();
}
}
|
Change the following Java code into C# without altering its purpose. | public class AdditionChains {
private static class Pair {
int f, s;
Pair(int f, int s) {
this.f = f;
this.s = s;
}
}
private static int[] prepend(int n, int[] seq) {
int[] result = new int[seq.length + 1];
result[0] = n;
System.arraycopy(seq, 0, result, 1, seq.length);
return result;
}
private static Pair check_seq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);
else if (seq[0] == n) return new Pair(pos, 1);
else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);
else return new Pair(min_len, 0);
}
private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Pair(min_len, 0);
Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);
Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);
if (res2.f < res1.f) return res2;
else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);
else throw new RuntimeException("Try_perm exception");
}
private static Pair init_try_perm(int x) {
return try_perm(0, 0, new int[]{1}, x, 12);
}
private static void find_brauer(int num) {
Pair res = init_try_perm(num);
System.out.println();
System.out.println("N = " + num);
System.out.println("Minimum length of chains: L(n)= " + res.f);
System.out.println("Number of minimum length Brauer chains: " + res.s);
}
public static void main(String[] args) {
int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};
for (int i : nums) {
find_brauer(i);
}
}
}
| using System;
namespace AdditionChains {
class Program {
static int[] Prepend(int n, int[] seq) {
int[] result = new int[seq.Length + 1];
Array.Copy(seq, 0, result, 1, seq.Length);
result[0] = n;
return result;
}
static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);
if (seq[0] == n) return new Tuple<int, int>(pos, 1);
if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);
return new Tuple<int, int>(min_len, 0);
}
static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Tuple<int, int>(min_len, 0);
Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);
Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);
if (res2.Item1 < res1.Item1) return res2;
if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);
throw new Exception("TryPerm exception");
}
static Tuple<int, int> InitTryPerm(int x) {
return TryPerm(0, 0, new int[] { 1 }, x, 12);
}
static void FindBrauer(int num) {
Tuple<int, int> res = InitTryPerm(num);
Console.WriteLine();
Console.WriteLine("N = {0}", num);
Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1);
Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2);
}
static void Main(string[] args) {
int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };
Array.ForEach(nums, n => FindBrauer(n));
}
}
}
|
Write the same algorithm in C# as shown in this Java implementation. | import java.util.function.Consumer;
import java.util.stream.IntStream;
public class Repeat {
public static void main(String[] args) {
repeat(3, (x) -> System.out.println("Example " + x));
}
static void repeat (int n, Consumer<Integer> fun) {
IntStream.range(0, n).forEach(i -> fun.accept(i + 1));
}
}
| using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 1);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
| public class Program
{
static void Main()
{
System.Console.WriteLine(42.ModInverse(2017));
}
}
public static class IntExtensions
{
public static int ModInverse(this int a, int m)
{
if (m == 1) return 0;
int m0 = m;
(int x, int y) = (1, 0);
while (a > 1) {
int q = a / m;
(a, m) = (m, a % m);
(x, y) = (y, x - q * y);
}
return x < 0 ? x + m0 : x;
}
}
|
Convert this Java snippet to C# and keep its semantics consistent. | import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloWorld{
public static void main(String[] args) throws IOException{
ServerSocket listener = new ServerSocket(8080);
while(true){
Socket sock = listener.accept();
new PrintWriter(sock.getOutputStream(), true).
println("Goodbye, World!");
sock.close();
}
}
}
| using System.Text;
using System.Net.Sockets;
using System.Net;
namespace WebServer
{
class GoodByeWorld
{
static void Main(string[] args)
{
const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";
const int port = 8080;
bool serverRunning = true;
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (serverRunning)
{
Socket socketConnection = tcpListener.AcceptSocket();
byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);
socketConnection.Send(bMsg);
socketConnection.Disconnect(true);
}
}
}
}
|
Generate a C# translation of this Java snippet without changing its computational steps. | import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloWorld{
public static void main(String[] args) throws IOException{
ServerSocket listener = new ServerSocket(8080);
while(true){
Socket sock = listener.accept();
new PrintWriter(sock.getOutputStream(), true).
println("Goodbye, World!");
sock.close();
}
}
}
| using System.Text;
using System.Net.Sockets;
using System.Net;
namespace WebServer
{
class GoodByeWorld
{
static void Main(string[] args)
{
const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";
const int port = 8080;
bool serverRunning = true;
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (serverRunning)
{
Socket socketConnection = tcpListener.AcceptSocket();
byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);
socketConnection.Send(bMsg);
socketConnection.Disconnect(true);
}
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Java version. | public class Clear
{
public static void main (String[] args)
{
System.out.print("\033[2J");
}
}
| System.Console.Clear();
|
Transform the following Java implementation into C#, maintaining the same output and logic. | import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapConnectionDemo {
public static void main(String[] args) throws LdapException, IOException {
try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
connection.bind();
connection.unBind();
}
}
}
|
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
|
Convert this Java snippet to C# and keep its semantics consistent. | import java.util.ArrayList;
import java.util.List;
public class PythagoreanQuadruples {
public static void main(String[] args) {
long d = 2200;
System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
}
private static List<Long> getPythagoreanQuadruples(long max) {
List<Long> list = new ArrayList<>();
long n = -1;
long m = -1;
while ( true ) {
long nTest = (long) Math.pow(2, n+1);
long mTest = (long) (5L * Math.pow(2, m+1));
long test = 0;
if ( nTest > mTest ) {
test = mTest;
m++;
}
else {
test = nTest;
n++;
}
if ( test < max ) {
list.add(test);
}
else {
break;
}
}
return list;
}
}
| using System;
namespace PythagoreanQuadruples {
class Program {
const int MAX = 2200;
const int MAX2 = MAX * MAX * 2;
static void Main(string[] args) {
bool[] found = new bool[MAX + 1];
bool[] a2b2 = new bool[MAX2 + 1];
int s = 3;
for(int a = 1; a <= MAX; a++) {
int a2 = a * a;
for (int b=a; b<=MAX; b++) {
a2b2[a2 + b * b] = true;
}
}
for (int c = 1; c <= MAX; c++) {
int s1 = s;
s += 2;
int s2 = s;
for (int d = c + 1; d <= MAX; d++) {
if (a2b2[s1]) found[d] = true;
s1 += s2;
s2 += 2;
}
}
Console.WriteLine("The values of d <= {0} which can't be represented:", MAX);
for (int d = 1; d < MAX; d++) {
if (!found[d]) Console.Write("{0} ", d);
}
Console.WriteLine();
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import java.util.*;
public class Sokoban {
String destBoard, currBoard;
int playerX, playerY, nCols;
Sokoban(String[] board) {
nCols = board[0].length();
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < nCols; c++) {
char ch = board[r].charAt(c);
destBuf.append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.append(ch != '.' ? ch : ' ');
if (ch == '@') {
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.toString();
currBoard = currBuf.toString();
}
String move(int x, int y, int dx, int dy, String trialBoard) {
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard.charAt(newPlayerPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new String(trial);
}
String push(int x, int y, int dx, int dy, String trialBoard) {
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard.charAt(newBoxPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new String(trial);
}
boolean isSolved(String trialBoard) {
for (int i = 0; i < trialBoard.length(); i++)
if ((destBoard.charAt(i) == '.')
!= (trialBoard.charAt(i) == '$'))
return false;
return true;
}
String solve() {
class Board {
String cur, sol;
int x, y;
Board(String s1, String s2, int px, int py) {
cur = s1;
sol = s2;
x = px;
y = py;
}
}
char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};
int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Set<String> history = new HashSet<>();
LinkedList<Board> open = new LinkedList<>();
history.add(currBoard);
open.add(new Board(currBoard, "", playerX, playerY));
while (!open.isEmpty()) {
Board item = open.poll();
String cur = item.cur;
String sol = item.sol;
int x = item.x;
int y = item.y;
for (int i = 0; i < dirs.length; i++) {
String trial = cur;
int dx = dirs[i][0];
int dy = dirs[i][1];
if (trial.charAt((y + dy) * nCols + x + dx) == '$') {
if ((trial = push(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][1];
if (isSolved(trial))
return newSol;
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
} else if ((trial = move(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][0];
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
}
}
return "No solution";
}
public static void main(String[] a) {
String level = "#######,# #,# #,#. # #,#. $$ #,"
+ "#.$$ #,#.# @#,#######";
System.out.println(new Sokoban(level.split(",")).solve());
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SokobanSolver
{
public class SokobanSolver
{
private class Board
{
public string Cur { get; internal set; }
public string Sol { get; internal set; }
public int X { get; internal set; }
public int Y { get; internal set; }
public Board(string cur, string sol, int x, int y)
{
Cur = cur;
Sol = sol;
X = x;
Y = y;
}
}
private string destBoard, currBoard;
private int playerX, playerY, nCols;
SokobanSolver(string[] board)
{
nCols = board[0].Length;
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.Length; r++)
{
for (int c = 0; c < nCols; c++)
{
char ch = board[r][c];
destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.Append(ch != '.' ? ch : ' ');
if (ch == '@')
{
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.ToString();
currBoard = currBuf.ToString();
}
private string Move(int x, int y, int dx, int dy, string trialBoard)
{
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard[newPlayerPos] != ' ')
return null;
char[] trial = trialBoard.ToCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new string(trial);
}
private string Push(int x, int y, int dx, int dy, string trialBoard)
{
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard[newBoxPos] != ' ')
return null;
char[] trial = trialBoard.ToCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new string(trial);
}
private bool IsSolved(string trialBoard)
{
for (int i = 0; i < trialBoard.Length; i++)
if ((destBoard[i] == '.')
!= (trialBoard[i] == '$'))
return false;
return true;
}
private string Solve()
{
char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };
int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };
ISet<string> history = new HashSet<string>();
LinkedList<Board> open = new LinkedList<Board>();
history.Add(currBoard);
open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));
while (!open.Count.Equals(0))
{
Board item = open.First();
open.RemoveFirst();
string cur = item.Cur;
string sol = item.Sol;
int x = item.X;
int y = item.Y;
for (int i = 0; i < dirs.GetLength(0); i++)
{
string trial = cur;
int dx = dirs[i, 0];
int dy = dirs[i, 1];
if (trial[(y + dy) * nCols + x + dx] == '$')
{
if ((trial = Push(x, y, dx, dy, trial)) != null)
{
if (!history.Contains(trial))
{
string newSol = sol + dirLabels[i, 1];
if (IsSolved(trial))
return newSol;
open.AddLast(new Board(trial, newSol, x + dx, y + dy));
history.Add(trial);
}
}
}
else if ((trial = Move(x, y, dx, dy, trial)) != null)
{
if (!history.Contains(trial))
{
string newSol = sol + dirLabels[i, 0];
open.AddLast(new Board(trial, newSol, x + dx, y + dy));
history.Add(trial);
}
}
}
}
return "No solution";
}
public static void Main(string[] a)
{
string level = "#######," +
"# #," +
"# #," +
"#. # #," +
"#. $$ #," +
"#.$$ #," +
"#.# @#," +
"#######";
System.Console.WriteLine("Level:\n");
foreach (string line in level.Split(','))
{
System.Console.WriteLine(line);
}
System.Console.WriteLine("\nSolution:\n");
System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import java.util.*;
public class PracticalNumbers {
public static void main(String[] args) {
final int from = 1;
final int to = 333;
List<Integer> practical = new ArrayList<>();
for (int i = from; i <= to; ++i) {
if (isPractical(i))
practical.add(i);
}
System.out.printf("Found %d practical numbers between %d and %d:\n%s\n",
practical.size(), from, to, shorten(practical, 10));
printPractical(666);
printPractical(6666);
printPractical(66666);
printPractical(672);
printPractical(720);
printPractical(222222);
}
private static void printPractical(int n) {
if (isPractical(n))
System.out.printf("%d is a practical number.\n", n);
else
System.out.printf("%d is not a practical number.\n", n);
}
private static boolean isPractical(int n) {
int[] divisors = properDivisors(n);
for (int i = 1; i < n; ++i) {
if (!sumOfAnySubset(i, divisors, divisors.length))
return false;
}
return true;
}
private static boolean sumOfAnySubset(int n, int[] f, int len) {
if (len == 0)
return false;
int total = 0;
for (int i = 0; i < len; ++i) {
if (n == f[i])
return true;
total += f[i];
}
if (n == total)
return true;
if (n > total)
return false;
--len;
int d = n - f[len];
return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);
}
private static int[] properDivisors(int n) {
List<Integer> divisors = new ArrayList<>();
divisors.add(1);
for (int i = 2;; ++i) {
int i2 = i * i;
if (i2 > n)
break;
if (n % i == 0) {
divisors.add(i);
if (i2 != n)
divisors.add(n / i);
}
}
int[] result = new int[divisors.size()];
for (int i = 0; i < result.length; ++i)
result[i] = divisors.get(i);
Arrays.sort(result);
return result;
}
private static String shorten(List<Integer> list, int n) {
StringBuilder str = new StringBuilder();
int len = list.size(), i = 0;
if (n > 0 && len > 0)
str.append(list.get(i++));
for (; i < n && i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
if (len > i + n) {
if (n > 0)
str.append(", ...");
i = len - n;
}
for (; i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
return str.toString();
}
}
| using System.Collections.Generic; using System.Linq; using static System.Console;
class Program {
static bool soas(int n, IEnumerable<int> f) {
if (n <= 0) return false; if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;
case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);
return soas(d, rf) || soas(n, rf); } return true; }
static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();
return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); }
static void Main() {
int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)
if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : "");
Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m);
do Write("\n{0,5} is a{1}practical number.",
m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
|
Generate a C# translation of this Java snippet without changing its computational steps. | 1.
1.0
2432311.7567374
1.234E-10
1.234e-10
758832d
728832f
1.0f
758832D
728832F
1.0F
1 / 2.
1 / 2
| double d = 1;
d = 1d;
d = 1D;
d = 1.2;
d = 1.2d;
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2;
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m;
|
Port the provided Java code into C# while preserving the original functionality. | import java.util.*;
public class ErdosPrimes {
public static void main(String[] args) {
boolean[] sieve = primeSieve(1000000);
int maxPrint = 2500;
int maxCount = 7875;
System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint);
for (int count = 0, prime = 1; count < maxCount; ++prime) {
if (erdos(sieve, prime)) {
++count;
if (prime < maxPrint) {
System.out.printf("%6d", prime);
if (count % 10 == 0)
System.out.println();
}
if (count == maxCount)
System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime);
}
}
}
private static boolean erdos(boolean[] sieve, int p) {
if (!sieve[p])
return false;
for (int k = 1, f = 1; f < p; ++k, f *= k) {
if (sieve[p - f])
return false;
}
return true;
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
}
| using System; using static System.Console;
class Program {
const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];
static void Main(string[] args) {
f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)
f[b] = f[a] * (b + 1);
int pc = 0, nth = 0, lv = 0;
for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {
if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " ");
nth++; lv = i; }
Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); }
static string ord(int n) {
return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; }
static bool is_erdos_prime(int p) {
if (!is_pr(p)) return false; int m = 0, t;
while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;
return true;
bool is_pr(int x) {
if (x < 4) return x > 1; if ((x & 1) == 0) return false;
for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;
return true; } } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.