Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from COBOL to Java with equivalent syntax and logic.
program-id. ehello. procedure division. display "Goodbye, world!" upon syserr. stop run.
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
Rewrite this program in Python while keeping its functionality equivalent to the COBOL version.
program-id. ehello. procedure division. display "Goodbye, world!" upon syserr. stop run.
import sys print >> sys.stderr, "Goodbye, World!"
Translate this program into VB but keep the logic exactly as in COBOL.
program-id. ehello. procedure division. display "Goodbye, world!" upon syserr. stop run.
Sub StandardError() Debug.Print "Goodbye World!" End Sub
Can you help me rewrite this code in Go instead of COBOL, keeping it the same logically?
program-id. ehello. procedure division. display "Goodbye, world!" upon syserr. stop run.
package main func main() { println("Goodbye, World!") }
Port the following code from REXX to C with equivalent syntax and logic.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
Please provide an equivalent version of this REXX code in C#.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
Can you help me rewrite this code in C++ instead of REXX, keeping it the same logically?
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
Port the provided REXX code into Java while preserving the original functionality.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
Change the following REXX code into Python without altering its purpose.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
import sys print >> sys.stderr, "Goodbye, World!"
Generate a VB translation of this REXX snippet without changing its computational steps.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
Sub StandardError() Debug.Print "Goodbye World!" End Sub
Write the same algorithm in Go as shown in this REXX implementation.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
package main func main() { println("Goodbye, World!") }
Preserve the algorithm and functionality while converting the code from Ruby to C.
STDERR.puts "Goodbye, World!"
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
Translate the given Ruby code snippet into C# without altering its behavior.
STDERR.puts "Goodbye, World!"
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
Write the same code in C++ as shown below in Ruby.
STDERR.puts "Goodbye, World!"
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
Ensure the translated Java code behaves exactly like the original Ruby snippet.
STDERR.puts "Goodbye, World!"
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
Maintain the same structure and functionality when rewriting this code in C.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Scala version.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
Generate a C++ translation of this Scala snippet without changing its computational steps.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
Convert this Scala snippet to Java and keep its semantics consistent.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
Rewrite the snippet below in Python so it works the same as the original Scala code.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
import sys print >> sys.stderr, "Goodbye, World!"
Preserve the algorithm and functionality while converting the code from Scala to VB.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
Sub StandardError() Debug.Print "Goodbye World!" End Sub
Convert this Scala snippet to Go and keep its semantics consistent.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
package main func main() { println("Goodbye, World!") }
Produce a functionally identical C code for the snippet given in Swift.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
Convert the following code from Swift to C#, ensuring the logic remains intact.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
Convert this Swift snippet to C++ and keep its semantics consistent.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
Convert this Swift snippet to Java and keep its semantics consistent.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
Generate a Python translation of this Swift snippet without changing its computational steps.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
import sys print >> sys.stderr, "Goodbye, World!"
Rewrite this program in VB while keeping its functionality equivalent to the Swift version.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
Sub StandardError() Debug.Print "Goodbye World!" End Sub
Convert this Swift snippet to Go and keep its semantics consistent.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
package main func main() { println("Goodbye, World!") }
Write the same algorithm in C as shown in this Tcl implementation.
puts stderr "Goodbye, World!"
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
puts stderr "Goodbye, World!"
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
Ensure the translated C++ code behaves exactly like the original Tcl snippet.
puts stderr "Goodbye, World!"
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
Keep all operations the same but rewrite the snippet in Java.
puts stderr "Goodbye, World!"
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
Convert this Ada snippet to PHP and keep its semantics consistent.
with Ada.Text_IO; use Ada.Text_IO; procedure Goodbye_World is begin Put_Line (Standard_Error, "Goodbye, World!"); end Goodbye_World;
fprintf(STDERR, "Goodbye, World!\n");
Generate an equivalent PHP version of this BBC_Basic code.
STD_ERROR_HANDLE = -12 SYS "GetStdHandle", STD_ERROR_HANDLE TO @hfile%(1) PRINT #13, "Goodbye, World!" QUIT
fprintf(STDERR, "Goodbye, World!\n");
Translate the given Common_Lisp code snippet into PHP without altering its behavior.
(binding [*out* *err*] (println "Goodbye, world!"))
fprintf(STDERR, "Goodbye, World!\n");
Change the programming language of this snippet from D to PHP without modifying what it does.
import std.stdio; void main () { stderr.writeln("Goodbye, World!"); }
fprintf(STDERR, "Goodbye, World!\n");
Translate the given Delphi code snippet into PHP without altering its behavior.
program Project1; begin WriteLn(ErrOutput, 'Goodbye, World!'); end.
fprintf(STDERR, "Goodbye, World!\n");
Produce a language-to-language conversion: from Forth to PHP, same semantics.
outfile-id stderr to outfile-id ." Goodbye, World!" cr to outfile-id
fprintf(STDERR, "Goodbye, World!\n");
Change the programming language of this snippet from Fortran to PHP without modifying what it does.
program StdErr use iso_fortran_env write (ERROR_UNIT, *) "Goodbye, World end program StdErr
fprintf(STDERR, "Goodbye, World!\n");
Preserve the algorithm and functionality while converting the code from OCaml to PHP.
prerr_endline "Goodbye, World!"; Printf.eprintf "Goodbye, World!\n";
fprintf(STDERR, "Goodbye, World!\n");
Write a version of this Pascal function in PHP with identical behavior.
program byeworld; begin writeln(StdErr, 'Goodbye, World!'); end.
fprintf(STDERR, "Goodbye, World!\n");
Rewrite this program in PHP while keeping its functionality equivalent to the COBOL version.
program-id. ehello. procedure division. display "Goodbye, world!" upon syserr. stop run.
fprintf(STDERR, "Goodbye, World!\n");
Generate an equivalent PHP version of this REXX code.
options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
fprintf(STDERR, "Goodbye, World!\n");
Generate an equivalent PHP version of this Scala code.
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
fprintf(STDERR, "Goodbye, World!\n");
Transform the following Swift implementation into PHP, maintaining the same output and logic.
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("\nWrote \(bytes) bytes") }
fprintf(STDERR, "Goodbye, World!\n");
Please provide an equivalent version of this C code in Rust.
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr); return 0; }
fn main() { eprintln!("Hello, {}!", "world"); }
Ensure the translated Rust code behaves exactly like the original Java snippet.
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
fn main() { eprintln!("Hello, {}!", "world"); }
Write the same code in Rust as shown below in Go.
package main func main() { println("Goodbye, World!") }
fn main() { eprintln!("Hello, {}!", "world"); }
Change the following Rust code into Python without altering its purpose.
fn main() { eprintln!("Hello, {}!", "world"); }
import sys print >> sys.stderr, "Goodbye, World!"
Maintain the same structure and functionality when rewriting this code in VB.
fn main() { eprintln!("Hello, {}!", "world"); }
Sub StandardError() Debug.Print "Goodbye World!" End Sub
Write the same code in Rust as shown below in C#.
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
fn main() { eprintln!("Hello, {}!", "world"); }
Rewrite this program in Rust while keeping its functionality equivalent to the C++ version.
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
fn main() { eprintln!("Hello, {}!", "world"); }
Preserve the algorithm and functionality while converting the code from Ada to C#.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Convert the following code from Ada to C, ensuring the logic remains intact.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Ensure the translated C++ code behaves exactly like the original Ada snippet.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Ensure the translated Go code behaves exactly like the original Ada snippet.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Convert this Ada snippet to Java and keep its semantics consistent.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Rewrite this program in Python while keeping its functionality equivalent to the Ada version.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Write a version of this Arturo function in C with identical behavior.
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Can you help me rewrite this code in C# instead of Arturo, keeping it the same logically?
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Convert the following code from Arturo to C++, ensuring the logic remains intact.
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Translate this program into Java but keep the logic exactly as in Arturo.
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Rewrite the snippet below in Python so it works the same as the original Arturo code.
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Generate an equivalent Go version of this Arturo code.
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Convert this AutoHotKey block to C, preserving its control flow and logic.
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Produce a language-to-language conversion: from AutoHotKey to C#, same semantics.
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Translate the given AutoHotKey code snippet into C++ without altering its behavior.
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Convert this AutoHotKey block to Java, preserving its control flow and logic.
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Produce a language-to-language conversion: from AutoHotKey to Python, same semantics.
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Maintain the same structure and functionality when rewriting this code in Go.
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Preserve the algorithm and functionality while converting the code from AWK to C.
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Write a version of this AWK function in C# with identical behavior.
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Generate a C++ translation of this AWK snippet without changing its computational steps.
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Convert this AWK block to Java, preserving its control flow and logic.
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Can you help me rewrite this code in Python instead of AWK, keeping it the same logically?
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Ensure the translated Go code behaves exactly like the original AWK snippet.
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Generate a C translation of this BBC_Basic snippet without changing its computational steps.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Produce a functionally identical C# code for the snippet given in BBC_Basic.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Write the same code in C++ as shown below in BBC_Basic.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Translate the given BBC_Basic code snippet into Java without altering its behavior.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Change the following BBC_Basic code into Python without altering its purpose.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Port the provided BBC_Basic code into Go while preserving the original functionality.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Convert this Clojure snippet to C and keep its semantics consistent.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Preserve the algorithm and functionality while converting the code from Clojure to C#.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Produce a language-to-language conversion: from Clojure to C++, same semantics.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Rewrite the snippet below in Java so it works the same as the original Clojure code.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Convert this Clojure block to Python, preserving its control flow and logic.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Convert the following code from Clojure to Go, ensuring the logic remains intact.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Ensure the translated C code behaves exactly like the original Common_Lisp snippet.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Port the provided Common_Lisp code into C# while preserving the original functionality.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Please provide an equivalent version of this Common_Lisp code in C++.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Translate this program into Java but keep the logic exactly as in Common_Lisp.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Please provide an equivalent version of this Common_Lisp code in Python.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Rewrite this program in Go while keeping its functionality equivalent to the Common_Lisp version.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Change the programming language of this snippet from D to C without modifying what it does.
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; char checksum(in char[] sedol) pure @safe in { assert(sedol.length == 6); foreach (immutable c; sedol) assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { assert(result.isDigit); } body { static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); return digits[10 - (d % 10)]; } void main() { foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".split) writeln(sedol, sedol.checksum); }
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Translate the given D code snippet into C# without altering its behavior.
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; char checksum(in char[] sedol) pure @safe in { assert(sedol.length == 6); foreach (immutable c; sedol) assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { assert(result.isDigit); } body { static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); return digits[10 - (d % 10)]; } void main() { foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".split) writeln(sedol, sedol.checksum); }
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Can you help me rewrite this code in C++ instead of D, keeping it the same logically?
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; char checksum(in char[] sedol) pure @safe in { assert(sedol.length == 6); foreach (immutable c; sedol) assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { assert(result.isDigit); } body { static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); return digits[10 - (d % 10)]; } void main() { foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".split) writeln(sedol, sedol.checksum); }
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Can you help me rewrite this code in Java instead of D, keeping it the same logically?
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; char checksum(in char[] sedol) pure @safe in { assert(sedol.length == 6); foreach (immutable c; sedol) assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { assert(result.isDigit); } body { static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); return digits[10 - (d % 10)]; } void main() { foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".split) writeln(sedol, sedol.checksum); }
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Ensure the translated Python code behaves exactly like the original D snippet.
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; char checksum(in char[] sedol) pure @safe in { assert(sedol.length == 6); foreach (immutable c; sedol) assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { assert(result.isDigit); } body { static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); return digits[10 - (d % 10)]; } void main() { foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".split) writeln(sedol, sedol.checksum); }
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)