Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in C# while keeping its functionality equivalent to the Factor version. | USING: concurrency.distributed concurrency.messaging threads io.sockets io.servers ;
QUALIFIED: concurrency.messaging
: prettyprint-message ( -- ) concurrency.messaging:receive . flush prettyprint-message ;
[ prettyprint-message ] "logger" spawn dup name>> register-remote-thread
"127.0.0.1" 9000 <inet4> <node-server> start-server
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Ensure the translated Python code behaves exactly like the original Factor snippet. | USING: concurrency.distributed concurrency.messaging threads io.sockets io.servers ;
QUALIFIED: concurrency.messaging
: prettyprint-message ( -- ) concurrency.messaging:receive . flush prettyprint-message ;
[ prettyprint-message ] "logger" spawn dup name>> register-remote-thread
"127.0.0.1" 9000 <inet4> <node-server> start-server
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Produce a functionally identical Go code for the snippet given in Factor. | USING: concurrency.distributed concurrency.messaging threads io.sockets io.servers ;
QUALIFIED: concurrency.messaging
: prettyprint-message ( -- ) concurrency.messaging:receive . flush prettyprint-message ;
[ prettyprint-message ] "logger" spawn dup name>> register-remote-thread
"127.0.0.1" 9000 <inet4> <node-server> start-server
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Produce a language-to-language conversion: from Julia to C, same semantics. |
function count_heads(n)
c::Int = 0
for i = 1:n
c += rand(Bool)
end
c
end
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Generate a C# translation of this Julia snippet without changing its computational steps. |
function count_heads(n)
c::Int = 0
for i = 1:n
c += rand(Bool)
end
c
end
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Convert the following code from Julia to Python, ensuring the logic remains intact. |
function count_heads(n)
c::Int = 0
for i = 1:n
c += rand(Bool)
end
c
end
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Maintain the same structure and functionality when rewriting this code in Go. |
function count_heads(n)
c::Int = 0
for i = 1:n
c += rand(Bool)
end
c
end
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Maintain the same structure and functionality when rewriting this code in C. | LaunchKernels[2];
ParallelEvaluate[RandomReal[]]
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Port the provided Mathematica code into C# while preserving the original functionality. | LaunchKernels[2];
ParallelEvaluate[RandomReal[]]
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Maintain the same structure and functionality when rewriting this code in Python. | LaunchKernels[2];
ParallelEvaluate[RandomReal[]]
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Convert the following code from Mathematica to Go, ensuring the logic remains intact. | LaunchKernels[2];
ParallelEvaluate[RandomReal[]]
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Generate an equivalent C version of this Nim code. | import os, nanomsg
proc sendMsg(s: cint, msg: string) =
echo "SENDING \"",msg,"\""
let bytes = s.send(msg.cstring, msg.len + 1, 0)
assert bytes == msg.len + 1
proc recvMsg(s: cint) =
var buf: cstring
let bytes = s.recv(addr buf, MSG, 0)
if bytes > 0:
echo "RECEIVED \"",buf,"\""
discard freemsg buf
proc sendRecv(s: cint, msg: string) =
var to: cint = 100
discard s.setSockOpt(SOL_SOCKET, RCVTIMEO, addr to, sizeof to)
while true:
s.recvMsg
sleep 1000
s.sendMsg msg
proc node0(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.bindd url
assert res >= 0
s.sendRecv "node0"
discard s.shutdown 0
proc node1(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.connect url
assert res >= 0
s.sendRecv "node1"
discard s.shutdown 0
if paramStr(1) == "node0":
node0 paramStr(2)
elif paramStr(1) == "node1":
node1 paramStr(2)
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Convert this Nim block to C#, preserving its control flow and logic. | import os, nanomsg
proc sendMsg(s: cint, msg: string) =
echo "SENDING \"",msg,"\""
let bytes = s.send(msg.cstring, msg.len + 1, 0)
assert bytes == msg.len + 1
proc recvMsg(s: cint) =
var buf: cstring
let bytes = s.recv(addr buf, MSG, 0)
if bytes > 0:
echo "RECEIVED \"",buf,"\""
discard freemsg buf
proc sendRecv(s: cint, msg: string) =
var to: cint = 100
discard s.setSockOpt(SOL_SOCKET, RCVTIMEO, addr to, sizeof to)
while true:
s.recvMsg
sleep 1000
s.sendMsg msg
proc node0(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.bindd url
assert res >= 0
s.sendRecv "node0"
discard s.shutdown 0
proc node1(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.connect url
assert res >= 0
s.sendRecv "node1"
discard s.shutdown 0
if paramStr(1) == "node0":
node0 paramStr(2)
elif paramStr(1) == "node1":
node1 paramStr(2)
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Transform the following Nim implementation into Python, maintaining the same output and logic. | import os, nanomsg
proc sendMsg(s: cint, msg: string) =
echo "SENDING \"",msg,"\""
let bytes = s.send(msg.cstring, msg.len + 1, 0)
assert bytes == msg.len + 1
proc recvMsg(s: cint) =
var buf: cstring
let bytes = s.recv(addr buf, MSG, 0)
if bytes > 0:
echo "RECEIVED \"",buf,"\""
discard freemsg buf
proc sendRecv(s: cint, msg: string) =
var to: cint = 100
discard s.setSockOpt(SOL_SOCKET, RCVTIMEO, addr to, sizeof to)
while true:
s.recvMsg
sleep 1000
s.sendMsg msg
proc node0(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.bindd url
assert res >= 0
s.sendRecv "node0"
discard s.shutdown 0
proc node1(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.connect url
assert res >= 0
s.sendRecv "node1"
discard s.shutdown 0
if paramStr(1) == "node0":
node0 paramStr(2)
elif paramStr(1) == "node1":
node1 paramStr(2)
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Produce a language-to-language conversion: from Nim to Go, same semantics. | import os, nanomsg
proc sendMsg(s: cint, msg: string) =
echo "SENDING \"",msg,"\""
let bytes = s.send(msg.cstring, msg.len + 1, 0)
assert bytes == msg.len + 1
proc recvMsg(s: cint) =
var buf: cstring
let bytes = s.recv(addr buf, MSG, 0)
if bytes > 0:
echo "RECEIVED \"",buf,"\""
discard freemsg buf
proc sendRecv(s: cint, msg: string) =
var to: cint = 100
discard s.setSockOpt(SOL_SOCKET, RCVTIMEO, addr to, sizeof to)
while true:
s.recvMsg
sleep 1000
s.sendMsg msg
proc node0(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.bindd url
assert res >= 0
s.sendRecv "node0"
discard s.shutdown 0
proc node1(url: string) =
var s = socket(AF_SP, nanomsg.PAIR)
assert s >= 0
let res = s.connect url
assert res >= 0
s.sendRecv "node1"
discard s.shutdown 0
if paramStr(1) == "node0":
node0 paramStr(2)
elif paramStr(1) == "node1":
node1 paramStr(2)
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Translate this program into C but keep the logic exactly as in OCaml. | open Printf
let create_logger () =
def log(text) & logs(l) =
printf "Logged: %s\n%!" text;
logs((text, Unix.gettimeofday ())::l) & reply to log
or search(text) & logs(l) =
logs(l) & reply List.filter (fun (line, _) -> line = text) l to search
in
spawn logs([]);
(log, search)
def wait() & finished() = reply to wait
let register name service = Join.Ns.register Join.Ns.here name service
let () =
let log, search = create_logger () in
register "log" log;
register "search" search;
Join.Site.listen (Unix.ADDR_INET (Join.Site.get_local_addr(), 12345));
wait ()
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Can you help me rewrite this code in C# instead of OCaml, keeping it the same logically? | open Printf
let create_logger () =
def log(text) & logs(l) =
printf "Logged: %s\n%!" text;
logs((text, Unix.gettimeofday ())::l) & reply to log
or search(text) & logs(l) =
logs(l) & reply List.filter (fun (line, _) -> line = text) l to search
in
spawn logs([]);
(log, search)
def wait() & finished() = reply to wait
let register name service = Join.Ns.register Join.Ns.here name service
let () =
let log, search = create_logger () in
register "log" log;
register "search" search;
Join.Site.listen (Unix.ADDR_INET (Join.Site.get_local_addr(), 12345));
wait ()
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Port the provided OCaml code into Python while preserving the original functionality. | open Printf
let create_logger () =
def log(text) & logs(l) =
printf "Logged: %s\n%!" text;
logs((text, Unix.gettimeofday ())::l) & reply to log
or search(text) & logs(l) =
logs(l) & reply List.filter (fun (line, _) -> line = text) l to search
in
spawn logs([]);
(log, search)
def wait() & finished() = reply to wait
let register name service = Join.Ns.register Join.Ns.here name service
let () =
let log, search = create_logger () in
register "log" log;
register "search" search;
Join.Site.listen (Unix.ADDR_INET (Join.Site.get_local_addr(), 12345));
wait ()
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Produce a functionally identical Go code for the snippet given in OCaml. | open Printf
let create_logger () =
def log(text) & logs(l) =
printf "Logged: %s\n%!" text;
logs((text, Unix.gettimeofday ())::l) & reply to log
or search(text) & logs(l) =
logs(l) & reply List.filter (fun (line, _) -> line = text) l to search
in
spawn logs([]);
(log, search)
def wait() & finished() = reply to wait
let register name service = Join.Ns.register Join.Ns.here name service
let () =
let log, search = create_logger () in
register "log" log;
register "search" search;
Join.Site.listen (Unix.ADDR_INET (Join.Site.get_local_addr(), 12345));
wait ()
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Generate a C translation of this Perl snippet without changing its computational steps. | use strict;
use warnings;
use Data::Dumper;
use IO::Socket::INET;
use Safe;
sub get_data {
my $sock = IO::Socket::INET->new(
LocalHost => "localhost",
LocalPort => "10000",
Proto => "tcp",
Listen => 1,
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
my $cli = $sock->accept();
my $safe = Safe->new;
my $x = $safe->reval(join("", <$cli>));
close $cli;
close $sock;
return $x;
}
sub send_data {
my $host = shift;
my $data = shift;
my $sock = IO::Socket::INET->new(
PeerAddr => "$host:10000",
Proto => "tcp",
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
print $sock Data::Dumper->Dump([$data]);
close $sock;
}
if (@ARGV) {
my $x = get_data();
print "Got data\n", Data::Dumper->Dump([$x]);
} else {
send_data('some_host', { a=>100, b=>[1 .. 10] });
}
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Convert the following code from Perl to C#, ensuring the logic remains intact. | use strict;
use warnings;
use Data::Dumper;
use IO::Socket::INET;
use Safe;
sub get_data {
my $sock = IO::Socket::INET->new(
LocalHost => "localhost",
LocalPort => "10000",
Proto => "tcp",
Listen => 1,
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
my $cli = $sock->accept();
my $safe = Safe->new;
my $x = $safe->reval(join("", <$cli>));
close $cli;
close $sock;
return $x;
}
sub send_data {
my $host = shift;
my $data = shift;
my $sock = IO::Socket::INET->new(
PeerAddr => "$host:10000",
Proto => "tcp",
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
print $sock Data::Dumper->Dump([$data]);
close $sock;
}
if (@ARGV) {
my $x = get_data();
print "Got data\n", Data::Dumper->Dump([$x]);
} else {
send_data('some_host', { a=>100, b=>[1 .. 10] });
}
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Write the same algorithm in Python as shown in this Perl implementation. | use strict;
use warnings;
use Data::Dumper;
use IO::Socket::INET;
use Safe;
sub get_data {
my $sock = IO::Socket::INET->new(
LocalHost => "localhost",
LocalPort => "10000",
Proto => "tcp",
Listen => 1,
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
my $cli = $sock->accept();
my $safe = Safe->new;
my $x = $safe->reval(join("", <$cli>));
close $cli;
close $sock;
return $x;
}
sub send_data {
my $host = shift;
my $data = shift;
my $sock = IO::Socket::INET->new(
PeerAddr => "$host:10000",
Proto => "tcp",
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
print $sock Data::Dumper->Dump([$data]);
close $sock;
}
if (@ARGV) {
my $x = get_data();
print "Got data\n", Data::Dumper->Dump([$x]);
} else {
send_data('some_host', { a=>100, b=>[1 .. 10] });
}
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Please provide an equivalent version of this Perl code in Go. | use strict;
use warnings;
use Data::Dumper;
use IO::Socket::INET;
use Safe;
sub get_data {
my $sock = IO::Socket::INET->new(
LocalHost => "localhost",
LocalPort => "10000",
Proto => "tcp",
Listen => 1,
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
my $cli = $sock->accept();
my $safe = Safe->new;
my $x = $safe->reval(join("", <$cli>));
close $cli;
close $sock;
return $x;
}
sub send_data {
my $host = shift;
my $data = shift;
my $sock = IO::Socket::INET->new(
PeerAddr => "$host:10000",
Proto => "tcp",
Reuse => 1);
unless ($sock) { die "Socket creation failure" }
print $sock Data::Dumper->Dump([$data]);
close $sock;
}
if (@ARGV) {
my $x = get_data();
print "Got data\n", Data::Dumper->Dump([$x]);
} else {
send_data('some_host', { a=>100, b=>[1 .. 10] });
}
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Generate a C translation of this Racket snippet without changing its computational steps. | #lang racket/base
(require racket/place/distributed racket/place)
(define (fib n)
(if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(provide work)
(define (work)
(place ch
(place-channel-put ch (fib (place-channel-get ch)))))
(module+ main
(define places
(for/list ([host '("localhost" "localhost" "localhost" "localhost")]
[port (in-naturals 12345)])
(define-values [node place]
(spawn-node-supervise-place-at host #:listen-port port #:thunk #t
(quote-module-path "..") 'work))
place))
(message-router
(after-seconds 1
(for ([p places]) (*channel-put p 42))
(printf "Results: ~s\n" (map *channel-get places))
(exit))))
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Convert this Racket block to C#, preserving its control flow and logic. | #lang racket/base
(require racket/place/distributed racket/place)
(define (fib n)
(if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(provide work)
(define (work)
(place ch
(place-channel-put ch (fib (place-channel-get ch)))))
(module+ main
(define places
(for/list ([host '("localhost" "localhost" "localhost" "localhost")]
[port (in-naturals 12345)])
(define-values [node place]
(spawn-node-supervise-place-at host #:listen-port port #:thunk #t
(quote-module-path "..") 'work))
place))
(message-router
(after-seconds 1
(for ([p places]) (*channel-put p 42))
(printf "Results: ~s\n" (map *channel-get places))
(exit))))
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Keep all operations the same but rewrite the snippet in Python. | #lang racket/base
(require racket/place/distributed racket/place)
(define (fib n)
(if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(provide work)
(define (work)
(place ch
(place-channel-put ch (fib (place-channel-get ch)))))
(module+ main
(define places
(for/list ([host '("localhost" "localhost" "localhost" "localhost")]
[port (in-naturals 12345)])
(define-values [node place]
(spawn-node-supervise-place-at host #:listen-port port #:thunk #t
(quote-module-path "..") 'work))
place))
(message-router
(after-seconds 1
(for ([p places]) (*channel-put p 42))
(printf "Results: ~s\n" (map *channel-get places))
(exit))))
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Translate this program into Go but keep the logic exactly as in Racket. | #lang racket/base
(require racket/place/distributed racket/place)
(define (fib n)
(if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(provide work)
(define (work)
(place ch
(place-channel-put ch (fib (place-channel-get ch)))))
(module+ main
(define places
(for/list ([host '("localhost" "localhost" "localhost" "localhost")]
[port (in-naturals 12345)])
(define-values [node place]
(spawn-node-supervise-place-at host #:listen-port port #:thunk #t
(quote-module-path "..") 'work))
place))
(message-router
(after-seconds 1
(for ([p places]) (*channel-put p 42))
(printf "Results: ~s\n" (map *channel-get places))
(exit))))
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Generate an equivalent C version of this Ruby code. | require 'drb/drb'
URI="druby://localhost:8787"
class TimeServer
def get_current_time
return Time.now
end
end
FRONT_OBJECT = TimeServer.new
$SAFE = 1
DRb.start_service(URI, FRONT_OBJECT)
DRb.thread.join
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Translate the given Ruby code snippet into C# without altering its behavior. | require 'drb/drb'
URI="druby://localhost:8787"
class TimeServer
def get_current_time
return Time.now
end
end
FRONT_OBJECT = TimeServer.new
$SAFE = 1
DRb.start_service(URI, FRONT_OBJECT)
DRb.thread.join
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Port the following code from Ruby to Python with equivalent syntax and logic. | require 'drb/drb'
URI="druby://localhost:8787"
class TimeServer
def get_current_time
return Time.now
end
end
FRONT_OBJECT = TimeServer.new
$SAFE = 1
DRb.start_service(URI, FRONT_OBJECT)
DRb.thread.join
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Write a version of this Ruby function in Go with identical behavior. | require 'drb/drb'
URI="druby://localhost:8787"
class TimeServer
def get_current_time
return Time.now
end
end
FRONT_OBJECT = TimeServer.new
$SAFE = 1
DRb.start_service(URI, FRONT_OBJECT)
DRb.thread.join
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Rewrite the snippet below in C so it works the same as the original Tcl code. | proc main {} {
global connections
set connections [dict create]
socket -server handleConnection 12345
vwait dummyVar ;
}
proc handleConnection {channel clientaddr clientport} {
global connections
dict set connections $channel address "$clientaddr:$clientport"
fconfigure $channel -buffering line
fileevent $channel readable [list handleMessage $channel]
}
proc handleMessage {channel} {
global connections
if {[gets $channel line] == -1} {
disconnect $channel
} else {
if {[string index [string trimleft $line] 0] eq "/"} {
set words [lassign [split [string trim $line]] command]
handleCommand $command $words $channel
} else {
echo $line $channel
}
}
}
proc disconnect {channel} {
global connections
dict unset connections $channel
fileevent $channel readable ""
close $channel
}
proc handleCommand {command words channel} {
global connections
switch -exact -- [string tolower $command] {
/nick {
dict set connections $channel nick [lindex $words 0]
}
/quit {
echo bye $channel
disconnect $channel
}
default {
puts $channel "\"$command\" not implemented"
}
}
}
proc echo {message senderchannel} {
global connections
foreach channel [dict keys $connections] {
if {$channel ne $senderchannel} {
set time [clock format [clock seconds] -format "%T"]
set nick [dict get $connections $channel nick]
puts $channel [format "\[%s\] %s: %s" $time $nick $message]
}
}
}
main
| #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Tcl. | proc main {} {
global connections
set connections [dict create]
socket -server handleConnection 12345
vwait dummyVar ;
}
proc handleConnection {channel clientaddr clientport} {
global connections
dict set connections $channel address "$clientaddr:$clientport"
fconfigure $channel -buffering line
fileevent $channel readable [list handleMessage $channel]
}
proc handleMessage {channel} {
global connections
if {[gets $channel line] == -1} {
disconnect $channel
} else {
if {[string index [string trimleft $line] 0] eq "/"} {
set words [lassign [split [string trim $line]] command]
handleCommand $command $words $channel
} else {
echo $line $channel
}
}
}
proc disconnect {channel} {
global connections
dict unset connections $channel
fileevent $channel readable ""
close $channel
}
proc handleCommand {command words channel} {
global connections
switch -exact -- [string tolower $command] {
/nick {
dict set connections $channel nick [lindex $words 0]
}
/quit {
echo bye $channel
disconnect $channel
}
default {
puts $channel "\"$command\" not implemented"
}
}
}
proc echo {message senderchannel} {
global connections
foreach channel [dict keys $connections] {
if {$channel ne $senderchannel} {
set time [clock format [clock seconds] -format "%T"]
set nick [dict get $connections $channel nick]
puts $channel [format "\[%s\] %s: %s" $time $nick $message]
}
}
}
main
| using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
Convert the following code from Tcl to Python, ensuring the logic remains intact. | proc main {} {
global connections
set connections [dict create]
socket -server handleConnection 12345
vwait dummyVar ;
}
proc handleConnection {channel clientaddr clientport} {
global connections
dict set connections $channel address "$clientaddr:$clientport"
fconfigure $channel -buffering line
fileevent $channel readable [list handleMessage $channel]
}
proc handleMessage {channel} {
global connections
if {[gets $channel line] == -1} {
disconnect $channel
} else {
if {[string index [string trimleft $line] 0] eq "/"} {
set words [lassign [split [string trim $line]] command]
handleCommand $command $words $channel
} else {
echo $line $channel
}
}
}
proc disconnect {channel} {
global connections
dict unset connections $channel
fileevent $channel readable ""
close $channel
}
proc handleCommand {command words channel} {
global connections
switch -exact -- [string tolower $command] {
/nick {
dict set connections $channel nick [lindex $words 0]
}
/quit {
echo bye $channel
disconnect $channel
}
default {
puts $channel "\"$command\" not implemented"
}
}
}
proc echo {message senderchannel} {
global connections
foreach channel [dict keys $connections] {
if {$channel ne $senderchannel} {
set time [clock format [clock seconds] -format "%T"]
set nick [dict get $connections $channel nick]
puts $channel [format "\[%s\] %s: %s" $time $nick $message]
}
}
}
main
|
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
return 'Server responded: %s' % data
def div(self, num1, num2):
return num1/num2
def foo_function():
return True
HOST = "localhost"
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close()
|
Change the following Tcl code into Go without altering its purpose. | proc main {} {
global connections
set connections [dict create]
socket -server handleConnection 12345
vwait dummyVar ;
}
proc handleConnection {channel clientaddr clientport} {
global connections
dict set connections $channel address "$clientaddr:$clientport"
fconfigure $channel -buffering line
fileevent $channel readable [list handleMessage $channel]
}
proc handleMessage {channel} {
global connections
if {[gets $channel line] == -1} {
disconnect $channel
} else {
if {[string index [string trimleft $line] 0] eq "/"} {
set words [lassign [split [string trim $line]] command]
handleCommand $command $words $channel
} else {
echo $line $channel
}
}
}
proc disconnect {channel} {
global connections
dict unset connections $channel
fileevent $channel readable ""
close $channel
}
proc handleCommand {command words channel} {
global connections
switch -exact -- [string tolower $command] {
/nick {
dict set connections $channel nick [lindex $words 0]
}
/quit {
echo bye $channel
disconnect $channel
}
default {
puts $channel "\"$command\" not implemented"
}
}
}
proc echo {message senderchannel} {
global connections
foreach channel [dict keys $connections] {
if {$channel ne $senderchannel} {
set time [clock format [clock seconds] -format "%T"]
set nick [dict get $connections $channel nick]
puts $channel [format "\[%s\] %s: %s" $time $nick $message]
}
}
}
main
| package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
}
|
Preserve the algorithm and functionality while converting the code from Ada to C#. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Generate a C# translation of this Ada snippet without changing its computational steps. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Translate this program into C but keep the logic exactly as in Ada. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Change the programming language of this snippet from Ada to C without modifying what it does. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Ada to C++. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Can you help me rewrite this code in C++ instead of Ada, keeping it the same logically? | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in Go. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Generate an equivalent Go version of this Ada code. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Change the following Ada code into Java without altering its purpose. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Write the same code in Java as shown below in Ada. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Convert this Ada block to Python, preserving its control flow and logic. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Ensure the translated Python code behaves exactly like the original Ada snippet. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Write a version of this Ada function in VB with identical behavior. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| Module Module1
Function CheckISBN13(code As String) As Boolean
code = code.Replace("-", "").Replace(" ", "")
If code.Length <> 13 Then
Return False
End If
Dim sum = 0
For Each i_d In code.Select(Function(digit, index) (index, digit))
Dim index = i_d.index
Dim digit = i_d.digit
If Char.IsDigit(digit) Then
sum += (Asc(digit) - Asc("0")) * If(index Mod 2 = 0, 1, 3)
Else
Return False
End If
Next
Return sum Mod 10 = 0
End Function
Sub Main()
Console.WriteLine(CheckISBN13("978-1734314502"))
Console.WriteLine(CheckISBN13("978-1734314509"))
Console.WriteLine(CheckISBN13("978-1788399081"))
Console.WriteLine(CheckISBN13("978-1788399083"))
End Sub
End Module
|
Generate a VB translation of this Ada snippet without changing its computational steps. | with Ada.Text_IO;
procedure ISBN_Check is
function Is_Valid (ISBN : String) return Boolean is
Odd : Boolean := True;
Sum : Integer := 0;
Value : Integer;
begin
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Character'Pos (ISBN (I)) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
return Sum mod 10 = 0;
end Is_Valid;
procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : constant Boolean := Is_Valid (ISBN);
begin
Put (ISBN); Put (" ");
Put ((if Valid then "Good" else "Bad"));
New_Line;
end Show;
begin
Show ("978-1734314502");
Show ("978-1734314509");
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;
| Module Module1
Function CheckISBN13(code As String) As Boolean
code = code.Replace("-", "").Replace(" ", "")
If code.Length <> 13 Then
Return False
End If
Dim sum = 0
For Each i_d In code.Select(Function(digit, index) (index, digit))
Dim index = i_d.index
Dim digit = i_d.digit
If Char.IsDigit(digit) Then
sum += (Asc(digit) - Asc("0")) * If(index Mod 2 = 0, 1, 3)
Else
Return False
End If
Next
Return sum Mod 10 = 0
End Function
Sub Main()
Console.WriteLine(CheckISBN13("978-1734314502"))
Console.WriteLine(CheckISBN13("978-1734314509"))
Console.WriteLine(CheckISBN13("978-1788399081"))
Console.WriteLine(CheckISBN13("978-1788399083"))
End Sub
End Module
|
Convert the following code from Arturo to C, ensuring the logic remains intact. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Write the same algorithm in C as shown in this Arturo implementation. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Please provide an equivalent version of this Arturo code in C#. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Please provide an equivalent version of this Arturo code in C#. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Arturo version. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Can you help me rewrite this code in Java instead of Arturo, keeping it the same logically? | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Rewrite the snippet below in Java so it works the same as the original Arturo code. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Keep all operations the same but rewrite the snippet in Python. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Maintain the same structure and functionality when rewriting this code in Python. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Convert the following code from Arturo to VB, ensuring the logic remains intact. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Please provide an equivalent version of this Arturo code in VB. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Generate an equivalent Go version of this Arturo code. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Port the following code from Arturo to Go with equivalent syntax and logic. | validISBN?: function [isbn][
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
s: 0
loop.with:'i isbn 'n [
if? even? i -> s: s + n
else -> s: s + 3*n
]
checkDigit: 10 - s % 10
return currentCheck = checkDigit
]
tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]
loop tests 'test [
print [test "=>" validISBN? test]
]
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Maintain the same structure and functionality when rewriting this code in C. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original AutoHotKey code. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Port the following code from AutoHotKey to C# with equivalent syntax and logic. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Change the following AutoHotKey code into C# without altering its purpose. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Please provide an equivalent version of this AutoHotKey code in C++. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Convert this AutoHotKey block to Java, preserving its control flow and logic. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Keep all operations the same but rewrite the snippet in Java. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Change the programming language of this snippet from AutoHotKey to Python without modifying what it does. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Change the programming language of this snippet from AutoHotKey to Python without modifying what it does. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Rewrite the snippet below in VB so it works the same as the original AutoHotKey code. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Port the following code from AutoHotKey to VB with equivalent syntax and logic. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Can you help me rewrite this code in Go instead of AutoHotKey, keeping it the same logically? | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Produce a language-to-language conversion: from AutoHotKey to Go, same semantics. | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the AWK version. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Change the following AWK code into C without altering its purpose. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Ensure the translated C# code behaves exactly like the original AWK snippet. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Generate a C# translation of this AWK snippet without changing its computational steps. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Please provide an equivalent version of this AWK code in C++. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Write a version of this AWK function in C++ with identical behavior. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Change the programming language of this snippet from AWK to Java without modifying what it does. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Change the following AWK code into Java without altering its purpose. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Port the provided AWK code into Python while preserving the original functionality. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Change the programming language of this snippet from AWK to Python without modifying what it does. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Rewrite the snippet below in VB so it works the same as the original AWK code. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Please provide an equivalent version of this AWK code in VB. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Preserve the algorithm and functionality while converting the code from AWK to Go. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Port the following code from AWK to Go with equivalent syntax and logic. |
BEGIN {
arr[++n] = "978-1734314502"
arr[++n] = "978-1734314509"
arr[++n] = "978-1788399081"
arr[++n] = "978-1788399083"
arr[++n] = "9780820424521"
arr[++n] = "0820424528"
for (i=1; i<=n; i++) {
printf("%s %s\n",arr[i],isbn13(arr[i]))
}
exit(0)
}
function isbn13(isbn, check_digit,i,sum) {
gsub(/[ -]/,"",isbn)
if (length(isbn) != 13) { return("NG length") }
for (i=1; i<=12; i++) {
sum += substr(isbn,i,1) * (i % 2 == 1 ? 1 : 3)
}
check_digit = 10 - (sum % 10)
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Write the same algorithm in C as shown in this Common_Lisp implementation. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Common_Lisp version. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Ensure the translated C++ code behaves exactly like the original Common_Lisp snippet. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Generate a C++ translation of this Common_Lisp snippet without changing its computational steps. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Translate this program into Java but keep the logic exactly as in Common_Lisp. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Produce a functionally identical Java code for the snippet given in Common_Lisp. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Transform the following Common_Lisp implementation into Python, maintaining the same output and logic. | ISBN13Check
=LAMBDA(s,
LET(
ns, FILTERP(
LAMBDA(v,
NOT(ISERROR(v))
)
)(
VALUE(CHARSROW(s))
),
ixs, SEQUENCE(
1, COLUMNS(ns),
1, 1
),
0 = MOD(
SUM(
IF(0 <> MOD(ixs, 2),
INDEX(ns, ixs),
3 * INDEX(ns, ixs)
)
),
10
)
)
)
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.