Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given D code snippet into Go 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); }
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) } } }
Write the same code in C as shown below in Delphi.
program Sedol; uses SysUtils; const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9; function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; end; Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0')); Result := Sedol + CheckDigit; end; procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end; begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.
#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 the same code in C# as shown below in Delphi.
program Sedol; uses SysUtils; const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9; function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; end; Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0')); Result := Sedol + CheckDigit; end; procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end; begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.
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 this Delphi block to C++, preserving its control flow and logic.
program Sedol; uses SysUtils; const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9; function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; end; Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0')); Result := Sedol + CheckDigit; end; procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end; begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.
#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; }
Write the same code in Java as shown below in Delphi.
program Sedol; uses SysUtils; const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9; function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; end; Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0')); Result := Sedol + CheckDigit; end; procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end; begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.
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].*?"); } }
Preserve the algorithm and functionality while converting the code from Delphi to Python.
program Sedol; uses SysUtils; const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9; function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; end; Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0')); Result := Sedol + CheckDigit; end; procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end; begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.
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)
Transform the following Delphi implementation into Go, maintaining the same output and logic.
program Sedol; uses SysUtils; const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9; function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; end; Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0')); Result := Sedol + CheckDigit; end; procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end; begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.
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) } } }
Produce a language-to-language conversion: from Elixir to C, same semantics.
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9] defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A } Enum.each(data, fn sedol -> :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
#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 Elixir to C#, same semantics.
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9] defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A } Enum.each(data, fn sedol -> :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
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 this Elixir block to C++, preserving its control flow and logic.
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9] defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A } Enum.each(data, fn sedol -> :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
#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 Elixir code snippet into Java without altering its behavior.
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9] defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A } Enum.each(data, fn sedol -> :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
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].*?"); } }
Preserve the algorithm and functionality while converting the code from Elixir to Python.
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9] defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A } Enum.each(data, fn sedol -> :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
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 Elixir code.
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9] defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A } Enum.each(data, fn sedol -> :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
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) } } }
Produce a functionally identical C code for the snippet given in F#.
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"] let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1] let inline isVowel c = Vowels.Contains (Char.ToUpper c) let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10 let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10 let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString()) let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
#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 the same algorithm in C# as shown in this F# implementation.
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"] let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1] let inline isVowel c = Vowels.Contains (Char.ToUpper c) let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10 let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10 let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString()) let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
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 F# to C++, same semantics.
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"] let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1] let inline isVowel c = Vowels.Contains (Char.ToUpper c) let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10 let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10 let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString()) let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
#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 F# code snippet into Java without altering its behavior.
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"] let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1] let inline isVowel c = Vowels.Contains (Char.ToUpper c) let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10 let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10 let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString()) let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
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].*?"); } }
Maintain the same structure and functionality when rewriting this code in Python.
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"] let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1] let inline isVowel c = Vowels.Contains (Char.ToUpper c) let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10 let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10 let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString()) let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
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 F# to Go, ensuring the logic remains intact.
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"] let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1] let inline isVowel c = Vowels.Contains (Char.ToUpper c) let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10 let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10 let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString()) let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
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 following Factor code into C without altering its purpose.
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols <PRIVATE CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" } CONSTANT: weights B{ 1 3 1 7 3 9 1 } : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ; : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ; : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ; : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ; : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ; PRIVATE> : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ; : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s %s\n" printf ] each ; MAIN: sedol-demo
#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 Factor.
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols <PRIVATE CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" } CONSTANT: weights B{ 1 3 1 7 3 9 1 } : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ; : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ; : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ; : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ; : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ; PRIVATE> : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ; : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s %s\n" printf ] each ; MAIN: sedol-demo
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; }
Change the following Factor code into C++ without altering its purpose.
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols <PRIVATE CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" } CONSTANT: weights B{ 1 3 1 7 3 9 1 } : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ; : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ; : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ; : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ; : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ; PRIVATE> : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ; : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s %s\n" printf ] each ; MAIN: sedol-demo
#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; }
Produce a functionally identical Java code for the snippet given in Factor.
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols <PRIVATE CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" } CONSTANT: weights B{ 1 3 1 7 3 9 1 } : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ; : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ; : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ; : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ; : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ; PRIVATE> : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ; : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s %s\n" printf ] each ; MAIN: sedol-demo
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].*?"); } }
Write the same code in Python as shown below in Factor.
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols <PRIVATE CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" } CONSTANT: weights B{ 1 3 1 7 3 9 1 } : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ; : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ; : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ; : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ; : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ; PRIVATE> : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ; : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s %s\n" printf ] each ; MAIN: sedol-demo
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)
Change the programming language of this snippet from Factor to Go without modifying what it does.
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols <PRIVATE CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" } CONSTANT: weights B{ 1 3 1 7 3 9 1 } : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ; : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ; : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ; : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ; : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ; PRIVATE> : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ; : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s %s\n" printf ] each ; MAIN: sedol-demo
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) } } }
Produce a language-to-language conversion: from Forth to C, same semantics.
create weight 1 , 3 , 1 , 7 , 3 , 9 , : char>num dup [char] 9 > 7 and - [char] 0 - ; : check+ 6 <> abort" wrong SEDOL length" 0 6 0 do over I + c@ char>num weight I cells + @ * + loop 10 mod 10 swap - 10 mod [char] 0 + over 6 + c! 7 ; : sedol" [char] " parse check+ type ; sedol" 710889" 7108899 ok sedol" B0YBKJ" B0YBKJ7 ok sedol" 406566" 4065663 ok sedol" B0YBLH" B0YBLH2 ok sedol" 228276" 2282765 ok sedol" B0YBKL" B0YBKL9 ok sedol" 557910" 5579107 ok sedol" B0YBKR" B0YBKR5 ok sedol" 585284" 5852842 ok sedol" B0YBKT" B0YBKT7 ok
#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; }
Maintain the same structure and functionality when rewriting this code in C#.
create weight 1 , 3 , 1 , 7 , 3 , 9 , : char>num dup [char] 9 > 7 and - [char] 0 - ; : check+ 6 <> abort" wrong SEDOL length" 0 6 0 do over I + c@ char>num weight I cells + @ * + loop 10 mod 10 swap - 10 mod [char] 0 + over 6 + c! 7 ; : sedol" [char] " parse check+ type ; sedol" 710889" 7108899 ok sedol" B0YBKJ" B0YBKJ7 ok sedol" 406566" 4065663 ok sedol" B0YBLH" B0YBLH2 ok sedol" 228276" 2282765 ok sedol" B0YBKL" B0YBKL9 ok sedol" 557910" 5579107 ok sedol" B0YBKR" B0YBKR5 ok sedol" 585284" 5852842 ok sedol" B0YBKT" B0YBKT7 ok
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; }
Ensure the translated C++ code behaves exactly like the original Forth snippet.
create weight 1 , 3 , 1 , 7 , 3 , 9 , : char>num dup [char] 9 > 7 and - [char] 0 - ; : check+ 6 <> abort" wrong SEDOL length" 0 6 0 do over I + c@ char>num weight I cells + @ * + loop 10 mod 10 swap - 10 mod [char] 0 + over 6 + c! 7 ; : sedol" [char] " parse check+ type ; sedol" 710889" 7108899 ok sedol" B0YBKJ" B0YBKJ7 ok sedol" 406566" 4065663 ok sedol" B0YBLH" B0YBLH2 ok sedol" 228276" 2282765 ok sedol" B0YBKL" B0YBKL9 ok sedol" 557910" 5579107 ok sedol" B0YBKR" B0YBKR5 ok sedol" 585284" 5852842 ok sedol" B0YBKT" B0YBKT7 ok
#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; }
Change the programming language of this snippet from Forth to Java without modifying what it does.
create weight 1 , 3 , 1 , 7 , 3 , 9 , : char>num dup [char] 9 > 7 and - [char] 0 - ; : check+ 6 <> abort" wrong SEDOL length" 0 6 0 do over I + c@ char>num weight I cells + @ * + loop 10 mod 10 swap - 10 mod [char] 0 + over 6 + c! 7 ; : sedol" [char] " parse check+ type ; sedol" 710889" 7108899 ok sedol" B0YBKJ" B0YBKJ7 ok sedol" 406566" 4065663 ok sedol" B0YBLH" B0YBLH2 ok sedol" 228276" 2282765 ok sedol" B0YBKL" B0YBKL9 ok sedol" 557910" 5579107 ok sedol" B0YBKR" B0YBKR5 ok sedol" 585284" 5852842 ok sedol" B0YBKT" B0YBKT7 ok
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].*?"); } }
Port the following code from Forth to Python with equivalent syntax and logic.
create weight 1 , 3 , 1 , 7 , 3 , 9 , : char>num dup [char] 9 > 7 and - [char] 0 - ; : check+ 6 <> abort" wrong SEDOL length" 0 6 0 do over I + c@ char>num weight I cells + @ * + loop 10 mod 10 swap - 10 mod [char] 0 + over 6 + c! 7 ; : sedol" [char] " parse check+ type ; sedol" 710889" 7108899 ok sedol" B0YBKJ" B0YBKJ7 ok sedol" 406566" 4065663 ok sedol" B0YBLH" B0YBLH2 ok sedol" 228276" 2282765 ok sedol" B0YBKL" B0YBKL9 ok sedol" 557910" 5579107 ok sedol" B0YBKR" B0YBKR5 ok sedol" 585284" 5852842 ok sedol" B0YBKT" B0YBKT7 ok
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)
Please provide an equivalent version of this Forth code in Go.
create weight 1 , 3 , 1 , 7 , 3 , 9 , : char>num dup [char] 9 > 7 and - [char] 0 - ; : check+ 6 <> abort" wrong SEDOL length" 0 6 0 do over I + c@ char>num weight I cells + @ * + loop 10 mod 10 swap - 10 mod [char] 0 + over 6 + c! 7 ; : sedol" [char] " parse check+ type ; sedol" 710889" 7108899 ok sedol" B0YBKJ" B0YBKJ7 ok sedol" 406566" 4065663 ok sedol" B0YBLH" B0YBLH2 ok sedol" 228276" 2282765 ok sedol" B0YBKL" B0YBKL9 ok sedol" 557910" 5579107 ok sedol" B0YBKR" B0YBKR5 ok sedol" 585284" 5852842 ok sedol" B0YBKT" B0YBKT7 ok
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 following Fortran code into C# without altering its purpose.
MODULE SEDOL_CHECK IMPLICIT NONE CONTAINS FUNCTION Checkdigit(c) CHARACTER :: Checkdigit CHARACTER(6), INTENT(IN) :: c CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp INTEGER :: i, n DO i = 1, 6 temp(i) = INDEX(alpha, c(i:i)) - 1 END DO temp = temp * weights n = MOD(10 - (MOD(SUM(temp), 10)), 10) Checkdigit = ACHAR(n + 48) END FUNCTION Checkdigit END MODULE SEDOL_CHECK PROGRAM SEDOLTEST USE SEDOL_CHECK IMPLICIT NONE CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ" CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , & "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /) CHARACTER(7) :: sedol INTEGER :: i, invalid DO i = 1, 10 invalid = VERIFY(codes(i), valid) IF (invalid == 0) THEN sedol = codes(i) sedol(7:7) = Checkdigit(codes(i)) ELSE sedol = "INVALID" END IF WRITE(*, "(2A9)") codes(i), sedol END DO END PROGRAM SEDOLTEST
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; }
Keep all operations the same but rewrite the snippet in C++.
MODULE SEDOL_CHECK IMPLICIT NONE CONTAINS FUNCTION Checkdigit(c) CHARACTER :: Checkdigit CHARACTER(6), INTENT(IN) :: c CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp INTEGER :: i, n DO i = 1, 6 temp(i) = INDEX(alpha, c(i:i)) - 1 END DO temp = temp * weights n = MOD(10 - (MOD(SUM(temp), 10)), 10) Checkdigit = ACHAR(n + 48) END FUNCTION Checkdigit END MODULE SEDOL_CHECK PROGRAM SEDOLTEST USE SEDOL_CHECK IMPLICIT NONE CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ" CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , & "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /) CHARACTER(7) :: sedol INTEGER :: i, invalid DO i = 1, 10 invalid = VERIFY(codes(i), valid) IF (invalid == 0) THEN sedol = codes(i) sedol(7:7) = Checkdigit(codes(i)) ELSE sedol = "INVALID" END IF WRITE(*, "(2A9)") codes(i), sedol END DO END PROGRAM SEDOLTEST
#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; }
Preserve the algorithm and functionality while converting the code from Fortran to C.
MODULE SEDOL_CHECK IMPLICIT NONE CONTAINS FUNCTION Checkdigit(c) CHARACTER :: Checkdigit CHARACTER(6), INTENT(IN) :: c CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp INTEGER :: i, n DO i = 1, 6 temp(i) = INDEX(alpha, c(i:i)) - 1 END DO temp = temp * weights n = MOD(10 - (MOD(SUM(temp), 10)), 10) Checkdigit = ACHAR(n + 48) END FUNCTION Checkdigit END MODULE SEDOL_CHECK PROGRAM SEDOLTEST USE SEDOL_CHECK IMPLICIT NONE CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ" CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , & "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /) CHARACTER(7) :: sedol INTEGER :: i, invalid DO i = 1, 10 invalid = VERIFY(codes(i), valid) IF (invalid == 0) THEN sedol = codes(i) sedol(7:7) = Checkdigit(codes(i)) ELSE sedol = "INVALID" END IF WRITE(*, "(2A9)") codes(i), sedol END DO END PROGRAM SEDOLTEST
#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 Java code for the snippet given in Fortran.
MODULE SEDOL_CHECK IMPLICIT NONE CONTAINS FUNCTION Checkdigit(c) CHARACTER :: Checkdigit CHARACTER(6), INTENT(IN) :: c CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp INTEGER :: i, n DO i = 1, 6 temp(i) = INDEX(alpha, c(i:i)) - 1 END DO temp = temp * weights n = MOD(10 - (MOD(SUM(temp), 10)), 10) Checkdigit = ACHAR(n + 48) END FUNCTION Checkdigit END MODULE SEDOL_CHECK PROGRAM SEDOLTEST USE SEDOL_CHECK IMPLICIT NONE CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ" CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , & "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /) CHARACTER(7) :: sedol INTEGER :: i, invalid DO i = 1, 10 invalid = VERIFY(codes(i), valid) IF (invalid == 0) THEN sedol = codes(i) sedol(7:7) = Checkdigit(codes(i)) ELSE sedol = "INVALID" END IF WRITE(*, "(2A9)") codes(i), sedol END DO END PROGRAM SEDOLTEST
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].*?"); } }
Preserve the algorithm and functionality while converting the code from Fortran to Python.
MODULE SEDOL_CHECK IMPLICIT NONE CONTAINS FUNCTION Checkdigit(c) CHARACTER :: Checkdigit CHARACTER(6), INTENT(IN) :: c CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp INTEGER :: i, n DO i = 1, 6 temp(i) = INDEX(alpha, c(i:i)) - 1 END DO temp = temp * weights n = MOD(10 - (MOD(SUM(temp), 10)), 10) Checkdigit = ACHAR(n + 48) END FUNCTION Checkdigit END MODULE SEDOL_CHECK PROGRAM SEDOLTEST USE SEDOL_CHECK IMPLICIT NONE CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ" CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , & "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /) CHARACTER(7) :: sedol INTEGER :: i, invalid DO i = 1, 10 invalid = VERIFY(codes(i), valid) IF (invalid == 0) THEN sedol = codes(i) sedol(7:7) = Checkdigit(codes(i)) ELSE sedol = "INVALID" END IF WRITE(*, "(2A9)") codes(i), sedol END DO END PROGRAM SEDOLTEST
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 PHP version of this Fortran code.
MODULE SEDOL_CHECK IMPLICIT NONE CONTAINS FUNCTION Checkdigit(c) CHARACTER :: Checkdigit CHARACTER(6), INTENT(IN) :: c CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp INTEGER :: i, n DO i = 1, 6 temp(i) = INDEX(alpha, c(i:i)) - 1 END DO temp = temp * weights n = MOD(10 - (MOD(SUM(temp), 10)), 10) Checkdigit = ACHAR(n + 48) END FUNCTION Checkdigit END MODULE SEDOL_CHECK PROGRAM SEDOLTEST USE SEDOL_CHECK IMPLICIT NONE CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ" CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , & "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /) CHARACTER(7) :: sedol INTEGER :: i, invalid DO i = 1, 10 invalid = VERIFY(codes(i), valid) IF (invalid == 0) THEN sedol = codes(i) sedol(7:7) = Checkdigit(codes(i)) ELSE sedol = "INVALID" END IF WRITE(*, "(2A9)") codes(i), sedol END DO END PROGRAM SEDOLTEST
function char2value($c) { assert(stripos('AEIOU', $c) === FALSE); return intval($c, 36); } $sedolweight = array(1,3,1,7,3,9); function checksum($sedol) { global $sedolweight; $tmp = array_sum(array_map(create_function('$ch, $weight', 'return char2value($ch) * $weight;'), str_split($sedol), $sedolweight) ); return strval((10 - ($tmp % 10)) % 10); } foreach (array('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT') as $sedol) echo $sedol, checksum($sedol), "\n";
Please provide an equivalent version of this Groovy code in C.
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
#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; }
Maintain the same structure and functionality when rewriting this code in C#.
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
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 Groovy code in C++.
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
#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 Groovy.
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
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 functionally identical Python code for the snippet given in Groovy.
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
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.
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
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) } } }
Port the provided Haskell code into C while preserving the original functionality.
import Data.Char (isAsciiUpper, isDigit, ord) checkSum :: String -> String checkSum x = case traverse sedolValue x of Right xs -> (show . checkSumFromSedolValues) xs Left annotated -> annotated checkSumFromSedolValues :: [Int] -> Int checkSumFromSedolValues xs = rem ( 10 - rem ( sum $ zipWith (*) [1, 3, 1, 7, 3, 9] xs ) 10 ) 10 sedolValue :: Char -> Either String Int sedolValue c | c `elem` "AEIOU" = Left " ← Unexpected vowel." | isDigit c = Right (ord c - ord '0') | isAsciiUpper c = Right (ord c - ord 'A' + 10) main :: IO () main = mapM_ (putStrLn . ((<>) <*> checkSum)) [ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "BOYBKT", "B00030" ]
#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 Haskell to C++, same semantics.
import Data.Char (isAsciiUpper, isDigit, ord) checkSum :: String -> String checkSum x = case traverse sedolValue x of Right xs -> (show . checkSumFromSedolValues) xs Left annotated -> annotated checkSumFromSedolValues :: [Int] -> Int checkSumFromSedolValues xs = rem ( 10 - rem ( sum $ zipWith (*) [1, 3, 1, 7, 3, 9] xs ) 10 ) 10 sedolValue :: Char -> Either String Int sedolValue c | c `elem` "AEIOU" = Left " ← Unexpected vowel." | isDigit c = Right (ord c - ord '0') | isAsciiUpper c = Right (ord c - ord 'A' + 10) main :: IO () main = mapM_ (putStrLn . ((<>) <*> checkSum)) [ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "BOYBKT", "B00030" ]
#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; }
Generate an equivalent Java version of this Haskell code.
import Data.Char (isAsciiUpper, isDigit, ord) checkSum :: String -> String checkSum x = case traverse sedolValue x of Right xs -> (show . checkSumFromSedolValues) xs Left annotated -> annotated checkSumFromSedolValues :: [Int] -> Int checkSumFromSedolValues xs = rem ( 10 - rem ( sum $ zipWith (*) [1, 3, 1, 7, 3, 9] xs ) 10 ) 10 sedolValue :: Char -> Either String Int sedolValue c | c `elem` "AEIOU" = Left " ← Unexpected vowel." | isDigit c = Right (ord c - ord '0') | isAsciiUpper c = Right (ord c - ord 'A' + 10) main :: IO () main = mapM_ (putStrLn . ((<>) <*> checkSum)) [ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "BOYBKT", "B00030" ]
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].*?"); } }
Generate a Python translation of this Haskell snippet without changing its computational steps.
import Data.Char (isAsciiUpper, isDigit, ord) checkSum :: String -> String checkSum x = case traverse sedolValue x of Right xs -> (show . checkSumFromSedolValues) xs Left annotated -> annotated checkSumFromSedolValues :: [Int] -> Int checkSumFromSedolValues xs = rem ( 10 - rem ( sum $ zipWith (*) [1, 3, 1, 7, 3, 9] xs ) 10 ) 10 sedolValue :: Char -> Either String Int sedolValue c | c `elem` "AEIOU" = Left " ← Unexpected vowel." | isDigit c = Right (ord c - ord '0') | isAsciiUpper c = Right (ord c - ord 'A' + 10) main :: IO () main = mapM_ (putStrLn . ((<>) <*> checkSum)) [ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "BOYBKT", "B00030" ]
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)
Keep all operations the same but rewrite the snippet in Go.
import Data.Char (isAsciiUpper, isDigit, ord) checkSum :: String -> String checkSum x = case traverse sedolValue x of Right xs -> (show . checkSumFromSedolValues) xs Left annotated -> annotated checkSumFromSedolValues :: [Int] -> Int checkSumFromSedolValues xs = rem ( 10 - rem ( sum $ zipWith (*) [1, 3, 1, 7, 3, 9] xs ) 10 ) 10 sedolValue :: Char -> Either String Int sedolValue c | c `elem` "AEIOU" = Left " ← Unexpected vowel." | isDigit c = Right (ord c - ord '0') | isAsciiUpper c = Right (ord c - ord 'A' + 10) main :: IO () main = mapM_ (putStrLn . ((<>) <*> checkSum)) [ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "BOYBKT", "B00030" ]
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) } } }
Transform the following Icon implementation into C, maintaining the same output and logic.
procedure main() every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"| "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030")) end procedure sedol(x) static w,c initial { every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 every c[!"AEIOU"] := &null w := [1,3,1,7,3,9] } if *(x := map(x,&lcase,&ucase)) = *w then { every (t :=0, i := 1 to *x) do t +:= \c[x[i]]*w[i] | fail return x || (10 - (t%10)) % 10 } end
#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 the same code in C# as shown below in Icon.
procedure main() every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"| "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030")) end procedure sedol(x) static w,c initial { every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 every c[!"AEIOU"] := &null w := [1,3,1,7,3,9] } if *(x := map(x,&lcase,&ucase)) = *w then { every (t :=0, i := 1 to *x) do t +:= \c[x[i]]*w[i] | fail return x || (10 - (t%10)) % 10 } end
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; }
Change the programming language of this snippet from Icon to C++ without modifying what it does.
procedure main() every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"| "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030")) end procedure sedol(x) static w,c initial { every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 every c[!"AEIOU"] := &null w := [1,3,1,7,3,9] } if *(x := map(x,&lcase,&ucase)) = *w then { every (t :=0, i := 1 to *x) do t +:= \c[x[i]]*w[i] | fail return x || (10 - (t%10)) % 10 } end
#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; }
Generate a Java translation of this Icon snippet without changing its computational steps.
procedure main() every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"| "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030")) end procedure sedol(x) static w,c initial { every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 every c[!"AEIOU"] := &null w := [1,3,1,7,3,9] } if *(x := map(x,&lcase,&ucase)) = *w then { every (t :=0, i := 1 to *x) do t +:= \c[x[i]]*w[i] | fail return x || (10 - (t%10)) % 10 } end
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 programming language of this snippet from Icon to Python without modifying what it does.
procedure main() every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"| "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030")) end procedure sedol(x) static w,c initial { every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 every c[!"AEIOU"] := &null w := [1,3,1,7,3,9] } if *(x := map(x,&lcase,&ucase)) = *w then { every (t :=0, i := 1 to *x) do t +:= \c[x[i]]*w[i] | fail return x || (10 - (t%10)) % 10 } end
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 Icon version.
procedure main() every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"| "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030")) end procedure sedol(x) static w,c initial { every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 every c[!"AEIOU"] := &null w := [1,3,1,7,3,9] } if *(x := map(x,&lcase,&ucase)) = *w then { every (t :=0, i := 1 to *x) do t +:= \c[x[i]]*w[i] | fail return x || (10 - (t%10)) % 10 } end
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 J snippet to C and keep its semantics consistent.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
#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; }
Rewrite this program in C# while keeping its functionality equivalent to the J version.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
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; }
Change the programming language of this snippet from J to C++ without modifying what it does.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
#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 J snippet to Java and keep its semantics consistent.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
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].*?"); } }
Transform the following J implementation into Python, maintaining the same output and logic.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
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 the same code in Go as shown below in J.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
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) } } }
Write the same algorithm in C as shown in this Julia implementation.
using Base.Test function appendchecksum(chars::AbstractString) if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end weights = [1, 3, 1, 7, 3, 9, 1] s = 0 for (w, c) in zip(weights, chars) s += w * parse(Int, c, 36) end return string(chars, (10 - s % 10) % 10) end tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] @testset "Checksums" begin for (t, c) in zip(tests, csums) @test appendchecksum(t) == c end end
#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 Julia function in C# with identical behavior.
using Base.Test function appendchecksum(chars::AbstractString) if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end weights = [1, 3, 1, 7, 3, 9, 1] s = 0 for (w, c) in zip(weights, chars) s += w * parse(Int, c, 36) end return string(chars, (10 - s % 10) % 10) end tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] @testset "Checksums" begin for (t, c) in zip(tests, csums) @test appendchecksum(t) == c end end
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; }
Ensure the translated C++ code behaves exactly like the original Julia snippet.
using Base.Test function appendchecksum(chars::AbstractString) if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end weights = [1, 3, 1, 7, 3, 9, 1] s = 0 for (w, c) in zip(weights, chars) s += w * parse(Int, c, 36) end return string(chars, (10 - s % 10) % 10) end tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] @testset "Checksums" begin for (t, c) in zip(tests, csums) @test appendchecksum(t) == c end end
#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; }
Port the following code from Julia to Java with equivalent syntax and logic.
using Base.Test function appendchecksum(chars::AbstractString) if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end weights = [1, 3, 1, 7, 3, 9, 1] s = 0 for (w, c) in zip(weights, chars) s += w * parse(Int, c, 36) end return string(chars, (10 - s % 10) % 10) end tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] @testset "Checksums" begin for (t, c) in zip(tests, csums) @test appendchecksum(t) == c end end
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].*?"); } }
Translate this program into Python but keep the logic exactly as in Julia.
using Base.Test function appendchecksum(chars::AbstractString) if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end weights = [1, 3, 1, 7, 3, 9, 1] s = 0 for (w, c) in zip(weights, chars) s += w * parse(Int, c, 36) end return string(chars, (10 - s % 10) % 10) end tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] @testset "Checksums" begin for (t, c) in zip(tests, csums) @test appendchecksum(t) == c end end
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)
Produce a functionally identical Go code for the snippet given in Julia.
using Base.Test function appendchecksum(chars::AbstractString) if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end weights = [1, 3, 1, 7, 3, 9, 1] s = 0 for (w, c) in zip(weights, chars) s += w * parse(Int, c, 36) end return string(chars, (10 - s % 10) % 10) end tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] @testset "Checksums" begin for (t, c) in zip(tests, csums) @test appendchecksum(t) == c end end
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 an equivalent C version of this Mathematica code.
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
#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 following code from Mathematica to C# with equivalent syntax and logic.
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
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; }
Keep all operations the same but rewrite the snippet in C++.
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
#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 Mathematica code snippet into Java without altering its behavior.
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
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 Mathematica version.
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
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 the same algorithm in Go as shown in this Mathematica implementation.
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
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) } } }
Please provide an equivalent version of this Nim code in C.
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7') const weight = [1, 3, 1, 7, 3, 9] proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0')) for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(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; }
Convert this Nim snippet to C# and keep its semantics consistent.
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7') const weight = [1, 3, 1, 7, 3, 9] proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0')) for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(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; }
Transform the following Nim implementation into C++, maintaining the same output and logic.
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7') const weight = [1, 3, 1, 7, 3, 9] proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0')) for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(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; }
Generate an equivalent Java version of this Nim code.
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7') const weight = [1, 3, 1, 7, 3, 9] proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0')) for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(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].*?"); } }
Can you help me rewrite this code in Python instead of Nim, keeping it the same logically?
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7') const weight = [1, 3, 1, 7, 3, 9] proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0')) for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(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)
Rewrite this program in Go while keeping its functionality equivalent to the Nim version.
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7') const weight = [1, 3, 1, 7, 3, 9] proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0')) for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(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) } } }
Write the same algorithm in C as shown in this OCaml implementation.
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false let sedolweight = [1;3;1;7;3;9] let explode s = s |> String.to_seq |> List.of_seq let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;; List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
#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 OCaml, keeping it the same logically?
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false let sedolweight = [1;3;1;7;3;9] let explode s = s |> String.to_seq |> List.of_seq let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;; List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
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; }
Ensure the translated C++ code behaves exactly like the original OCaml snippet.
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false let sedolweight = [1;3;1;7;3;9] let explode s = s |> String.to_seq |> List.of_seq let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;; List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
#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; }
Generate a Java translation of this OCaml snippet without changing its computational steps.
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false let sedolweight = [1;3;1;7;3;9] let explode s = s |> String.to_seq |> List.of_seq let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;; List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
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 functionally identical Python code for the snippet given in OCaml.
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false let sedolweight = [1;3;1;7;3;9] let explode s = s |> String.to_seq |> List.of_seq let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;; List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
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 this OCaml block to Go, preserving its control flow and logic.
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false let sedolweight = [1;3;1;7;3;9] let explode s = s |> String.to_seq |> List.of_seq let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;; List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
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) } } }
Produce a functionally identical C code for the snippet given in Pascal.
program Sedols(output); function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end; function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end; const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030'); var seforl: string; i: integer; begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
#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; }
Rewrite the snippet below in C# so it works the same as the original Pascal code.
program Sedols(output); function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end; function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end; const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030'); var seforl: string; i: integer; begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
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; }
Port the following code from Pascal to C++ with equivalent syntax and logic.
program Sedols(output); function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end; function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end; const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030'); var seforl: string; i: integer; begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
#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 Pascal block to Java, preserving its control flow and logic.
program Sedols(output); function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end; function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end; const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030'); var seforl: string; i: integer; begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
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].*?"); } }
Generate an equivalent Python version of this Pascal code.
program Sedols(output); function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end; function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end; const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030'); var seforl: string; i: integer; begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
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)
Translate the given Pascal code snippet into Go without altering its behavior.
program Sedols(output); function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end; function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end; const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030'); var seforl: string; i: integer; begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
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) } } }
Rewrite the snippet below in C so it works the same as the original Perl code.
use List::Util qw(sum); use POSIX qw(strtol); sub zip :prototype(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedan :prototype($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
#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; }
Keep all operations the same but rewrite the snippet in C#.
use List::Util qw(sum); use POSIX qw(strtol); sub zip :prototype(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedan :prototype($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
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 an equivalent C++ version of this Perl code.
use List::Util qw(sum); use POSIX qw(strtol); sub zip :prototype(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedan :prototype($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
#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; }
Produce a functionally identical Java code for the snippet given in Perl.
use List::Util qw(sum); use POSIX qw(strtol); sub zip :prototype(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedan :prototype($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
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 Perl code.
use List::Util qw(sum); use POSIX qw(strtol); sub zip :prototype(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedan :prototype($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
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 Perl to Go, ensuring the logic remains intact.
use List::Util qw(sum); use POSIX qw(strtol); sub zip :prototype(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedan :prototype($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
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 PowerShell snippet to C and keep its semantics consistent.
function Add-SEDOLCheckDigit { Param ( [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )] [parameter ( Mandatory = $True ) ] [string] $SixDigitSEDOL ) $SEDOL = [string[]][char[]]$SixDigitSEDOL $Weight = @( 1, 3, 1, 7, 3, 9 ) $Characters = "0123456789abcdefghijklmnopqrstuvwxyz" $CheckSum = 0 0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] } $CheckDigit = ( 10 - $CheckSum % 10 ) % 10 return ( $SixDigitSEDOL + $CheckDigit ) } $List = @( "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ) ForEach ( $PartialSEDOL in $List ) { Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL }
#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 following code from PowerShell to C# with equivalent syntax and logic.
function Add-SEDOLCheckDigit { Param ( [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )] [parameter ( Mandatory = $True ) ] [string] $SixDigitSEDOL ) $SEDOL = [string[]][char[]]$SixDigitSEDOL $Weight = @( 1, 3, 1, 7, 3, 9 ) $Characters = "0123456789abcdefghijklmnopqrstuvwxyz" $CheckSum = 0 0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] } $CheckDigit = ( 10 - $CheckSum % 10 ) % 10 return ( $SixDigitSEDOL + $CheckDigit ) } $List = @( "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ) ForEach ( $PartialSEDOL in $List ) { Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL }
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; }
Keep all operations the same but rewrite the snippet in C++.
function Add-SEDOLCheckDigit { Param ( [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )] [parameter ( Mandatory = $True ) ] [string] $SixDigitSEDOL ) $SEDOL = [string[]][char[]]$SixDigitSEDOL $Weight = @( 1, 3, 1, 7, 3, 9 ) $Characters = "0123456789abcdefghijklmnopqrstuvwxyz" $CheckSum = 0 0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] } $CheckDigit = ( 10 - $CheckSum % 10 ) % 10 return ( $SixDigitSEDOL + $CheckDigit ) } $List = @( "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ) ForEach ( $PartialSEDOL in $List ) { Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL }
#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; }
Port the following code from PowerShell to Java with equivalent syntax and logic.
function Add-SEDOLCheckDigit { Param ( [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )] [parameter ( Mandatory = $True ) ] [string] $SixDigitSEDOL ) $SEDOL = [string[]][char[]]$SixDigitSEDOL $Weight = @( 1, 3, 1, 7, 3, 9 ) $Characters = "0123456789abcdefghijklmnopqrstuvwxyz" $CheckSum = 0 0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] } $CheckDigit = ( 10 - $CheckSum % 10 ) % 10 return ( $SixDigitSEDOL + $CheckDigit ) } $List = @( "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ) ForEach ( $PartialSEDOL in $List ) { Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL }
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].*?"); } }