Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this Racket function in C with identical behavior. | #lang racket
(define t 5)
(define count 0)
(define mutex (make-semaphore 1))
(define turnstile (make-semaphore 0))
(define turnstile2 (make-semaphore 1))
(define ch (make-channel))
(define (make-producer name start)
(λ ()
(let loop ([n start])
(sleep (* 0.01 (random 10)))
(semaphore-wait mutex)
(set! count (+ count 1))
(when (= count t)
(semaphore-wait turnstile2)
(semaphore-post turnstile))
(semaphore-post mutex)
(semaphore-wait turnstile)
(semaphore-post turnstile)
(channel-put ch n)
(semaphore-wait mutex)
(set! count (- count 1))
(when (= count 0)
(semaphore-wait turnstile)
(semaphore-post turnstile2))
(semaphore-post mutex)
(semaphore-wait turnstile2)
(semaphore-post turnstile2)
(loop (+ n t)))))
(map (λ(start) (thread (make-producer start start)))
(range 0 t))
(let loop ()
(displayln (for/list ([_ t]) (channel-get ch)))
(loop))
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Transform the following Racket implementation into C#, maintaining the same output and logic. | #lang racket
(define t 5)
(define count 0)
(define mutex (make-semaphore 1))
(define turnstile (make-semaphore 0))
(define turnstile2 (make-semaphore 1))
(define ch (make-channel))
(define (make-producer name start)
(λ ()
(let loop ([n start])
(sleep (* 0.01 (random 10)))
(semaphore-wait mutex)
(set! count (+ count 1))
(when (= count t)
(semaphore-wait turnstile2)
(semaphore-post turnstile))
(semaphore-post mutex)
(semaphore-wait turnstile)
(semaphore-post turnstile)
(channel-put ch n)
(semaphore-wait mutex)
(set! count (- count 1))
(when (= count 0)
(semaphore-wait turnstile)
(semaphore-post turnstile2))
(semaphore-post mutex)
(semaphore-wait turnstile2)
(semaphore-post turnstile2)
(loop (+ n t)))))
(map (λ(start) (thread (make-producer start start)))
(range 0 t))
(let loop ()
(displayln (for/list ([_ t]) (channel-get ch)))
(loop))
| 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 the same code in C++ as shown below in Racket. | #lang racket
(define t 5)
(define count 0)
(define mutex (make-semaphore 1))
(define turnstile (make-semaphore 0))
(define turnstile2 (make-semaphore 1))
(define ch (make-channel))
(define (make-producer name start)
(λ ()
(let loop ([n start])
(sleep (* 0.01 (random 10)))
(semaphore-wait mutex)
(set! count (+ count 1))
(when (= count t)
(semaphore-wait turnstile2)
(semaphore-post turnstile))
(semaphore-post mutex)
(semaphore-wait turnstile)
(semaphore-post turnstile)
(channel-put ch n)
(semaphore-wait mutex)
(set! count (- count 1))
(when (= count 0)
(semaphore-wait turnstile)
(semaphore-post turnstile2))
(semaphore-post mutex)
(semaphore-wait turnstile2)
(semaphore-post turnstile2)
(loop (+ n t)))))
(map (λ(start) (thread (make-producer start start)))
(range 0 t))
(let loop ()
(displayln (for/list ([_ t]) (channel-get ch)))
(loop))
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Change the programming language of this snippet from Racket to Java without modifying what it does. | #lang racket
(define t 5)
(define count 0)
(define mutex (make-semaphore 1))
(define turnstile (make-semaphore 0))
(define turnstile2 (make-semaphore 1))
(define ch (make-channel))
(define (make-producer name start)
(λ ()
(let loop ([n start])
(sleep (* 0.01 (random 10)))
(semaphore-wait mutex)
(set! count (+ count 1))
(when (= count t)
(semaphore-wait turnstile2)
(semaphore-post turnstile))
(semaphore-post mutex)
(semaphore-wait turnstile)
(semaphore-post turnstile)
(channel-put ch n)
(semaphore-wait mutex)
(set! count (- count 1))
(when (= count 0)
(semaphore-wait turnstile)
(semaphore-post turnstile2))
(semaphore-post mutex)
(semaphore-wait turnstile2)
(semaphore-post turnstile2)
(loop (+ n t)))))
(map (λ(start) (thread (make-producer start start)))
(range 0 t))
(let loop ()
(displayln (for/list ([_ t]) (channel-get ch)))
(loop))
| 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;
}
}
|
Change the following Racket code into Python without altering its purpose. | #lang racket
(define t 5)
(define count 0)
(define mutex (make-semaphore 1))
(define turnstile (make-semaphore 0))
(define turnstile2 (make-semaphore 1))
(define ch (make-channel))
(define (make-producer name start)
(λ ()
(let loop ([n start])
(sleep (* 0.01 (random 10)))
(semaphore-wait mutex)
(set! count (+ count 1))
(when (= count t)
(semaphore-wait turnstile2)
(semaphore-post turnstile))
(semaphore-post mutex)
(semaphore-wait turnstile)
(semaphore-post turnstile)
(channel-put ch n)
(semaphore-wait mutex)
(set! count (- count 1))
(when (= count 0)
(semaphore-wait turnstile)
(semaphore-post turnstile2))
(semaphore-post mutex)
(semaphore-wait turnstile2)
(semaphore-post turnstile2)
(loop (+ n t)))))
(map (λ(start) (thread (make-producer start start)))
(range 0 t))
(let loop ()
(displayln (for/list ([_ t]) (channel-get ch)))
(loop))
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Write the same algorithm in Go as shown in this Racket implementation. | #lang racket
(define t 5)
(define count 0)
(define mutex (make-semaphore 1))
(define turnstile (make-semaphore 0))
(define turnstile2 (make-semaphore 1))
(define ch (make-channel))
(define (make-producer name start)
(λ ()
(let loop ([n start])
(sleep (* 0.01 (random 10)))
(semaphore-wait mutex)
(set! count (+ count 1))
(when (= count t)
(semaphore-wait turnstile2)
(semaphore-post turnstile))
(semaphore-post mutex)
(semaphore-wait turnstile)
(semaphore-post turnstile)
(channel-put ch n)
(semaphore-wait mutex)
(set! count (- count 1))
(when (= count 0)
(semaphore-wait turnstile)
(semaphore-post turnstile2))
(semaphore-post mutex)
(semaphore-wait turnstile2)
(semaphore-post turnstile2)
(loop (+ n t)))))
(map (λ(start) (thread (make-producer start start)))
(range 0 t))
(let loop ()
(displayln (for/list ([_ t]) (channel-get ch)))
(loop))
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Port the following code from Ruby to C with equivalent syntax and logic. | require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap("INT") { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail "bad command from workshop"
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail "Worker
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError, "No worker
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6)
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Write the same algorithm in C# as shown in this Ruby implementation. | require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap("INT") { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail "bad command from workshop"
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail "Worker
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError, "No worker
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6)
| 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();
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap("INT") { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail "bad command from workshop"
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail "Worker
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError, "No worker
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6)
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Port the provided Ruby code into Java while preserving the original functionality. | require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap("INT") { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail "bad command from workshop"
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail "Worker
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError, "No worker
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6)
| 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;
}
}
|
Generate an equivalent Python version of this Ruby code. | require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap("INT") { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail "bad command from workshop"
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail "Worker
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError, "No worker
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6)
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Translate the given Ruby code snippet into Go without altering its behavior. | require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap("INT") { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail "bad command from workshop"
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail "Worker
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError, "No worker
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6)
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Preserve the algorithm and functionality while converting the code from Scala to C. |
import java.util.Random
val rgen = Random()
var nWorkers = 0
var nTasks = 0
class Worker(private val threadID: Int) : Runnable {
@Synchronized
override fun run() {
try {
val workTime = rgen.nextInt(900) + 100L
println("Worker $threadID will work for $workTime msec.")
Thread.sleep(workTime)
nFinished++
println("Worker $threadID is ready")
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
companion object {
private var nFinished = 0
@Synchronized
fun checkPoint() {
while (nFinished != nWorkers) {
try {
Thread.sleep(10)
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
nFinished = 0
}
}
}
fun runTasks() {
for (i in 1..nTasks) {
println("\nStarting task number $i.")
for (j in 1..nWorkers) Thread(Worker(j)).start()
Worker.checkPoint()
}
}
fun main(args: Array<String>) {
print("Enter number of workers to use: ")
nWorkers = readLine()!!.toInt()
print("Enter number of tasks to complete: ")
nTasks = readLine()!!.toInt()
runTasks()
}
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Please provide an equivalent version of this Scala code in C#. |
import java.util.Random
val rgen = Random()
var nWorkers = 0
var nTasks = 0
class Worker(private val threadID: Int) : Runnable {
@Synchronized
override fun run() {
try {
val workTime = rgen.nextInt(900) + 100L
println("Worker $threadID will work for $workTime msec.")
Thread.sleep(workTime)
nFinished++
println("Worker $threadID is ready")
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
companion object {
private var nFinished = 0
@Synchronized
fun checkPoint() {
while (nFinished != nWorkers) {
try {
Thread.sleep(10)
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
nFinished = 0
}
}
}
fun runTasks() {
for (i in 1..nTasks) {
println("\nStarting task number $i.")
for (j in 1..nWorkers) Thread(Worker(j)).start()
Worker.checkPoint()
}
}
fun main(args: Array<String>) {
print("Enter number of workers to use: ")
nWorkers = readLine()!!.toInt()
print("Enter number of tasks to complete: ")
nTasks = readLine()!!.toInt()
runTasks()
}
| 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();
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
import java.util.Random
val rgen = Random()
var nWorkers = 0
var nTasks = 0
class Worker(private val threadID: Int) : Runnable {
@Synchronized
override fun run() {
try {
val workTime = rgen.nextInt(900) + 100L
println("Worker $threadID will work for $workTime msec.")
Thread.sleep(workTime)
nFinished++
println("Worker $threadID is ready")
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
companion object {
private var nFinished = 0
@Synchronized
fun checkPoint() {
while (nFinished != nWorkers) {
try {
Thread.sleep(10)
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
nFinished = 0
}
}
}
fun runTasks() {
for (i in 1..nTasks) {
println("\nStarting task number $i.")
for (j in 1..nWorkers) Thread(Worker(j)).start()
Worker.checkPoint()
}
}
fun main(args: Array<String>) {
print("Enter number of workers to use: ")
nWorkers = readLine()!!.toInt()
print("Enter number of tasks to complete: ")
nTasks = readLine()!!.toInt()
runTasks()
}
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Convert the following code from Scala to Java, ensuring the logic remains intact. |
import java.util.Random
val rgen = Random()
var nWorkers = 0
var nTasks = 0
class Worker(private val threadID: Int) : Runnable {
@Synchronized
override fun run() {
try {
val workTime = rgen.nextInt(900) + 100L
println("Worker $threadID will work for $workTime msec.")
Thread.sleep(workTime)
nFinished++
println("Worker $threadID is ready")
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
companion object {
private var nFinished = 0
@Synchronized
fun checkPoint() {
while (nFinished != nWorkers) {
try {
Thread.sleep(10)
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
nFinished = 0
}
}
}
fun runTasks() {
for (i in 1..nTasks) {
println("\nStarting task number $i.")
for (j in 1..nWorkers) Thread(Worker(j)).start()
Worker.checkPoint()
}
}
fun main(args: Array<String>) {
print("Enter number of workers to use: ")
nWorkers = readLine()!!.toInt()
print("Enter number of tasks to complete: ")
nTasks = readLine()!!.toInt()
runTasks()
}
| 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;
}
}
|
Convert this Scala snippet to Python and keep its semantics consistent. |
import java.util.Random
val rgen = Random()
var nWorkers = 0
var nTasks = 0
class Worker(private val threadID: Int) : Runnable {
@Synchronized
override fun run() {
try {
val workTime = rgen.nextInt(900) + 100L
println("Worker $threadID will work for $workTime msec.")
Thread.sleep(workTime)
nFinished++
println("Worker $threadID is ready")
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
companion object {
private var nFinished = 0
@Synchronized
fun checkPoint() {
while (nFinished != nWorkers) {
try {
Thread.sleep(10)
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
nFinished = 0
}
}
}
fun runTasks() {
for (i in 1..nTasks) {
println("\nStarting task number $i.")
for (j in 1..nWorkers) Thread(Worker(j)).start()
Worker.checkPoint()
}
}
fun main(args: Array<String>) {
print("Enter number of workers to use: ")
nWorkers = readLine()!!.toInt()
print("Enter number of tasks to complete: ")
nTasks = readLine()!!.toInt()
runTasks()
}
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Write the same code in Go as shown below in Scala. |
import java.util.Random
val rgen = Random()
var nWorkers = 0
var nTasks = 0
class Worker(private val threadID: Int) : Runnable {
@Synchronized
override fun run() {
try {
val workTime = rgen.nextInt(900) + 100L
println("Worker $threadID will work for $workTime msec.")
Thread.sleep(workTime)
nFinished++
println("Worker $threadID is ready")
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
companion object {
private var nFinished = 0
@Synchronized
fun checkPoint() {
while (nFinished != nWorkers) {
try {
Thread.sleep(10)
}
catch (e: InterruptedException) {
println("Error: thread execution interrupted")
e.printStackTrace()
}
}
nFinished = 0
}
}
}
fun runTasks() {
for (i in 1..nTasks) {
println("\nStarting task number $i.")
for (j in 1..nWorkers) Thread(Worker(j)).start()
Worker.checkPoint()
}
}
fun main(args: Array<String>) {
print("Enter number of workers to use: ")
nWorkers = readLine()!!.toInt()
print("Enter number of tasks to complete: ")
nTasks = readLine()!!.toInt()
runTasks()
}
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Convert this Tcl snippet to C and keep its semantics consistent. | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
lappend members $id
}
return $id
}
proc Leave {id} {
variable members
set idx [lsearch -exact $members $id]
if {$idx > -1} {
set members [lreplace $members $idx $idx]
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
}
return
}
proc Deliver {id} {
variable waiting
lappend waiting $id
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
return
}
proc Release {} {
variable members
variable waiting
variable event
unset event
if {[llength $members] != [llength $waiting]} return
set w $waiting
set waiting {}
foreach id $w {
thread::send -async $id {incr ::checkpoint::Delivered}
}
}
proc makeThread {{script ""}} {
set id [thread::create thread::wait]
thread::send $id {
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
proc join {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Join [thread::id]]
}
proc leave {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Leave [thread::id]]
}
proc deliver {} {
variable checkpoint
after 0 [list thread::send $checkpoint [list \
::checkpoint::Deliver [thread::id]]]
vwait ::checkpoint::Delivered
}
}
}
thread::send $id [list set ::checkpoint::checkpoint [thread::id]]
thread::send $id $script
return $id
}
proc anyJoined {} {
variable members
expr {[llength $members] > 0}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Write a version of this Tcl function in C# with identical behavior. | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
lappend members $id
}
return $id
}
proc Leave {id} {
variable members
set idx [lsearch -exact $members $id]
if {$idx > -1} {
set members [lreplace $members $idx $idx]
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
}
return
}
proc Deliver {id} {
variable waiting
lappend waiting $id
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
return
}
proc Release {} {
variable members
variable waiting
variable event
unset event
if {[llength $members] != [llength $waiting]} return
set w $waiting
set waiting {}
foreach id $w {
thread::send -async $id {incr ::checkpoint::Delivered}
}
}
proc makeThread {{script ""}} {
set id [thread::create thread::wait]
thread::send $id {
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
proc join {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Join [thread::id]]
}
proc leave {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Leave [thread::id]]
}
proc deliver {} {
variable checkpoint
after 0 [list thread::send $checkpoint [list \
::checkpoint::Deliver [thread::id]]]
vwait ::checkpoint::Delivered
}
}
}
thread::send $id [list set ::checkpoint::checkpoint [thread::id]]
thread::send $id $script
return $id
}
proc anyJoined {} {
variable members
expr {[llength $members] > 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();
}
}
}
}
|
Ensure the translated C++ code behaves exactly like the original Tcl snippet. | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
lappend members $id
}
return $id
}
proc Leave {id} {
variable members
set idx [lsearch -exact $members $id]
if {$idx > -1} {
set members [lreplace $members $idx $idx]
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
}
return
}
proc Deliver {id} {
variable waiting
lappend waiting $id
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
return
}
proc Release {} {
variable members
variable waiting
variable event
unset event
if {[llength $members] != [llength $waiting]} return
set w $waiting
set waiting {}
foreach id $w {
thread::send -async $id {incr ::checkpoint::Delivered}
}
}
proc makeThread {{script ""}} {
set id [thread::create thread::wait]
thread::send $id {
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
proc join {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Join [thread::id]]
}
proc leave {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Leave [thread::id]]
}
proc deliver {} {
variable checkpoint
after 0 [list thread::send $checkpoint [list \
::checkpoint::Deliver [thread::id]]]
vwait ::checkpoint::Delivered
}
}
}
thread::send $id [list set ::checkpoint::checkpoint [thread::id]]
thread::send $id $script
return $id
}
proc anyJoined {} {
variable members
expr {[llength $members] > 0}
}
}
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Keep all operations the same but rewrite the snippet in Java. | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
lappend members $id
}
return $id
}
proc Leave {id} {
variable members
set idx [lsearch -exact $members $id]
if {$idx > -1} {
set members [lreplace $members $idx $idx]
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
}
return
}
proc Deliver {id} {
variable waiting
lappend waiting $id
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
return
}
proc Release {} {
variable members
variable waiting
variable event
unset event
if {[llength $members] != [llength $waiting]} return
set w $waiting
set waiting {}
foreach id $w {
thread::send -async $id {incr ::checkpoint::Delivered}
}
}
proc makeThread {{script ""}} {
set id [thread::create thread::wait]
thread::send $id {
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
proc join {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Join [thread::id]]
}
proc leave {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Leave [thread::id]]
}
proc deliver {} {
variable checkpoint
after 0 [list thread::send $checkpoint [list \
::checkpoint::Deliver [thread::id]]]
vwait ::checkpoint::Delivered
}
}
}
thread::send $id [list set ::checkpoint::checkpoint [thread::id]]
thread::send $id $script
return $id
}
proc anyJoined {} {
variable members
expr {[llength $members] > 0}
}
}
| 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;
}
}
|
Rewrite the snippet below in Python so it works the same as the original Tcl code. | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
lappend members $id
}
return $id
}
proc Leave {id} {
variable members
set idx [lsearch -exact $members $id]
if {$idx > -1} {
set members [lreplace $members $idx $idx]
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
}
return
}
proc Deliver {id} {
variable waiting
lappend waiting $id
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
return
}
proc Release {} {
variable members
variable waiting
variable event
unset event
if {[llength $members] != [llength $waiting]} return
set w $waiting
set waiting {}
foreach id $w {
thread::send -async $id {incr ::checkpoint::Delivered}
}
}
proc makeThread {{script ""}} {
set id [thread::create thread::wait]
thread::send $id {
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
proc join {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Join [thread::id]]
}
proc leave {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Leave [thread::id]]
}
proc deliver {} {
variable checkpoint
after 0 [list thread::send $checkpoint [list \
::checkpoint::Deliver [thread::id]]]
vwait ::checkpoint::Delivered
}
}
}
thread::send $id [list set ::checkpoint::checkpoint [thread::id]]
thread::send $id $script
return $id
}
proc anyJoined {} {
variable members
expr {[llength $members] > 0}
}
}
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Translate the given Tcl code snippet into Go without altering its behavior. | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
lappend members $id
}
return $id
}
proc Leave {id} {
variable members
set idx [lsearch -exact $members $id]
if {$idx > -1} {
set members [lreplace $members $idx $idx]
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
}
return
}
proc Deliver {id} {
variable waiting
lappend waiting $id
variable event
if {![info exists event]} {
set event [after idle ::checkpoint::Release]
}
return
}
proc Release {} {
variable members
variable waiting
variable event
unset event
if {[llength $members] != [llength $waiting]} return
set w $waiting
set waiting {}
foreach id $w {
thread::send -async $id {incr ::checkpoint::Delivered}
}
}
proc makeThread {{script ""}} {
set id [thread::create thread::wait]
thread::send $id {
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
proc join {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Join [thread::id]]
}
proc leave {} {
variable checkpoint
thread::send $checkpoint [list \
::checkpoint::Leave [thread::id]]
}
proc deliver {} {
variable checkpoint
after 0 [list thread::send $checkpoint [list \
::checkpoint::Deliver [thread::id]]]
vwait ::checkpoint::Delivered
}
}
}
thread::send $id [list set ::checkpoint::checkpoint [thread::id]]
thread::send $id $script
return $id
}
proc anyJoined {} {
variable members
expr {[llength $members] > 0}
}
}
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Produce a functionally identical Rust code for the snippet given in C++. | #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use array_init::array_init;
pub fn checkpoint() {
const NUM_TASKS: usize = 10;
const NUM_ITERATIONS: u8 = 10;
let barrier = Barrier::new(NUM_TASKS);
let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));
let arc = Arc::new((barrier, events));
let (tx, rx) = channel();
for i in 0..NUM_TASKS {
let arc = Arc::clone(&arc);
let tx = tx.clone();
spawn(move || {
let (ref barrier, ref events) = *arc;
let event = &events[i];
for _ in 0..NUM_ITERATIONS {
event.store(true, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| e.load(Ordering::Acquire)));
barrier.wait();
event.store(false, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));
barrier.wait();
}
tx.send(()).unwrap();
});
}
drop(tx);
for _ in 0..NUM_TASKS {
rx.recv().unwrap();
}
}
fn main() {
checkpoint();
}
|
Keep all operations the same but rewrite the snippet in Rust. | 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();
}
}
}
}
|
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use array_init::array_init;
pub fn checkpoint() {
const NUM_TASKS: usize = 10;
const NUM_ITERATIONS: u8 = 10;
let barrier = Barrier::new(NUM_TASKS);
let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));
let arc = Arc::new((barrier, events));
let (tx, rx) = channel();
for i in 0..NUM_TASKS {
let arc = Arc::clone(&arc);
let tx = tx.clone();
spawn(move || {
let (ref barrier, ref events) = *arc;
let event = &events[i];
for _ in 0..NUM_ITERATIONS {
event.store(true, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| e.load(Ordering::Acquire)));
barrier.wait();
event.store(false, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));
barrier.wait();
}
tx.send(()).unwrap();
});
}
drop(tx);
for _ in 0..NUM_TASKS {
rx.recv().unwrap();
}
}
fn main() {
checkpoint();
}
|
Please provide an equivalent version of this Go code in Rust. | package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use array_init::array_init;
pub fn checkpoint() {
const NUM_TASKS: usize = 10;
const NUM_ITERATIONS: u8 = 10;
let barrier = Barrier::new(NUM_TASKS);
let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));
let arc = Arc::new((barrier, events));
let (tx, rx) = channel();
for i in 0..NUM_TASKS {
let arc = Arc::clone(&arc);
let tx = tx.clone();
spawn(move || {
let (ref barrier, ref events) = *arc;
let event = &events[i];
for _ in 0..NUM_ITERATIONS {
event.store(true, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| e.load(Ordering::Acquire)));
barrier.wait();
event.store(false, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));
barrier.wait();
}
tx.send(()).unwrap();
});
}
drop(tx);
for _ in 0..NUM_TASKS {
rx.recv().unwrap();
}
}
fn main() {
checkpoint();
}
|
Please provide an equivalent version of this C code in Rust. | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use array_init::array_init;
pub fn checkpoint() {
const NUM_TASKS: usize = 10;
const NUM_ITERATIONS: u8 = 10;
let barrier = Barrier::new(NUM_TASKS);
let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));
let arc = Arc::new((barrier, events));
let (tx, rx) = channel();
for i in 0..NUM_TASKS {
let arc = Arc::clone(&arc);
let tx = tx.clone();
spawn(move || {
let (ref barrier, ref events) = *arc;
let event = &events[i];
for _ in 0..NUM_ITERATIONS {
event.store(true, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| e.load(Ordering::Acquire)));
barrier.wait();
event.store(false, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));
barrier.wait();
}
tx.send(()).unwrap();
});
}
drop(tx);
for _ in 0..NUM_TASKS {
rx.recv().unwrap();
}
}
fn main() {
checkpoint();
}
|
Produce a language-to-language conversion: from Java to Rust, same semantics. | 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;
}
}
|
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use array_init::array_init;
pub fn checkpoint() {
const NUM_TASKS: usize = 10;
const NUM_ITERATIONS: u8 = 10;
let barrier = Barrier::new(NUM_TASKS);
let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));
let arc = Arc::new((barrier, events));
let (tx, rx) = channel();
for i in 0..NUM_TASKS {
let arc = Arc::clone(&arc);
let tx = tx.clone();
spawn(move || {
let (ref barrier, ref events) = *arc;
let event = &events[i];
for _ in 0..NUM_ITERATIONS {
event.store(true, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| e.load(Ordering::Acquire)));
barrier.wait();
event.store(false, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));
barrier.wait();
}
tx.send(()).unwrap();
});
}
drop(tx);
for _ in 0..NUM_TASKS {
rx.recv().unwrap();
}
}
fn main() {
checkpoint();
}
|
Please provide an equivalent version of this Rust code in Python. |
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use array_init::array_init;
pub fn checkpoint() {
const NUM_TASKS: usize = 10;
const NUM_ITERATIONS: u8 = 10;
let barrier = Barrier::new(NUM_TASKS);
let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));
let arc = Arc::new((barrier, events));
let (tx, rx) = channel();
for i in 0..NUM_TASKS {
let arc = Arc::clone(&arc);
let tx = tx.clone();
spawn(move || {
let (ref barrier, ref events) = *arc;
let event = &events[i];
for _ in 0..NUM_ITERATIONS {
event.store(true, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| e.load(Ordering::Acquire)));
barrier.wait();
event.store(false, Ordering::Release);
barrier.wait();
assert!(events.iter().all(|e| !e.load(Ordering::Acquire)));
barrier.wait();
}
tx.send(()).unwrap();
});
}
drop(tx);
for _ in 0..NUM_TASKS {
rx.recv().unwrap();
}
}
fn main() {
checkpoint();
}
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Change the following Ada code into C# without altering its purpose. | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
C := A + B;
Put("A + B = "); Put(C);
New_Line;
C := A * B;
Put("A * B = "); Put(C);
New_Line;
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
C := -A;
Put("-A = "); Put(C);
New_Line;
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Can you help me rewrite this code in C instead of Ada, keeping it the same logically? | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
C := A + B;
Put("A + B = "); Put(C);
New_Line;
C := A * B;
Put("A * B = "); Put(C);
New_Line;
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
C := -A;
Put("-A = "); Put(C);
New_Line;
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Rewrite the snippet below in C++ so it works the same as the original Ada code. | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
C := A + B;
Put("A + B = "); Put(C);
New_Line;
C := A * B;
Put("A * B = "); Put(C);
New_Line;
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
C := -A;
Put("-A = "); Put(C);
New_Line;
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Convert this Ada block to Go, preserving its control flow and logic. | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
C := A + B;
Put("A + B = "); Put(C);
New_Line;
C := A * B;
Put("A * B = "); Put(C);
New_Line;
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
C := -A;
Put("-A = "); Put(C);
New_Line;
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Write the same algorithm in Java as shown in this Ada implementation. | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
C := A + B;
Put("A + B = "); Put(C);
New_Line;
C := A * B;
Put("A * B = "); Put(C);
New_Line;
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
C := -A;
Put("-A = "); Put(C);
New_Line;
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Convert this Ada block to Python, preserving its control flow and logic. | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
C := A + B;
Put("A + B = "); Put(C);
New_Line;
C := A * B;
Put("A * B = "); Put(C);
New_Line;
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
C := -A;
Put("-A = "); Put(C);
New_Line;
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Write the same algorithm in C as shown in this Arturo implementation. | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Generate an equivalent C# version of this Arturo code. | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Can you help me rewrite this code in Java instead of Arturo, keeping it the same logically? | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Convert this Arturo block to Python, preserving its control flow and logic. | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Write the same algorithm in Go as shown in this Arturo implementation. | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Can you help me rewrite this code in C instead of AutoHotKey, keeping it the same logically? | Cset(C,1,1)
MsgBox % Cstr(C)
Cneg(C,C)
MsgBox % Cstr(C)
Cadd(C,C,C)
MsgBox % Cstr(C)
Cinv(D,C)
MsgBox % Cstr(D)
Cmul(C,C,D)
MsgBox % Cstr(C)
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double")
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Convert the following code from AutoHotKey to C#, ensuring the logic remains intact. | Cset(C,1,1)
MsgBox % Cstr(C)
Cneg(C,C)
MsgBox % Cstr(C)
Cadd(C,C,C)
MsgBox % Cstr(C)
Cinv(D,C)
MsgBox % Cstr(D)
Cmul(C,C,D)
MsgBox % Cstr(C)
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double")
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Port the provided AutoHotKey code into C++ while preserving the original functionality. | Cset(C,1,1)
MsgBox % Cstr(C)
Cneg(C,C)
MsgBox % Cstr(C)
Cadd(C,C,C)
MsgBox % Cstr(C)
Cinv(D,C)
MsgBox % Cstr(D)
Cmul(C,C,D)
MsgBox % Cstr(C)
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double")
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Port the following code from AutoHotKey to Java with equivalent syntax and logic. | Cset(C,1,1)
MsgBox % Cstr(C)
Cneg(C,C)
MsgBox % Cstr(C)
Cadd(C,C,C)
MsgBox % Cstr(C)
Cinv(D,C)
MsgBox % Cstr(D)
Cmul(C,C,D)
MsgBox % Cstr(C)
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double")
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Transform the following AutoHotKey implementation into Python, maintaining the same output and logic. | Cset(C,1,1)
MsgBox % Cstr(C)
Cneg(C,C)
MsgBox % Cstr(C)
Cadd(C,C,C)
MsgBox % Cstr(C)
Cinv(D,C)
MsgBox % Cstr(D)
Cmul(C,C,D)
MsgBox % Cstr(C)
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double")
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Can you help me rewrite this code in Go instead of AutoHotKey, keeping it the same logically? | Cset(C,1,1)
MsgBox % Cstr(C)
Cneg(C,C)
MsgBox % Cstr(C)
Cadd(C,C,C)
MsgBox % Cstr(C)
Cinv(D,C)
MsgBox % Cstr(D)
Cmul(C,C,D)
MsgBox % Cstr(C)
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double")
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Rewrite this program in C while keeping its functionality equivalent to the AWK version. |
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Produce a functionally identical C# code for the snippet given in AWK. |
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the AWK version. |
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the AWK version. |
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Write the same code in Python as shown below in AWK. |
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Preserve the algorithm and functionality while converting the code from AWK to Go. |
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Transform the following BBC_Basic implementation into C, maintaining the same output and logic. | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Port the provided BBC_Basic code into C# while preserving the original functionality. | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Transform the following BBC_Basic implementation into C++, maintaining the same output and logic. | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Can you help me rewrite this code in Java instead of BBC_Basic, keeping it the same logically? | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Transform the following BBC_Basic implementation into Python, maintaining the same output and logic. | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Can you help me rewrite this code in Go instead of BBC_Basic, keeping it the same logically? | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Port the following code from Clojure to C with equivalent syntax and logic. | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number]
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Can you help me rewrite this code in C# instead of Clojure, keeping it the same logically? | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number]
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Transform the following Clojure implementation into C++, maintaining the same output and logic. | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number]
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Can you help me rewrite this code in Java instead of Clojure, keeping it the same logically? | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number]
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Convert this Clojure snippet to Python and keep its semantics consistent. | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number]
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Ensure the translated Go code behaves exactly like the original Clojure snippet. | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number]
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Write the same algorithm in C as shown in this Common_Lisp implementation. | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Convert this Common_Lisp block to C#, preserving its control flow and logic. | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Generate an equivalent C++ version of this Common_Lisp code. | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Transform the following Common_Lisp implementation into Java, maintaining the same output and logic. | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Port the provided Common_Lisp code into Python while preserving the original functionality. | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Preserve the algorithm and functionality while converting the code from Common_Lisp to Go. | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Translate the given D code snippet into C without altering its behavior. | import std.stdio, std.complex;
void main() {
auto x = complex(1, 1);
auto y = complex(3.14159, 1.2);
writeln(x + y);
writeln(x * y);
writeln(1.0 / x);
writeln(-x);
}
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Port the following code from D to C# with equivalent syntax and logic. | import std.stdio, std.complex;
void main() {
auto x = complex(1, 1);
auto y = complex(3.14159, 1.2);
writeln(x + y);
writeln(x * y);
writeln(1.0 / x);
writeln(-x);
}
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Write a version of this D function in C++ with identical behavior. | import std.stdio, std.complex;
void main() {
auto x = complex(1, 1);
auto y = complex(3.14159, 1.2);
writeln(x + y);
writeln(x * y);
writeln(1.0 / x);
writeln(-x);
}
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Transform the following D implementation into Java, maintaining the same output and logic. | import std.stdio, std.complex;
void main() {
auto x = complex(1, 1);
auto y = complex(3.14159, 1.2);
writeln(x + y);
writeln(x * y);
writeln(1.0 / x);
writeln(-x);
}
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Convert this D snippet to Python and keep its semantics consistent. | import std.stdio, std.complex;
void main() {
auto x = complex(1, 1);
auto y = complex(3.14159, 1.2);
writeln(x + y);
writeln(x * y);
writeln(1.0 / x);
writeln(-x);
}
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Convert this D snippet to Go and keep its semantics consistent. | import std.stdio, std.complex;
void main() {
auto x = complex(1, 1);
auto y = complex(3.14159, 1.2);
writeln(x + y);
writeln(x * y);
writeln(1.0 / x);
writeln(-x);
}
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Generate an equivalent C version of this Delphi code. | program Arithmetic_Complex;
uses
System.SysUtils,
System.VarCmplx;
var
a, b: Variant;
begin
a := VarComplexCreate(5, 3);
b := VarComplexCreate(0.5, 6.0);
writeln(format('(%s) + (%s) = %s',[a,b, a+b]));
writeln(format('(%s) * (%s) = %s',[a,b, a*b]));
writeln(format('-(%s) = %s',[a,- a]));
writeln(format('1/(%s) = %s',[a,1/a]));
writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));
Readln;
end.
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Ensure the translated C# code behaves exactly like the original Delphi snippet. | program Arithmetic_Complex;
uses
System.SysUtils,
System.VarCmplx;
var
a, b: Variant;
begin
a := VarComplexCreate(5, 3);
b := VarComplexCreate(0.5, 6.0);
writeln(format('(%s) + (%s) = %s',[a,b, a+b]));
writeln(format('(%s) * (%s) = %s',[a,b, a*b]));
writeln(format('-(%s) = %s',[a,- a]));
writeln(format('1/(%s) = %s',[a,1/a]));
writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));
Readln;
end.
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Write the same code in C++ as shown below in Delphi. | program Arithmetic_Complex;
uses
System.SysUtils,
System.VarCmplx;
var
a, b: Variant;
begin
a := VarComplexCreate(5, 3);
b := VarComplexCreate(0.5, 6.0);
writeln(format('(%s) + (%s) = %s',[a,b, a+b]));
writeln(format('(%s) * (%s) = %s',[a,b, a*b]));
writeln(format('-(%s) = %s',[a,- a]));
writeln(format('1/(%s) = %s',[a,1/a]));
writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));
Readln;
end.
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Produce a functionally identical Java code for the snippet given in Delphi. | program Arithmetic_Complex;
uses
System.SysUtils,
System.VarCmplx;
var
a, b: Variant;
begin
a := VarComplexCreate(5, 3);
b := VarComplexCreate(0.5, 6.0);
writeln(format('(%s) + (%s) = %s',[a,b, a+b]));
writeln(format('(%s) * (%s) = %s',[a,b, a*b]));
writeln(format('-(%s) = %s',[a,- a]));
writeln(format('1/(%s) = %s',[a,1/a]));
writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));
Readln;
end.
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Port the provided Delphi code into Python while preserving the original functionality. | program Arithmetic_Complex;
uses
System.SysUtils,
System.VarCmplx;
var
a, b: Variant;
begin
a := VarComplexCreate(5, 3);
b := VarComplexCreate(0.5, 6.0);
writeln(format('(%s) + (%s) = %s',[a,b, a+b]));
writeln(format('(%s) * (%s) = %s',[a,b, a*b]));
writeln(format('-(%s) = %s',[a,- a]));
writeln(format('1/(%s) = %s',[a,1/a]));
writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));
Readln;
end.
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Port the following code from Delphi to Go with equivalent syntax and logic. | program Arithmetic_Complex;
uses
System.SysUtils,
System.VarCmplx;
var
a, b: Variant;
begin
a := VarComplexCreate(5, 3);
b := VarComplexCreate(0.5, 6.0);
writeln(format('(%s) + (%s) = %s',[a,b, a+b]));
writeln(format('(%s) * (%s) = %s',[a,b, a*b]));
writeln(format('-(%s) = %s',[a,- a]));
writeln(format('1/(%s) = %s',[a,1/a]));
writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));
Readln;
end.
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Convert the following code from Elixir to C, ensuring the logic remains intact. | defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
defstruct real: 0, imag: 0
def new(real, imag) do
%__MODULE__{real: real, imag: imag}
end
def add(a, b) do
{a, b} = convert(a, b)
new(a.real + b.real, a.imag + b.imag)
end
def sub(a, b) do
{a, b} = convert(a, b)
new(a.real - b.real, a.imag - b.imag)
end
def mul(a, b) do
{a, b} = convert(a, b)
new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag)
end
def div(a, b) do
{a, b} = convert(a, b)
divisor = abs2(b)
new((a.real*b.real + a.imag*b.imag) / divisor,
(a.imag*b.real - a.real*b.imag) / divisor)
end
def neg(a) do
a = convert(a)
new(-a.real, -a.imag)
end
def inv(a) do
a = convert(a)
divisor = abs2(a)
new(a.real / divisor, -a.imag / divisor)
end
def conj(a) do
a = convert(a)
new(a.real, -a.imag)
end
def abs(a) do
:math.sqrt(abs2(a))
end
defp abs2(a) do
a = convert(a)
a.real*a.real + a.imag*a.imag
end
defp convert(a) when is_number(a), do: new(a, 0)
defp convert(%__MODULE__{} = a), do: a
defp convert(a, b), do: {convert(a), convert(b)}
def task do
a = new(1, 3)
b = new(5, 2)
IO.puts "a =
IO.puts "b =
IO.puts "add(a,b):
IO.puts "sub(a,b):
IO.puts "mul(a,b):
IO.puts "div(a,b):
IO.puts "div(b,a):
IO.puts "neg(a) :
IO.puts "inv(a) :
IO.puts "conj(a) :
end
end
defimpl String.Chars, for: Complex do
def to_string(%Complex{real: real, imag: imag}) do
if imag >= 0, do: "
else: "
end
end
Complex.task
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Preserve the algorithm and functionality while converting the code from Elixir to C#. | defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
defstruct real: 0, imag: 0
def new(real, imag) do
%__MODULE__{real: real, imag: imag}
end
def add(a, b) do
{a, b} = convert(a, b)
new(a.real + b.real, a.imag + b.imag)
end
def sub(a, b) do
{a, b} = convert(a, b)
new(a.real - b.real, a.imag - b.imag)
end
def mul(a, b) do
{a, b} = convert(a, b)
new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag)
end
def div(a, b) do
{a, b} = convert(a, b)
divisor = abs2(b)
new((a.real*b.real + a.imag*b.imag) / divisor,
(a.imag*b.real - a.real*b.imag) / divisor)
end
def neg(a) do
a = convert(a)
new(-a.real, -a.imag)
end
def inv(a) do
a = convert(a)
divisor = abs2(a)
new(a.real / divisor, -a.imag / divisor)
end
def conj(a) do
a = convert(a)
new(a.real, -a.imag)
end
def abs(a) do
:math.sqrt(abs2(a))
end
defp abs2(a) do
a = convert(a)
a.real*a.real + a.imag*a.imag
end
defp convert(a) when is_number(a), do: new(a, 0)
defp convert(%__MODULE__{} = a), do: a
defp convert(a, b), do: {convert(a), convert(b)}
def task do
a = new(1, 3)
b = new(5, 2)
IO.puts "a =
IO.puts "b =
IO.puts "add(a,b):
IO.puts "sub(a,b):
IO.puts "mul(a,b):
IO.puts "div(a,b):
IO.puts "div(b,a):
IO.puts "neg(a) :
IO.puts "inv(a) :
IO.puts "conj(a) :
end
end
defimpl String.Chars, for: Complex do
def to_string(%Complex{real: real, imag: imag}) do
if imag >= 0, do: "
else: "
end
end
Complex.task
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Elixir code. | defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
defstruct real: 0, imag: 0
def new(real, imag) do
%__MODULE__{real: real, imag: imag}
end
def add(a, b) do
{a, b} = convert(a, b)
new(a.real + b.real, a.imag + b.imag)
end
def sub(a, b) do
{a, b} = convert(a, b)
new(a.real - b.real, a.imag - b.imag)
end
def mul(a, b) do
{a, b} = convert(a, b)
new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag)
end
def div(a, b) do
{a, b} = convert(a, b)
divisor = abs2(b)
new((a.real*b.real + a.imag*b.imag) / divisor,
(a.imag*b.real - a.real*b.imag) / divisor)
end
def neg(a) do
a = convert(a)
new(-a.real, -a.imag)
end
def inv(a) do
a = convert(a)
divisor = abs2(a)
new(a.real / divisor, -a.imag / divisor)
end
def conj(a) do
a = convert(a)
new(a.real, -a.imag)
end
def abs(a) do
:math.sqrt(abs2(a))
end
defp abs2(a) do
a = convert(a)
a.real*a.real + a.imag*a.imag
end
defp convert(a) when is_number(a), do: new(a, 0)
defp convert(%__MODULE__{} = a), do: a
defp convert(a, b), do: {convert(a), convert(b)}
def task do
a = new(1, 3)
b = new(5, 2)
IO.puts "a =
IO.puts "b =
IO.puts "add(a,b):
IO.puts "sub(a,b):
IO.puts "mul(a,b):
IO.puts "div(a,b):
IO.puts "div(b,a):
IO.puts "neg(a) :
IO.puts "inv(a) :
IO.puts "conj(a) :
end
end
defimpl String.Chars, for: Complex do
def to_string(%Complex{real: real, imag: imag}) do
if imag >= 0, do: "
else: "
end
end
Complex.task
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Keep all operations the same but rewrite the snippet in Java. | defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
defstruct real: 0, imag: 0
def new(real, imag) do
%__MODULE__{real: real, imag: imag}
end
def add(a, b) do
{a, b} = convert(a, b)
new(a.real + b.real, a.imag + b.imag)
end
def sub(a, b) do
{a, b} = convert(a, b)
new(a.real - b.real, a.imag - b.imag)
end
def mul(a, b) do
{a, b} = convert(a, b)
new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag)
end
def div(a, b) do
{a, b} = convert(a, b)
divisor = abs2(b)
new((a.real*b.real + a.imag*b.imag) / divisor,
(a.imag*b.real - a.real*b.imag) / divisor)
end
def neg(a) do
a = convert(a)
new(-a.real, -a.imag)
end
def inv(a) do
a = convert(a)
divisor = abs2(a)
new(a.real / divisor, -a.imag / divisor)
end
def conj(a) do
a = convert(a)
new(a.real, -a.imag)
end
def abs(a) do
:math.sqrt(abs2(a))
end
defp abs2(a) do
a = convert(a)
a.real*a.real + a.imag*a.imag
end
defp convert(a) when is_number(a), do: new(a, 0)
defp convert(%__MODULE__{} = a), do: a
defp convert(a, b), do: {convert(a), convert(b)}
def task do
a = new(1, 3)
b = new(5, 2)
IO.puts "a =
IO.puts "b =
IO.puts "add(a,b):
IO.puts "sub(a,b):
IO.puts "mul(a,b):
IO.puts "div(a,b):
IO.puts "div(b,a):
IO.puts "neg(a) :
IO.puts "inv(a) :
IO.puts "conj(a) :
end
end
defimpl String.Chars, for: Complex do
def to_string(%Complex{real: real, imag: imag}) do
if imag >= 0, do: "
else: "
end
end
Complex.task
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Write the same code in Python as shown below in Elixir. | defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
defstruct real: 0, imag: 0
def new(real, imag) do
%__MODULE__{real: real, imag: imag}
end
def add(a, b) do
{a, b} = convert(a, b)
new(a.real + b.real, a.imag + b.imag)
end
def sub(a, b) do
{a, b} = convert(a, b)
new(a.real - b.real, a.imag - b.imag)
end
def mul(a, b) do
{a, b} = convert(a, b)
new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag)
end
def div(a, b) do
{a, b} = convert(a, b)
divisor = abs2(b)
new((a.real*b.real + a.imag*b.imag) / divisor,
(a.imag*b.real - a.real*b.imag) / divisor)
end
def neg(a) do
a = convert(a)
new(-a.real, -a.imag)
end
def inv(a) do
a = convert(a)
divisor = abs2(a)
new(a.real / divisor, -a.imag / divisor)
end
def conj(a) do
a = convert(a)
new(a.real, -a.imag)
end
def abs(a) do
:math.sqrt(abs2(a))
end
defp abs2(a) do
a = convert(a)
a.real*a.real + a.imag*a.imag
end
defp convert(a) when is_number(a), do: new(a, 0)
defp convert(%__MODULE__{} = a), do: a
defp convert(a, b), do: {convert(a), convert(b)}
def task do
a = new(1, 3)
b = new(5, 2)
IO.puts "a =
IO.puts "b =
IO.puts "add(a,b):
IO.puts "sub(a,b):
IO.puts "mul(a,b):
IO.puts "div(a,b):
IO.puts "div(b,a):
IO.puts "neg(a) :
IO.puts "inv(a) :
IO.puts "conj(a) :
end
end
defimpl String.Chars, for: Complex do
def to_string(%Complex{real: real, imag: imag}) do
if imag >= 0, do: "
else: "
end
end
Complex.task
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Generate a Go translation of this Elixir snippet without changing its computational steps. | defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
defstruct real: 0, imag: 0
def new(real, imag) do
%__MODULE__{real: real, imag: imag}
end
def add(a, b) do
{a, b} = convert(a, b)
new(a.real + b.real, a.imag + b.imag)
end
def sub(a, b) do
{a, b} = convert(a, b)
new(a.real - b.real, a.imag - b.imag)
end
def mul(a, b) do
{a, b} = convert(a, b)
new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag)
end
def div(a, b) do
{a, b} = convert(a, b)
divisor = abs2(b)
new((a.real*b.real + a.imag*b.imag) / divisor,
(a.imag*b.real - a.real*b.imag) / divisor)
end
def neg(a) do
a = convert(a)
new(-a.real, -a.imag)
end
def inv(a) do
a = convert(a)
divisor = abs2(a)
new(a.real / divisor, -a.imag / divisor)
end
def conj(a) do
a = convert(a)
new(a.real, -a.imag)
end
def abs(a) do
:math.sqrt(abs2(a))
end
defp abs2(a) do
a = convert(a)
a.real*a.real + a.imag*a.imag
end
defp convert(a) when is_number(a), do: new(a, 0)
defp convert(%__MODULE__{} = a), do: a
defp convert(a, b), do: {convert(a), convert(b)}
def task do
a = new(1, 3)
b = new(5, 2)
IO.puts "a =
IO.puts "b =
IO.puts "add(a,b):
IO.puts "sub(a,b):
IO.puts "mul(a,b):
IO.puts "div(a,b):
IO.puts "div(b,a):
IO.puts "neg(a) :
IO.puts "inv(a) :
IO.puts "conj(a) :
end
end
defimpl String.Chars, for: Complex do
def to_string(%Complex{real: real, imag: imag}) do
if imag >= 0, do: "
else: "
end
end
Complex.task
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Convert this Erlang snippet to C and keep its semantics consistent. |
-module(complex_number).
-export([calculate/0]).
-record(complex, {real, img}).
calculate() ->
A = #complex{real=1, img=3},
B = #complex{real=5, img=2},
Sum = add (A, B),
print (Sum),
Product = multiply (A, B),
print (Product),
Negation = negation (A),
print (Negation),
Inversion = inverse (A),
print (Inversion),
Conjugate = conjugate (A),
print (Conjugate).
add (A, B) ->
RealPart = A#complex.real + B#complex.real,
ImgPart = A#complex.img + B#complex.img,
#complex{real=RealPart, img=ImgPart}.
multiply (A, B) ->
RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img),
ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img),
#complex{real=RealPart, img=ImgPart}.
negation (A) ->
#complex{real=-A#complex.real, img=-A#complex.img}.
inverse (A) ->
C = conjugate (A),
Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img),
RealPart = C#complex.real / Mod,
ImgPart = C#complex.img / Mod,
#complex{real=RealPart, img=ImgPart}.
conjugate (A) ->
RealPart = A#complex.real,
ImgPart = -A#complex.img,
#complex{real=RealPart, img=ImgPart}.
print (A) ->
if A#complex.img < 0 ->
io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]);
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end.
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Preserve the algorithm and functionality while converting the code from Erlang to C#. |
-module(complex_number).
-export([calculate/0]).
-record(complex, {real, img}).
calculate() ->
A = #complex{real=1, img=3},
B = #complex{real=5, img=2},
Sum = add (A, B),
print (Sum),
Product = multiply (A, B),
print (Product),
Negation = negation (A),
print (Negation),
Inversion = inverse (A),
print (Inversion),
Conjugate = conjugate (A),
print (Conjugate).
add (A, B) ->
RealPart = A#complex.real + B#complex.real,
ImgPart = A#complex.img + B#complex.img,
#complex{real=RealPart, img=ImgPart}.
multiply (A, B) ->
RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img),
ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img),
#complex{real=RealPart, img=ImgPart}.
negation (A) ->
#complex{real=-A#complex.real, img=-A#complex.img}.
inverse (A) ->
C = conjugate (A),
Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img),
RealPart = C#complex.real / Mod,
ImgPart = C#complex.img / Mod,
#complex{real=RealPart, img=ImgPart}.
conjugate (A) ->
RealPart = A#complex.real,
ImgPart = -A#complex.img,
#complex{real=RealPart, img=ImgPart}.
print (A) ->
if A#complex.img < 0 ->
io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]);
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end.
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Please provide an equivalent version of this Erlang code in C++. |
-module(complex_number).
-export([calculate/0]).
-record(complex, {real, img}).
calculate() ->
A = #complex{real=1, img=3},
B = #complex{real=5, img=2},
Sum = add (A, B),
print (Sum),
Product = multiply (A, B),
print (Product),
Negation = negation (A),
print (Negation),
Inversion = inverse (A),
print (Inversion),
Conjugate = conjugate (A),
print (Conjugate).
add (A, B) ->
RealPart = A#complex.real + B#complex.real,
ImgPart = A#complex.img + B#complex.img,
#complex{real=RealPart, img=ImgPart}.
multiply (A, B) ->
RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img),
ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img),
#complex{real=RealPart, img=ImgPart}.
negation (A) ->
#complex{real=-A#complex.real, img=-A#complex.img}.
inverse (A) ->
C = conjugate (A),
Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img),
RealPart = C#complex.real / Mod,
ImgPart = C#complex.img / Mod,
#complex{real=RealPart, img=ImgPart}.
conjugate (A) ->
RealPart = A#complex.real,
ImgPart = -A#complex.img,
#complex{real=RealPart, img=ImgPart}.
print (A) ->
if A#complex.img < 0 ->
io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]);
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end.
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Convert this Erlang block to Java, preserving its control flow and logic. |
-module(complex_number).
-export([calculate/0]).
-record(complex, {real, img}).
calculate() ->
A = #complex{real=1, img=3},
B = #complex{real=5, img=2},
Sum = add (A, B),
print (Sum),
Product = multiply (A, B),
print (Product),
Negation = negation (A),
print (Negation),
Inversion = inverse (A),
print (Inversion),
Conjugate = conjugate (A),
print (Conjugate).
add (A, B) ->
RealPart = A#complex.real + B#complex.real,
ImgPart = A#complex.img + B#complex.img,
#complex{real=RealPart, img=ImgPart}.
multiply (A, B) ->
RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img),
ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img),
#complex{real=RealPart, img=ImgPart}.
negation (A) ->
#complex{real=-A#complex.real, img=-A#complex.img}.
inverse (A) ->
C = conjugate (A),
Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img),
RealPart = C#complex.real / Mod,
ImgPart = C#complex.img / Mod,
#complex{real=RealPart, img=ImgPart}.
conjugate (A) ->
RealPart = A#complex.real,
ImgPart = -A#complex.img,
#complex{real=RealPart, img=ImgPart}.
print (A) ->
if A#complex.img < 0 ->
io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]);
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end.
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Convert this Erlang snippet to Python and keep its semantics consistent. |
-module(complex_number).
-export([calculate/0]).
-record(complex, {real, img}).
calculate() ->
A = #complex{real=1, img=3},
B = #complex{real=5, img=2},
Sum = add (A, B),
print (Sum),
Product = multiply (A, B),
print (Product),
Negation = negation (A),
print (Negation),
Inversion = inverse (A),
print (Inversion),
Conjugate = conjugate (A),
print (Conjugate).
add (A, B) ->
RealPart = A#complex.real + B#complex.real,
ImgPart = A#complex.img + B#complex.img,
#complex{real=RealPart, img=ImgPart}.
multiply (A, B) ->
RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img),
ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img),
#complex{real=RealPart, img=ImgPart}.
negation (A) ->
#complex{real=-A#complex.real, img=-A#complex.img}.
inverse (A) ->
C = conjugate (A),
Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img),
RealPart = C#complex.real / Mod,
ImgPart = C#complex.img / Mod,
#complex{real=RealPart, img=ImgPart}.
conjugate (A) ->
RealPart = A#complex.real,
ImgPart = -A#complex.img,
#complex{real=RealPart, img=ImgPart}.
print (A) ->
if A#complex.img < 0 ->
io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]);
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end.
| >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>>
|
Rewrite the snippet below in Go so it works the same as the original Erlang code. |
-module(complex_number).
-export([calculate/0]).
-record(complex, {real, img}).
calculate() ->
A = #complex{real=1, img=3},
B = #complex{real=5, img=2},
Sum = add (A, B),
print (Sum),
Product = multiply (A, B),
print (Product),
Negation = negation (A),
print (Negation),
Inversion = inverse (A),
print (Inversion),
Conjugate = conjugate (A),
print (Conjugate).
add (A, B) ->
RealPart = A#complex.real + B#complex.real,
ImgPart = A#complex.img + B#complex.img,
#complex{real=RealPart, img=ImgPart}.
multiply (A, B) ->
RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img),
ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img),
#complex{real=RealPart, img=ImgPart}.
negation (A) ->
#complex{real=-A#complex.real, img=-A#complex.img}.
inverse (A) ->
C = conjugate (A),
Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img),
RealPart = C#complex.real / Mod,
ImgPart = C#complex.img / Mod,
#complex{real=RealPart, img=ImgPart}.
conjugate (A) ->
RealPart = A#complex.real,
ImgPart = -A#complex.img,
#complex{real=RealPart, img=ImgPart}.
print (A) ->
if A#complex.img < 0 ->
io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]);
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end.
| package main
import (
"fmt"
"math/cmplx"
)
func main() {
a := 1 + 1i
b := 3.14159 + 1.25i
fmt.Println("a: ", a)
fmt.Println("b: ", b)
fmt.Println("a + b: ", a+b)
fmt.Println("a * b: ", a*b)
fmt.Println("-a: ", -a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}
|
Transform the following F# implementation into C, maintaining the same output and logic. | > open Microsoft.FSharp.Math;;
> let a = complex 1.0 1.0;;
val a : complex = 1r+1i
> let b = complex 3.14159 1.25;;
val b : complex = 3.14159r+1.25i
> a + b;;
val it : Complex = 4.14159r+2.25i {Conjugate = 4.14159r-2.25i;
ImaginaryPart = 2.25;
Magnitude = 4.713307515;
Phase = 0.497661247;
RealPart = 4.14159;
i = 2.25;
r = 4.14159;}
> a * b;;
val it : Complex = 1.89159r+4.39159i {Conjugate = 1.89159r-4.39159i;
ImaginaryPart = 4.39159;
Magnitude = 4.781649868;
Phase = 1.164082262;
RealPart = 1.89159;
i = 4.39159;
r = 1.89159;}
> a / b;;
val it : Complex =
0.384145932435901r+0.165463215905043i
{Conjugate = 0.384145932435901r-0.165463215905043i;
ImaginaryPart = 0.1654632159;
Magnitude = 0.418265673;
Phase = 0.4067140652;
RealPart = 0.3841459324;
i = 0.1654632159;
r = 0.3841459324;}
> -a;;
val it : complex = -1r-1i {Conjugate = -1r+1i;
ImaginaryPart = -1.0;
Magnitude = 1.414213562;
Phase = -2.35619449;
RealPart = -1.0;
i = -1.0;
r = -1.0;}
| #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
|
Write the same algorithm in C# as shown in this F# implementation. | > open Microsoft.FSharp.Math;;
> let a = complex 1.0 1.0;;
val a : complex = 1r+1i
> let b = complex 3.14159 1.25;;
val b : complex = 3.14159r+1.25i
> a + b;;
val it : Complex = 4.14159r+2.25i {Conjugate = 4.14159r-2.25i;
ImaginaryPart = 2.25;
Magnitude = 4.713307515;
Phase = 0.497661247;
RealPart = 4.14159;
i = 2.25;
r = 4.14159;}
> a * b;;
val it : Complex = 1.89159r+4.39159i {Conjugate = 1.89159r-4.39159i;
ImaginaryPart = 4.39159;
Magnitude = 4.781649868;
Phase = 1.164082262;
RealPart = 1.89159;
i = 4.39159;
r = 1.89159;}
> a / b;;
val it : Complex =
0.384145932435901r+0.165463215905043i
{Conjugate = 0.384145932435901r-0.165463215905043i;
ImaginaryPart = 0.1654632159;
Magnitude = 0.418265673;
Phase = 0.4067140652;
RealPart = 0.3841459324;
i = 0.1654632159;
r = 0.3841459324;}
> -a;;
val it : complex = -1r-1i {Conjugate = -1r+1i;
ImaginaryPart = -1.0;
Magnitude = 1.414213562;
Phase = -2.35619449;
RealPart = -1.0;
i = -1.0;
r = -1.0;}
| namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
}
|
Translate the given F# code snippet into C++ without altering its behavior. | > open Microsoft.FSharp.Math;;
> let a = complex 1.0 1.0;;
val a : complex = 1r+1i
> let b = complex 3.14159 1.25;;
val b : complex = 3.14159r+1.25i
> a + b;;
val it : Complex = 4.14159r+2.25i {Conjugate = 4.14159r-2.25i;
ImaginaryPart = 2.25;
Magnitude = 4.713307515;
Phase = 0.497661247;
RealPart = 4.14159;
i = 2.25;
r = 4.14159;}
> a * b;;
val it : Complex = 1.89159r+4.39159i {Conjugate = 1.89159r-4.39159i;
ImaginaryPart = 4.39159;
Magnitude = 4.781649868;
Phase = 1.164082262;
RealPart = 1.89159;
i = 4.39159;
r = 1.89159;}
> a / b;;
val it : Complex =
0.384145932435901r+0.165463215905043i
{Conjugate = 0.384145932435901r-0.165463215905043i;
ImaginaryPart = 0.1654632159;
Magnitude = 0.418265673;
Phase = 0.4067140652;
RealPart = 0.3841459324;
i = 0.1654632159;
r = 0.3841459324;}
> -a;;
val it : complex = -1r-1i {Conjugate = -1r+1i;
ImaginaryPart = -1.0;
Magnitude = 1.414213562;
Phase = -2.35619449;
RealPart = -1.0;
i = -1.0;
r = -1.0;}
| #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
std::cout << a + b << std::endl;
std::cout << a * b << std::endl;
std::cout << 1.0 / a << std::endl;
std::cout << -a << std::endl;
std::cout << std::conj(a) << std::endl;
}
|
Produce a functionally identical Java code for the snippet given in F#. | > open Microsoft.FSharp.Math;;
> let a = complex 1.0 1.0;;
val a : complex = 1r+1i
> let b = complex 3.14159 1.25;;
val b : complex = 3.14159r+1.25i
> a + b;;
val it : Complex = 4.14159r+2.25i {Conjugate = 4.14159r-2.25i;
ImaginaryPart = 2.25;
Magnitude = 4.713307515;
Phase = 0.497661247;
RealPart = 4.14159;
i = 2.25;
r = 4.14159;}
> a * b;;
val it : Complex = 1.89159r+4.39159i {Conjugate = 1.89159r-4.39159i;
ImaginaryPart = 4.39159;
Magnitude = 4.781649868;
Phase = 1.164082262;
RealPart = 1.89159;
i = 4.39159;
r = 1.89159;}
> a / b;;
val it : Complex =
0.384145932435901r+0.165463215905043i
{Conjugate = 0.384145932435901r-0.165463215905043i;
ImaginaryPart = 0.1654632159;
Magnitude = 0.418265673;
Phase = 0.4067140652;
RealPart = 0.3841459324;
i = 0.1654632159;
r = 0.3841459324;}
> -a;;
val it : complex = -1r-1i {Conjugate = -1r+1i;
ImaginaryPart = -1.0;
Magnitude = 1.414213562;
Phase = -2.35619449;
RealPart = -1.0;
i = -1.0;
r = -1.0;}
| public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5);
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.