Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given Rust code snippet into C# without altering its behavior.
struct Nonoblock { width: usize, config: Vec<usize>, spaces: Vec<usize>, } impl Nonoblock { pub fn new(width: usize, config: Vec<usize>) -> Nonoblock { Nonoblock { width: width, config: config, spaces: Vec::new(), } } pub fn solve(&mut self) -> Vec<Vec<i32>> { let mut output:...
using System; using System.Linq; using System.Text; public static class Nonoblock { public static void Main() { Positions(5, 2,1); Positions(5); Positions(10, 8); Positions(15, 2,3,2,3); Positions(5, 2,3); } public static void Positions(int cells, params int[] block...
Generate a C# translation of this Rust snippet without changing its computational steps.
let conn = ldap3::LdapConn::new("ldap: conn.simple_bind("bind_dn", "bind_pass")?.success()?;
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
Convert the following code from Rust to C#, ensuring the logic remains intact.
use std::cmp::{max, min}; use std::fmt; use std::ops; #[derive(Debug, Clone, PartialEq)] struct Board { cells: Vec<Vec<Option<u32>>>, } impl Board { fn new(initial_board: Vec<Vec<u32>>) -> Self { let b = initial_board .iter() .map(|r| { r.iter() ...
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)}; priva...
Can you help me rewrite this code in C# instead of Rust, keeping it the same logically?
use std::cmp::{max, min}; use std::fmt; use std::ops; #[derive(Debug, Clone, PartialEq)] struct Board { cells: Vec<Vec<Option<u32>>>, } impl Board { fn new(initial_board: Vec<Vec<u32>>) -> Self { let b = initial_board .iter() .map(|r| { r.iter() ...
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)}; priva...
Write the same code in C# as shown below in Rust.
use std::{ marker::PhantomData, f64::consts::PI, }; pub trait AngleUnit: Copy { const TURN: f64; const NAME: &'static str; } macro_rules! unit { ($name:ident, $value:expr, $string:expr) => ( #[derive(Debug, Copy, Clone)] struct $name; impl AngleUnit for $name { ...
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Mat...
Translate the given Rust code snippet into C# without altering its behavior.
extern crate reqwest; use reqwest::blocking::Client; use reqwest::header::CONNECTION; fn main() { let client = Client::new(); let res = client .get("https: .basic_auth("user", Some("password")) .header(CONNECTION, "close") .send() .unwrap(); let body = res.te...
using System; using System.Net; class Program { static void Main(string[] args) { var client = new WebClient(); client.Credentials = CredentialCache.DefaultCredentials; client.Credentials = new NetworkCredential("User", "Password"); var data = client.Download...
Ensure the translated C# code behaves exactly like the original Rust snippet.
use std::default::Default; use std::ops::AddAssign; use itertools::Itertools; use reqwest::get; #[derive(Default, Debug)] struct Feature<T> { pub cie: T, pub xie: T, pub cei: T, pub xei: T, } impl AddAssign<Feature<bool>> for Feature<u64> { fn add_assign(&mut self, rhs: Feature<bool>) { s...
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
Rewrite the snippet below in C# so it works the same as the original Rust code.
use std::default::Default; use std::ops::AddAssign; use itertools::Itertools; use reqwest::get; #[derive(Default, Debug)] struct Feature<T> { pub cie: T, pub xie: T, pub cei: T, pub xei: T, } impl AddAssign<Feature<bool>> for Feature<u64> { fn add_assign(&mut self, rhs: Feature<bool>) { s...
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
Produce a language-to-language conversion: from Rust to C#, same semantics.
#[cfg(windows)] mod bindings { ::windows::include_bindings!(); } #[cfg(windows)] use bindings::{ Windows::Win32::Security::{ GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS, TOKEN_USER, }, Windows::Win32::SystemServices::{ GetCurrentProces...
using System.Diagnostics; namespace RC { internal class Program { public static void Main() { string sSource = "Sample App"; string sLog = "Application"; string sEvent = "Hello from RC!"; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);...
Change the programming language of this snippet from Rust to C# without modifying what it does.
use assert_approx_eq::assert_approx_eq; const EPS: f64 = 1e-14; pub struct Point { x: f64, y: f64, } pub struct Line { p1: Point, p2: Point, } impl Line { pub fn circle_intersections(&self, mx: f64, my: f64, r: f64, segment: bool) -> Vec<Point> { let mut intersections: Vec<Point> = Vec::...
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { Circle circle = ((3, -5), 3); Line[] lines = { ((-10, 11), (10, -9)), ((-10, 11), (-11, 12), true), ((3, -2), (7, -2)) }; Pri...
Write a version of this Rust function in C# with identical behavior.
#[derive(Copy, Clone)] struct Fraction { numerator: u32, denominator: u32, } use std::fmt; impl fmt::Display for Fraction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", self.numerator, self.denominator) } } impl Fraction { fn new(n: u32, d: u32) -> Fractio...
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i...
Port the following code from Rust to C# with equivalent syntax and logic.
#[derive(Copy, Clone)] struct Fraction { numerator: u32, denominator: u32, } use std::fmt; impl fmt::Display for Fraction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", self.numerator, self.denominator) } } impl Fraction { fn new(n: u32, d: u32) -> Fractio...
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i...
Generate an equivalent C# version of this Rust code.
fn is_prime(n: u32) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 0 { ...
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { lon...
Produce a functionally identical C# code for the snippet given in Rust.
use std::collections::HashMap; use itertools::Itertools; fn cubes(n: u64) -> Vec<u64> { let mut cube_vector = Vec::new(); for i in 1..=n { cube_vector.push(i.pow(3)); } cube_vector } fn main() { let c = cubes(1201); let it = c.iter().combinations(2); let mut m = HashMap::new(); for x in it { let sum = x[0...
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TaxicabNumber { class Program { static void Main(string[] args) { IDictionary<long, IList<Tuple<int, int>>> taxicabNumbers = GetTaxicabNumbers(2006); PrintTaxicabNumbers(taxic...
Translate the given Rust code snippet into C# without altering its behavior.
fn is_prime(n: i32) -> bool { for i in 2..n { if i * i > n { return true; } if n % i == 0 { return false; } } n > 1 } fn next_prime(n: i32) -> i32 { for i in (n+1).. { if is_prime(i) { return i; } } 0 } fn main() { let mut n = 0; let mut prime_q = 5; let mut prime_p = 3; let mut prime_o...
using static System.Console; using static System.Linq.Enumerable; using System; public static class StrongAndWeakPrimes { public static void Main() { var primes = PrimeGenerator(10_000_100).ToList(); var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+1...
Generate a C# translation of this Rust snippet without changing its computational steps.
#[cfg(target_pointer_width = "64")] type USingle = u32; #[cfg(target_pointer_width = "64")] type UDouble = u64; #[cfg(target_pointer_width = "64")] const WORD_LEN: i32 = 32; #[cfg(not(target_pointer_width = "64"))] type USingle = u16; #[cfg(not(target_pointer_width = "64"))] type UDouble = u32; #[cfg(not(target_pointe...
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 2...
Rewrite the snippet below in C# so it works the same as the original Rust code.
#[cfg(target_pointer_width = "64")] type USingle = u32; #[cfg(target_pointer_width = "64")] type UDouble = u64; #[cfg(target_pointer_width = "64")] const WORD_LEN: i32 = 32; #[cfg(not(target_pointer_width = "64"))] type USingle = u16; #[cfg(not(target_pointer_width = "64"))] type UDouble = u32; #[cfg(not(target_pointe...
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 2...
Port the provided Rust code into C# while preserving the original functionality.
fn prime_sieve(limit: usize) -> Vec<bool> { let mut sieve = vec![true; limit]; if limit > 0 { sieve[0] = false; } if limit > 1 { sieve[1] = false; } for i in (4..limit).step_by(2) { sieve[i] = false; } let mut p = 3; loop { let mut q = p * p; i...
using System; using System.Collections.Generic; using static System.Console; using System.Linq; using DT = System.DateTime; class Program { static void Main(string[] args) { string s; foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) { var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now; in...
Keep all operations the same but rewrite the snippet in C#.
fn prime_sieve(limit: usize) -> Vec<bool> { let mut sieve = vec![true; limit]; if limit > 0 { sieve[0] = false; } if limit > 1 { sieve[1] = false; } for i in (4..limit).step_by(2) { sieve[i] = false; } let mut p = 3; loop { let mut q = p * p; i...
using System; using System.Collections.Generic; using static System.Console; using System.Linq; using DT = System.DateTime; class Program { static void Main(string[] args) { string s; foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) { var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now; in...
Convert this Rust snippet to C# and keep its semantics consistent.
fn motzkin(n: usize) -> Vec<usize> { let mut m = vec![0; n]; m[0] = 1; m[1] = 1; for i in 2..n { m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2); } m } fn main() { use num_format::{Locale, ToFormattedString}; let count = 42; let m = motzkin(count); ...
using System; using BI = System.Numerics.BigInteger; class Program { static bool hmf(BI x) { if (x < 4) return x == 1; if ((x & 1) == 0 || x % 3 == 0) return true; int l = (int)Math.Sqrt((double)x); for (int j = 5, d = 4; j <= l; j += d = 6 - d) if (x % j == 0) return x > j; return f...
Can you help me rewrite this code in C# instead of Rust, keeping it the same logically?
use std::env; fn main() { let n: usize = match env::args() .nth(1) .and_then(|arg| arg.parse().ok()) .ok_or("Please specify the size of the magic square, as a positive multiple of 4.") { Ok(arg) if arg >= 4 && arg % 4 == 0 => arg, Err(e) => panic!(e), _ => panic!...
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.GetLengt...
Write the same algorithm in C# as shown in this Rust implementation.
use std::collections::BinaryHeap; fn a094958_iter() -> Vec<u16> { (0..12) .map(|n| vec![1 << n, 5 * (1 << n)]) .flatten() .filter(|x| x < &2200) .collect::<BinaryHeap<u16>>() .into_sorted_vec() } fn a094958_filter() -> Vec<u16> { (1..2200) .filter(|n| ((n & (n ...
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 ...
Convert this Rust snippet to C# and keep its semantics consistent.
enum ExpectedTypes { Int(i64), UInt(u64), Real(f64), Text(String), Uncertain, } use ExpectedTypes::*; fn main() { let enum_test = &[Int(-5), UInt(10), Real(-15.5), Text("Twenty".to_owned()), Uncertain]; for entry in enum_test { match entry { Int(x...
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); S...
Port the following code from Rust to C# with equivalent syntax and logic.
fn is_prime(n: i32) -> bool { for i in 2..n { if i * i > n { return true; } if n % i == 0 { return false; } } n > 1 } fn is_safe_prime(n: i32) -> bool { is_prime(n) && is_prime((n - 1) / 2) } fn is_unsafe_prime(n: i32) -> bool { is_prime(n) && !is_prime((n - 1) / 2) } fn next_prime(n: i32) -> i32 ...
using static System.Console; using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class SafePrimes { public static void Main() { HashSet<int> primes = Primes(10_000_000).ToHashSet(); WriteLine("First 35 safe primes:"); WriteLine(string.J...
Generate a C# translation of this Rust snippet without changing its computational steps.
use std::collections::HashMap; use std::hash::Hash; fn hash_join<A, B, K>(first: &[(K, A)], second: &[(K, B)]) -> Vec<(A, K, B)> where K: Hash + Eq + Copy, A: Copy, B: Copy, { let mut hash_map = HashMap::new(); for &(key, val_a) in second { hash_map.entry(key).or_insert_with...
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; privat...
Translate the given Rust code snippet into C# without altering its behavior.
#[derive(Debug)] enum SetOperation { Union, Intersection, Difference, } #[derive(Debug, PartialEq)] enum RangeType { Inclusive, Exclusive, } #[derive(Debug)] struct CompositeSet<'a> { operation: SetOperation, a: &'a RealSet<'a>, b: &'a RealSet<'a>, } #[derive(Debug)] struct RangeSet {...
using System; namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; } public Predicate<TValue> Contains { get; private set; } public Set<TVal...
Write a version of this Rust function in C# with identical behavior.
#[derive(Debug)] enum SetOperation { Union, Intersection, Difference, } #[derive(Debug, PartialEq)] enum RangeType { Inclusive, Exclusive, } #[derive(Debug)] struct CompositeSet<'a> { operation: SetOperation, a: &'a RealSet<'a>, b: &'a RealSet<'a>, } #[derive(Debug)] struct RangeSet {...
using System; namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; } public Predicate<TValue> Contains { get; private set; } public Set<TVal...
Port the provided Rust code into C# while preserving the original functionality.
fn print_super_d_numbers(d: u32, limit: u32) { use rug::Assign; use rug::Integer; println!("First {} super-{} numbers:", limit, d); let digits = d.to_string().repeat(d as usize); let mut count = 0; let mut n = 1; let mut s = Integer::new(); while count < limit { s.assign(Inte...
using System; using System.Collections.Generic; using BI = System.Numerics.BigInteger; using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>; using static System.Console; class Program { struct LI { public UInt64 lo, ml, mh, hi, tp; } const UInt64 Lm = 1_000_000_000_000_000_000UL; ...
Convert this Rust snippet to C# and keep its semantics consistent.
fn print_super_d_numbers(d: u32, limit: u32) { use rug::Assign; use rug::Integer; println!("First {} super-{} numbers:", limit, d); let digits = d.to_string().repeat(d as usize); let mut count = 0; let mut n = 1; let mut s = Integer::new(); while count < limit { s.assign(Inte...
using System; using System.Collections.Generic; using BI = System.Numerics.BigInteger; using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>; using static System.Console; class Program { struct LI { public UInt64 lo, ml, mh, hi, tp; } const UInt64 Lm = 1_000_000_000_000_000_000UL; ...
Produce a language-to-language conversion: from Rust to C#, same semantics.
use std::rc::Rc; use std::ops::{Add, Mul}; #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, } impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) }...
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this ...
Convert the following code from Rust to C#, ensuring the logic remains intact.
use std::rc::Rc; use std::ops::{Add, Mul}; #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, } impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) }...
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this ...
Rewrite the snippet below in C# so it works the same as the original Rust code.
use std::net::Ipv4Addr; fn canonical_cidr(cidr: &str) -> Result<String, &str> { let mut split = cidr.splitn(2, '/'); if let (Some(addr), Some(mask)) = (split.next(), split.next()) { let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?; let mask = mask.parse::<u8>().map_err(|_| ...
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", ...
Rewrite the snippet below in C# so it works the same as the original Rust code.
use std::net::Ipv4Addr; fn canonical_cidr(cidr: &str) -> Result<String, &str> { let mut split = cidr.splitn(2, '/'); if let (Some(addr), Some(mask)) = (split.next(), split.next()) { let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?; let mask = mask.parse::<u8>().map_err(|_| ...
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", ...
Produce a language-to-language conversion: from Rust to C#, same semantics.
pub fn pi(n: usize) -> f64 { let mut a : f64 = 1.0; let two : f64= 2.0; let mut g = 1.0 / two.sqrt(); let mut s = 0.0; let mut k = 1; while k<=n { let a1 = (a+g)/two; let g1 = (a*g).sqrt(); a = a1; g = g1; s += (a.powi(2)-g.powi(2)) * two.powi((k...
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } ...
Port the provided Rust code into C# while preserving the original functionality.
pub fn pi(n: usize) -> f64 { let mut a : f64 = 1.0; let two : f64= 2.0; let mut g = 1.0 / two.sqrt(); let mut s = 0.0; let mut k = 1; while k<=n { let a1 = (a+g)/two; let g1 = (a*g).sqrt(); a = a1; g = g1; s += (a.powi(2)-g.powi(2)) * two.powi((k...
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } ...
Convert this Rust snippet to C# and keep its semantics consistent.
mod bit_array; mod prime_sieve; use prime_sieve::PrimeSieve; fn modpow(mut base: usize, mut exp: usize, n: usize) -> usize { if n == 1 { return 0; } let mut result = 1; base %= n; while exp > 0 { if (exp & 1) == 1 { result = (result * base) % n; } b...
using System; using System.Collections.Generic; using System.Linq; public static class LongPrimes { public static void Main() { var primes = SomePrimeGenerator.Primes(64000).Skip(1).Where(p => Period(p) == p - 1).Append(99999); Console.WriteLine(string.Join(" ", primes.TakeWhile(p => p <= 500))); ...
Produce a functionally identical C# code for the snippet given in Rust.
use num_bigint::BigInt; use num_integer::Integer; use num_traits::{One, Zero}; use std::fmt; #[derive(Debug, Clone, PartialEq, PartialOrd)] struct Rational { nominator: BigInt, denominator: BigInt, } impl Rational { fn new(n: &BigInt, d: &BigInt) -> Rational { assert!(!d.is_zero(), "denominator ca...
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
Convert this Rust snippet to C# and keep its semantics consistent.
use num_bigint::BigInt; use num_integer::Integer; use num_traits::{One, Zero}; use std::fmt; #[derive(Debug, Clone, PartialEq, PartialOrd)] struct Rational { nominator: BigInt, denominator: BigInt, } impl Rational { fn new(n: &BigInt, d: &BigInt) -> Rational { assert!(!d.is_zero(), "denominator ca...
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
Ensure the translated C# code behaves exactly like the original Rust snippet.
use std::time::Instant; use separator::Separatable; const NUMBER_OF_CUBAN_PRIMES: usize = 200; const COLUMNS: usize = 10; const LAST_CUBAN_PRIME: usize = 100_000; fn main() { println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME); let start = In...
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<long> primes = new List<long>() { 3, 5 }; static void Main(string[] args) { const int cutOff = 200; const int bigUn = 100000; const int chunks = 50; const int little = big...
Port the provided Rust code into C# while preserving the original functionality.
extern crate image; extern crate rand; use rand::prelude::*; use std::f32; fn main() { let max_iterations = 50_000; let img_side = 800; let tri_size = 400.0; let mut imgbuf = image::ImageBuffer::new(img_side, img_side); let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3]; for i in 0....
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), ...
Change the programming language of this snippet from Rust to C# without modifying what it does.
extern crate image; extern crate rand; use rand::prelude::*; use std::f32; fn main() { let max_iterations = 50_000; let img_side = 800; let tri_size = 400.0; let mut imgbuf = image::ImageBuffer::new(img_side, img_side); let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3]; for i in 0....
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), ...
Convert this Rust block to C#, preserving its control flow and logic.
type Number = f64; #[derive(Debug, Copy, Clone, PartialEq)] struct Operator { token: char, operation: fn(Number, Number) -> Number, precedence: u8, is_left_associative: bool, } #[derive(Debug, Clone, PartialEq)] enum Token { Digit(Number), Operator(Operator), LeftParen, RightParen, } ...
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, (str...
Please provide an equivalent version of this Rust code in C#.
fn power_of_two(l: isize, n: isize) -> isize { let mut test: isize = 0; let log: f64 = 2.0_f64.ln() / 10.0_f64.ln(); let mut factor: isize = 1; let mut looop = l; let mut nn = n; while looop > 10 { factor *= 10; looop /= 10; } while nn > 0 { test = test + 1; ...
using System; class Program { static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } static ...
Translate this program into C# but keep the logic exactly as in Rust.
fn power_of_two(l: isize, n: isize) -> isize { let mut test: isize = 0; let log: f64 = 2.0_f64.ln() / 10.0_f64.ln(); let mut factor: isize = 1; let mut looop = l; let mut nn = n; while looop > 10 { factor *= 10; looop /= 10; } while nn > 0 { test = test + 1; ...
using System; class Program { static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } static ...
Change the following Rust code into C# without altering its purpose.
fn is_prime(n: u32) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 0 { ...
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; namespace NSmooth { class Program { static readonly List<BigInteger> primes = new List<BigInteger>(); static readonly List<int> smallPrimes = new List<int>(); static Program() { primes.Add...
Port the following code from Rust to C# with equivalent syntax and logic.
mod bit_array; mod prime_sieve; use prime_sieve::PrimeSieve; fn find_prime_partition( sieve: &PrimeSieve, number: usize, count: usize, min_prime: usize, primes: &mut Vec<usize>, index: usize, ) -> bool { if count == 1 { if number >= min_prime && sieve.is_prime(number) { ...
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class Rosetta { static void Main() { foreach ((int x, int n) in new [] { (99809, 1), (18, 2), (19, 3), (20, 4), (2017,...
Write the same algorithm in C# as shown in this Rust implementation.
#[derive(Copy, Clone)] struct Point { x: f64, y: f64, } use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn perpendicular_distance(p: &Point, p1: &Point, p2: &Point) -> f64 { let dx = p2.x - p...
using System; using System.Collections.Generic; using System.Linq; namespace LineSimplification { using Point = Tuple<double, double>; class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; do...
Convert this Rust snippet to C# and keep its semantics consistent.
#[derive(Copy, Clone)] struct Point { x: f64, y: f64, } use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn perpendicular_distance(p: &Point, p1: &Point, p2: &Point) -> f64 { let dx = p2.x - p...
using System; using System.Collections.Generic; using System.Linq; namespace LineSimplification { using Point = Tuple<double, double>; class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; do...
Rewrite this program in C# while keeping its functionality equivalent to the Rust version.
use std::fmt; use std::ops::{Add, Div, Mul, Sub}; #[derive(Copy, Clone, Debug)] pub struct Vector<T> { pub x: T, pub y: T, } impl<T> fmt::Display for Vector<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(prec) = f.precision() { write!...
using System; using System.Collections.Generic; using System.Linq; namespace RosettaVectors { public class Vector { public double[] store; public Vector(IEnumerable<double> init) { store = init.ToArray(); } public Vector(double x, double y) { ...
Change the programming language of this snippet from Rust to C# without modifying what it does.
use core::cmp::Ordering; const STX: char = '\u{0002}'; const ETX: char = '\u{0003}'; pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering { let mut iter1 = lhs.chars(); let mut iter2 = rhs.chars(); loop { match (iter1.next(), iter2.next()) { (Some(lhs), Some(rhs)) => { ...
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --...
Keep all operations the same but rewrite the snippet in C#.
use core::cmp::Ordering; const STX: char = '\u{0002}'; const ETX: char = '\u{0003}'; pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering { let mut iter1 = lhs.chars(); let mut iter2 = rhs.chars(); loop { match (iter1.next(), iter2.next()) { (Some(lhs), Some(rhs)) => { ...
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --...
Generate an equivalent C# version of this Rust code.
mod bit_array; mod prime_sieve; use prime_sieve::PrimeSieve; fn upper_bound_for_nth_prime(n: usize) -> usize { let x = n as f64; (x * (x.ln() + x.ln().ln())) as usize } fn compute_transitions(limit: usize) { use std::collections::BTreeMap; let mut transitions = BTreeMap::new(); let mut prev = 2...
using System; namespace PrimeConspiracy { class Program { static void Main(string[] args) { const int limit = 1_000_000; const int sieveLimit = 15_500_000; int[,] buckets = new int[10, 10]; int prevDigit = 2; bool[] notPrime = Sieve(sieveLimit); ...
Write the same algorithm in C# as shown in this Rust implementation.
use math::{histogram::Histogram, traits::ToIterator}; use rand; use rand_distr::{Distribution, Normal}; fn mean(data: &[f32]) -> Option<f32> { let sum: f32 = data.iter().sum(); Some(sum / data.len() as f32) } fn standard_deviation(data: &[f32]) -> Option<f32> { let mean = mean(data).expect("inval...
using System; using MathNet.Numerics.Distributions; using MathNet.Numerics.Statistics; class Program { static void RunNormal(int sampleSize) { double[] X = new double[sampleSize]; var norm = new Normal(new Random()); norm.Samples(X); const int numBuckets = 10; var histo...
Please provide an equivalent version of this Rust code in C#.
use std::convert::TryInto; fn get_divisors(n: u32) -> Vec<u32> { let mut results = Vec::new(); for i in 1..(n / 2 + 1) { if n % i == 0 { results.push(i); } } results.push(n); results } fn is_summable(x: i32, divisors: &[u32]) -> bool { if !divisors.is_empty() { ...
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == ...
Transform the following Rust implementation into C#, maintaining the same output and logic.
use itertools::Itertools; use std::collections::HashMap; fn isqrt(n: u64) -> u64 { let mut s = (n as f64).sqrt() as u64; s = (s + n / s) >> 1; if s * s > n { s - 1 } else { s } } fn is_square(n: u64) -> bool { match n & 0xf { 0 | 1 | 4 | 9 => { let t = isqrt...
using System; using System.Collections.Generic; using System.Linq; using static System.Console; using UI = System.UInt64; using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>; using Lst = System.Collections.Generic.List<sbyte>; using DT = System.DateTime; class Program { const sbyte...
Convert this Rust block to C#, preserving its control flow and logic.
use std::env; use std::fs; use std::collections::HashMap; extern crate rand; use rand::{seq::index::sample, thread_rng}; fn read_data(filename: &str) -> String { fs::read_to_string(filename).expect("Something went wrong reading the file") } fn main() { let args: Vec<String> = env::args().collect(); let ...
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { ...
Rewrite this program in C# while keeping its functionality equivalent to the Rust version.
use rug::Integer; fn partitions(n: usize) -> Integer { let mut p = Vec::with_capacity(n + 1); p.push(Integer::from(1)); for i in 1..=n { let mut num = Integer::from(0); let mut k = 1; loop { let mut j = (k * (3 * k - 1)) / 2; if j > i { bre...
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d....
Write a version of this Rust function in C# with identical behavior.
use image::error::ImageResult; use image::{Rgb, RgbImage}; fn hsv_to_rgb(h: f64, s: f64, v: f64) -> Rgb<u8> { let hp = h / 60.0; let c = s * v; let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); let m = v - c; let mut r = 0.0; let mut g = 0.0; let mut b = 0.0; if hp <= 1.0 { r = c; ...
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source;...
Write the same algorithm in C# as shown in this Rust implementation.
fn print_diffs(vec: &[usize]) { for i in 0..vec.len() { if i > 0 { print!(" ({}) ", vec[i] - vec[i - 1]); } print!("{}", vec[i]); } println!(); } fn main() { let limit = 1000000; let mut asc = Vec::new(); let mut desc = Vec::new(); let mut max_asc = Ve...
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console; class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0, ...
Port the following code from Rust to C# with equivalent syntax and logic.
fn main() { let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0], vec![4.0, 1.0, 6.0], vec![7.0, 8.0, 9.0] ]; let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0], vec![-1.0, 2.0, -1.0]...
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b =...
Generate an equivalent C# version of this Rust code.
fn main() { let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0], vec![4.0, 1.0, 6.0], vec![7.0, 8.0, 9.0] ]; let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0], vec![-1.0, 2.0, -1.0]...
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b =...
Write the same algorithm in C# as shown in this Rust implementation.
fn sum_of_any_subset(n: isize, f: &[isize]) -> bool { let len = f.len(); if len == 0 { return false; } if f.contains(&n) { return true; } let mut total = 0; for i in 0..len { total += f[i]; } if n == total { return true; } if n > total { ...
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: v...
Produce a language-to-language conversion: from Rust to C#, same semantics.
use std::fs::File; use std::io::Read; use reqwest::blocking::Client; use reqwest::Identity; fn main() -> std::io::Result<()> { let identity = { let mut buf = Vec::new(); File::open("badssl.com-client.p12")?.read_to_end(&mut buf)?; Identity::from_pkcs12_der(&buf, "badssl...
using System; using System.Net; class Program { class MyWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.ClientCertificates.Add(new X509Certificate()); ...
Write the same code in C# as shown below in Rust.
use std::collections::{BTreeMap, BTreeSet}; #[derive(Clone, Debug)] pub struct Graph { neighbors: BTreeMap<usize, BTreeSet<usize>>, } impl Graph { pub fn new(size: usize) -> Self { Self { neighbors: (0..size).fold(BTreeMap::new(), |mut acc, x| { acc.insert(x, BTreeSet::new...
using System; using System.Collections.Generic; class Node { public int LowLink { get; set; } public int Index { get; set; } public int N { get; } public Node(int n) { N = n; Index = -1; LowLink = 0; } } class Graph { public HashSet<Node> V { get; } public Dict...
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if...
program bits implicit none integer :: n = 1, i do i = 1, 6 print "(B32,2(' ',I2))", n, trailz(n), 31 - leadz(n) n = 42 * n end do end program
Translate the given C code snippet into Fortran without altering its behavior.
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if...
program bits implicit none integer :: n = 1, i do i = 1, 6 print "(B32,2(' ',I2))", n, trailz(n), 31 - leadz(n) n = 42 * n end do end program
Produce a language-to-language conversion: from C to Fortran, same semantics.
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec; typedef struct { int n; vec* v; } polygon_t, *polygon; #define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;} #define BIN_S(op, r) double v##op(vec a, vec b){ return r; } BIN_V(sub, a.x - b.x, a.y - ...
module Polygons use Points_Module implicit none type polygon type(point), dimension(:), allocatable :: points integer, dimension(:), allocatable :: vertices end type polygon contains function create_polygon(pts, vt) type(polygon) :: create_polygon type(point), dimension(:), intent(in) :: ...
Rewrite the snippet below in Fortran so it works the same as the original C code.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t dig...
program game_24 implicit none real :: vector(4), reals(11), result, a, b, c, d integer :: numbers(4), ascii(11), i character(len=11) :: expression character :: syntax(11) character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /) character, ...
Produce a language-to-language conversion: from C to Fortran, same semantics.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t dig...
program game_24 implicit none real :: vector(4), reals(11), result, a, b, c, d integer :: numbers(4), ascii(11), i character(len=11) :: expression character :: syntax(11) character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /) character, ...
Change the following C code into Fortran without altering its purpose.
#define PI 3.14159265358979323 #define MINSIZE 10 #define MAXSIZE 100
real, parameter :: pi = 3.141593
Convert this C block to Fortran, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); f...
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. INTEGER ENUFF PARAMETER (ENUFF = 100000) INTEGER Q(ENUFF) Q(1) = 1 Q(2) = 1 Q(3:) = -123456789 DO I = 3,ENUFF Q(I) = Q(I - Q(I - 1)) + Q(I - Q(I - 2)) END DO Cast forth results as ...
Generate a Fortran translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); f...
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. INTEGER ENUFF PARAMETER (ENUFF = 100000) INTEGER Q(ENUFF) Q(1) = 1 Q(2) = 1 Q(3:) = -123456789 DO I = 3,ENUFF Q(I) = Q(I - Q(I - 1)) + Q(I - Q(I - 2)) END DO Cast forth results as ...
Convert this C snippet to Fortran and keep its semantics consistent.
#include <stdio.h> #include <string.h> int match(const char *s, const char *p, int overlap) { int c = 0, l = strlen(p); while (*s != '\0') { if (strncmp(s++, p, l)) continue; if (!overlap) s += l - 1; c++; } return c; } int main() { ...
program Example implicit none integer :: n n = countsubstring("the three truths", "th") write(*,*) n n = countsubstring("ababababab", "abab") write(*,*) n n = countsubstring("abaabba*bbaba*bbab", "a*b") write(*,*) n contains function countsubstring(s1, s2) result(c) character(*), intent(in) :: s...
Port the following code from C to Fortran with equivalent syntax and logic.
#include <stdio.h> #define mod(n,m) ((((n) % (m)) + (m)) % (m)) int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))...
LOGICAL FUNCTION ISPRIME(N) INTEGER N INTEGER F ISPRIME = .FALSE. DO F = 2,SQRT(DFLOAT(N)) IF (MOD(N,F).EQ.0) RETURN END DO ISPRIME = .TRUE. END FUNCTION ISPRIME PROGRAM CHASE INTEGER P1,P2,P3 INTEGER H3,D ...
Ensure the translated Fortran code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #define LEN 3 int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; } int main() { int user_action, my_action; int user_rec[] = {0, 0, 0}; const char *names[] = { "Rock", "Paper", "Scisso...
program rpsgame integer, parameter :: COMPUTER=1, HAPLESSUSER=2 integer, dimension(3) :: rps = (/1,1,1/) real, dimension(3) :: p character :: answer, cc integer :: exhaustion, i real, dimension(2) :: score = (/0, 0/) character(len=8), dimension(3) :: choices = (/'rock ','paper ',...
Write the same algorithm in Fortran as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { ...
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00 a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.30...
Write the same algorithm in Fortran as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { ...
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00 a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.30...
Generate an equivalent Fortran version of this C code.
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_fra...
program hickerson implicit none integer, parameter :: q = selected_real_kind(30) integer, parameter :: l = selected_int_kind(15) real(q) :: s, l2 integer :: i, n, k l2 = log(2.0_q) do n = 1, 17 s = 0.5_q / l2 do i = 1, n s = (s * i) / l2 end do k...
Maintain the same structure and functionality when rewriting this code in Fortran.
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_fra...
program hickerson implicit none integer, parameter :: q = selected_real_kind(30) integer, parameter :: l = selected_int_kind(15) real(q) :: s, l2 integer :: i, n, k l2 = log(2.0_q) do n = 1, 17 s = 0.5_q / l2 do i = 1, n s = (s * i) / l2 end do k...
Port the following code from C to Fortran with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t see...
program readconfig implicit none integer, parameter :: strlen = 100 logical :: needspeeling = .false., seedsremoved =.false. character(len=strlen) :: favouritefruit = "", fullname = "", fst, snd character(len=strlen), allocatable :: otherfamily(:), tmp(:) character(len=1000) :: line int...
Convert this C snippet to Fortran and keep its semantics consistent.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = ...
program Kron_frac implicit none interface function matkronpow(M, n) result(Mpowern) integer, dimension(:,:), intent(in) :: M integer, intent(in) :: n integer, dimension(size(M, 1)**n, size(M,2)**n) :: Mpowern end function matkronpow function kron(A, B) result(M) integer, dimens...
Translate the given C code snippet into Fortran without altering its behavior.
#include <stdio.h> static const char *dog = "Benjamin"; static const char *Dog = "Samba"; static const char *DOG = "Bernie"; int main() { printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG); return 0; }
program Example implicit none character(8) :: dog, Dog, DOG dog = "Benjamin" Dog = "Samba" DOG = "Bernie" if (dog == DOG) then write(*,*) "There is just one dog named ", dog else write(*,*) "The three dogs are named ", dog, Dog, " and ", DOG end if end program Example
Translate the given C code snippet into Fortran without altering its behavior.
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } ...
program Stooge implicit none integer :: i integer :: array(50) = (/ (i, i = 50, 1, -1) /) call Stoogesort(array) write(*,"(10i5)") array contains recursive subroutine Stoogesort(a) integer, intent(in out) :: a(:) integer :: j, t, temp j = size(a) if(a(j) < a(1)) then temp = a(j) a...
Produce a functionally identical Fortran code for the snippet given in C.
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, ...
SUBROUTINE CROAK(GASP) CHARACTER*(*) GASP WRITE (6,*) "Oh dear. ",GASP STOP "++ungood." END SUBROUTINE FILEHACK(FNAME,NB) CHARACTER*(*) FNAME INTEGER NB INTEGER L INTEGER F,T PARAMETER (F=66,T=67) LOGICAL EXIST C...
Translate this program into Fortran but keep the logic exactly as in C.
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, ...
SUBROUTINE CROAK(GASP) CHARACTER*(*) GASP WRITE (6,*) "Oh dear. ",GASP STOP "++ungood." END SUBROUTINE FILEHACK(FNAME,NB) CHARACTER*(*) FNAME INTEGER NB INTEGER L INTEGER F,T PARAMETER (F=66,T=67) LOGICAL EXIST C...
Change the following C code into Fortran without altering its purpose.
#include <stdio.h> void shell_sort (int *a, int n) { int h, i, j, t; for (h = n; h /= 2;) { for (i = h; i < n; i++) { t = a[i]; for (j = i; j >= h && t < a[j - h]; j -= h) { a[j] = a[j - h]; } a[j] = t; } } } int main (int ac,...
MODULE sort CONTAINS SUBROUTINE Shell_Sort(a) IMPLICIT NONE INTEGER :: i, j, increment REAL :: temp REAL, INTENT(in out) :: a(:) increment = SIZE(a) / 2 DO WHILE (increment > 0) DO i = increment+1, SIZE(a) j = i temp = a(i) DO WHILE (j >= increment+1 .AND. a(j-increment...
Change the following C code into Fortran without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> double PI; typedef double complex cplx; void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2); for (int i = 0; i < n; i += 2 * step) { cplx ...
program deconv use mkl95_lapack, only : gelsd implicit none real(8), allocatable :: g(:), href(:), A(:,:), f(:) real(8), pointer :: h(:), r(:) integer :: N character(len=16) :: cbuff integer :: i intrinsic :: nint allocate(g(21),f(16)) g = [24,...
Port the following code from C to Fortran with equivalent syntax and logic.
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1)...
MODULE SAMPLER CONTAINS SAM00200 CHARACTER*20 FUNCTION GETREC(N,F,IS) Careful. Some compilers get confused over the function name's usage. SAM00400 INTEGER N INTEGER F CHARACTER...
Can you help me rewrite this code in Fortran instead of C, keeping it the same logically?
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1)...
MODULE SAMPLER CONTAINS SAM00200 CHARACTER*20 FUNCTION GETREC(N,F,IS) Careful. Some compilers get confused over the function name's usage. SAM00400 INTEGER N INTEGER F CHARACTER...
Write the same code in Fortran as shown below in C.
#include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0) int foo() { return 1; } main() { int a = 0; otherwise a = 4 given (foo()); ...
INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Transform the following C implementation into Fortran, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0) int foo() { return 1; } main() { int a = 0; otherwise a = 4 given (foo()); ...
INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Produce a functionally identical Fortran code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define foreach(a, b, c) for (int a = b; a < c; a++) #define for_i foreach(i, 0, n) #define for_j foreach(j, 0, n) #define for_k foreach(k, 0, n) #define for_ij for_i for_j #define for_ijk for_ij for_k #define _dim int n #define _swap(x, y) { typeof(x) tmp = x; ...
program lu1 implicit none call check( reshape([real(8)::1,2,1,3,4,1,5,7,0 ],[3,3]) ) call check( reshape([real(8)::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1],[4,4]) ) contains subroutine check(a) real(8), intent(in) :: a(:,:) integer :: i,j,n real(8), allocatable :: a...
Can you help me rewrite this code in Fortran instead of C, keeping it the same logically?
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h> typedef const char * String; typedef struct sTable { String * *rows; int n_rows,n_cols; } *Table; typedef int (*CompareFctn)(String a, String b); struct { CompareFctn compare; int column; int ...
module ExampleOptionalParameter implicit none contains subroutine sort_table(table, ordering, column, reverse) type(table_type), intent(inout) :: table integer, optional :: column logical, optional :: reverse optional :: ordering interface integer function ordering(a, b) t...
Generate a Fortran translation of this C snippet without changing its computational steps.
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> typedef struct{ double value; double delta; }imprecise; #define SQR(x) ((x) * (x)) imprecise imprecise_add(imprecise a, imprecise b) { imprecise ret; ret.value = a.value + b.value; ret.delta = sqrt(SQR(a.delta) + SQR(b....
PROGRAM CALCULATE REAL X1, Y1, X2, Y2 REAL X1E,Y1E,X2E,Y2E DATA X1, Y1 ,X2, Y2 /100., 50., 200.,100./ DATA X1E,Y1E,X2E,Y2E/ 1.1, 1.2, 2.2, 2.3/ REAL DX,DY,D2,D,DXE,DYE,E CHARACTER*1 C PARAMETER (C = CHAR(241)) REAL SD SD(X,P,S) = P*ABS(X)**(P - 1...
Port the following code from C to Fortran with equivalent syntax and logic.
#include<math.h> #include<stdio.h> int main () { double inputs[11], check = 400, result; int i; printf ("\nPlease enter 11 numbers :"); for (i = 0; i < 11; i++) { scanf ("%lf", &inputs[i]); } printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); for (i = 10; i >= 0; i-...
program tpk implicit none real, parameter :: overflow = 400.0 real :: a(11), res integer :: i write(*,*) "Input eleven numbers:" read(*,*) a a = a(11:1:-1) do i = 1, 11 res = f(a(i)) write(*, "(a, f0.3, a)", advance = "no") "f(", a(i), ") = " if(res > overflow) then write(*, "(a...
Can you help me rewrite this code in Fortran instead of C, keeping it the same logically?
#include <stdio.h> #include <time.h> struct rate_state_s { time_t lastFlush; time_t period; size_t tickCount; }; void tic_rate(struct rate_state_s* pRate) { pRate->tickCount += 1; time_t now = time(NULL); if((now - pRate->lastFlush) >= pRate->period) { size_t tps = 0.0...
DO I = FIRST,LAST IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST ...much computation... END DO
Produce a functionally identical Fortran code for the snippet given in C.
#include <stdio.h> #include <string.h> typedef struct { char v[16]; } deck; typedef unsigned int uint; uint n, d, best[16]; void tryswaps(deck *a, uint f, uint s) { # define A a->v # define B b.v if (d > best[n]) best[n] = d; while (1) { if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) && (d + best[s] >= bes...
module top implicit none contains recursive function f(x) result(m) integer :: n, m, x(:),y(size(x)), fst fst = x(1) if (fst == 1) then m = 0 else y(1:fst) = x(fst:1:-1) y(fst+1:) = x(fst+1:) m = 1 + f(y) end if end function recursive function perms(x) result(p) integer, pointer :: p(:,:...
Convert the following code from C to Fortran, ensuring the logic remains intact.
#include <stdio.h> #include <ctype.h> static int owp(int odd) { int ch, ret; ch = getc(stdin); if (!odd) { putc(ch, stdout); if (ch == EOF || ch == '.') return EOF; if (ispunct(ch)) return 0; ...
MODULE ELUDOM INTEGER MSG,INF LOGICAL DEFER CONTAINS CHARACTER*1 RECURSIVE FUNCTION GET(IN) INTEGER IN CHARACTER*1 C READ (IN,1,ADVANCE="NO",EOR=3,END=4) C 1 FORMAT (A1,$) 2 IF (("A"<=C .AND. C<="Z").OR.("a"<=C .AND. C<="z")) THEN ...
Write a version of this C function in Fortran with identical behavior.
struct RS232_data { unsigned carrier_detect : 1; unsigned received_data : 1; unsigned transmitted_data : 1; unsigned data_terminal_ready : 1; unsigned signal_ground : 1; unsigned data_set_ready : 1; unsigned request_to_send : 1; unsigned clear_to_send :...
TYPE RS232PIN9 LOGICAL CARRIER_DETECT LOGICAL RECEIVED_DATA LOGICAL TRANSMITTED_DATA LOGICAL DATA_TERMINAL_READY LOGICAL SIGNAL_GROUND LOGICAL DATA_SET_READY LOGICAL REQUEST_TO_SEND LOGICAL CLEAR_TO_SEND LOGICAL RING_INDICATOR ...
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> unsigned int lpd(unsigned int n) { if (n<=1) return 1; int i; for (i=n-1; i>0; i--) if (n%i == 0) return i; } int main() { int i; for (i=1; i<=100; i++) { printf("%3d", lpd(i)); if (i % 10 == 0) printf("\n"); } return 0; }
program LargestProperDivisors implicit none integer i, lpd do 10 i=1, 100 write (*,'(I3)',advance='no') lpd(i) 10 if (i/10*10 .eq. i) write (*,*) end program integer function lpd(n) implicit none integer n, i if (n .le. 1) ...