Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Can you help me rewrite this code in Python instead of PowerShell, keeping it the same logically?
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 }
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 this program into Go but keep the logic exactly as in PowerShell.
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 }
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 Racket block to C, preserving its control flow and logic.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
#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 Racket implementation.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
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 Racket code in C++.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
Ensure the translated Java code behaves exactly like the original Racket snippet.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
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 Racket code.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
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)
Preserve the algorithm and functionality while converting the code from Racket to Go.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
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 COBOL to C, same semantics.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM 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; }
Produce a functionally identical C# code for the snippet given in COBOL.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM 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 COBOL implementation into C++, maintaining the same output and logic.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM 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; }
Convert this COBOL block to Java, preserving its control flow and logic.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM 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].*?"); } }
Ensure the translated Python code behaves exactly like the original COBOL snippet.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM 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)
Generate an equivalent Go version of this COBOL code.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM sedol.
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Convert this REXX snippet to C and keep its semantics consistent.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
Translate this program into C# but keep the logic exactly as in REXX.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
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 REXX code into C++ without altering its purpose.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
#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 REXX block to Java, preserving its control flow and logic.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Convert the following code from REXX to Python, ensuring the logic remains intact.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10) for sedol in .split(): print sedol + checksum(sedol)
Ensure the translated Go code behaves exactly like the original REXX snippet.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
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 Ruby implementation.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p 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 Ruby to C#, same semantics.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p 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; }
Rewrite the snippet below in C++ so it works the same as the original Ruby code.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p 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; }
Port the following code from Ruby to Java with equivalent syntax and logic.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p 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].*?"); } }
Write the same code in Python as shown below in Ruby.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p 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)
Translate this program into Go but keep the logic exactly as in Ruby.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p 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) } } }
Transform the following Scala implementation into C, maintaining the same output and logic.
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
#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 Scala, keeping it the same logically?
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 }; static int sedolChecksum(string sedol) { int len = sedol.Length; int sum = 0; if (len == 7) return (int)sedol[6]; if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) return -1; for (int i = 0; i < 6; i++) { if (Char.IsDigit(sedol[i])) sum += (((int)sedol[i] - 48) * sedol_weights[i]); else if (Char.IsLetter(sedol[i])) sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]); else return -1; } return (10 - (sum % 10)) % 10; }
Generate a C++ translation of this Scala snippet without changing its computational steps.
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
#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; }
Transform the following Scala implementation into Java, maintaining the same output and logic.
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
Ensure the translated Python code behaves exactly like the original Scala snippet.
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
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 language-to-language conversion: from Scala to Go, same semantics.
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 β00030 β0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s: %s\n", s, d) } else { fmt.Println(s + d) } } }
Preserve the algorithm and functionality while converting the code from Tcl to C.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $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; }
Change the following Tcl code into C# without altering its purpose.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $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; }
Generate a C++ translation of this Tcl snippet without changing its computational steps.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $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; }
Write the same code in Java as shown below in Tcl.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $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].*?"); } }
Convert the following code from Tcl to Python, ensuring the logic remains intact.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $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)
Port the following code from Tcl to Go with equivalent syntax and logic.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $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) } } }
Rewrite this program in PHP while keeping its functionality equivalent to the Rust version.
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
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";
Write a version of this Ada function in PHP with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_SEDOL is subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9; function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum : Integer := 0; Item : Integer; begin for Index in SEDOL'Range loop Item := Character'Pos (SEDOL (Index)); case Item is when Character'Pos ('0')..Character'Pos ('9') => Item := Item - Character'Pos ('0'); when Character'Pos ('B')..Character'Pos ('D') | Character'Pos ('F')..Character'Pos ('H') | Character'Pos ('J')..Character'Pos ('N') | Character'Pos ('P')..Character'Pos ('T') | Character'Pos ('V')..Character'Pos ('Z') => Item := Item - Character'Pos ('A') + 10; when others => raise Constraint_Error; end case; Sum := Sum + Item * Weight (Index); end loop; return SEDOL_Sum ((-Sum) mod 10); end Check; Test : constant array (1..10) of SEDOL_String := ( "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" ); begin for Index in Test'Range loop Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index)))); end loop; end Test_SEDOL;
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";
Generate a PHP translation of this Arturo snippet without changing its computational steps.
ord0: to :integer `0` ord7: to :integer `7` c2v: function [c][ ordC: to :integer c if? c < `A` -> return ordC - ord0 else -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ val: new 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 ] sedols: [ "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" ] loop sedols 'sed -> print [sed "->" sed ++ checksum sed]
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";
Can you help me rewrite this code in PHP instead of AutoHotKey, keeping it the same logically?
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB Loop, Parse, codes, `, output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n" Msgbox %output% SEDOL(code) { Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 If (StrLen(code) != 6) Return "Invalid length." StringCaseSense On Loop, Parse, code If A_LoopField is Number check_digit += A_LoopField * weight%A_Index% Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% Else Return "Invalid character." Return code . Mod(10-Mod(check_digit,10),10) }
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";
Ensure the translated PHP code behaves exactly like the original AWK snippet.
function ord(a) { return amap[a] } function sedol_checksum(sed) { sw[1] = 1; sw[2] = 3; sw[3] = 1 sw[4] = 7; sw[5] = 3; sw[6] = 9 sum = 0 for(i=1; i <= 6; i++) { c = substr(toupper(sed), i, 1) if ( c ~ /[[:digit:]]/ ) { sum += c*sw[i] } else { sum += (ord(c)-ord("A")+10)*sw[i] } } return (10 - (sum % 10)) % 10 } BEGIN { for(_i=0;_i<256;_i++) { astr = sprintf("%c", _i) amap[astr] = _i } } /[AEIOUaeiou]/ { print "'" $0 "' not a valid SEDOL code" next } { if ( (length($0) > 7) || (length($0) < 6) ) { print "'" $0 "' is too long or too short to be valid SEDOL" next } sedol = substr($0, 1, 6) sedolcheck = sedol_checksum(sedol) if ( length($0) == 7 ) { if ( (sedol sedolcheck) != $0 ) { print sedol sedolcheck " (original " $0 " has wrong check digit" } else { print sedol sedolcheck } } else { print sedol sedolcheck } }
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";
Change the following BBC_Basic code into PHP without altering its purpose.
PRINT FNsedol("710889") PRINT FNsedol("B0YBKJ") PRINT FNsedol("406566") PRINT FNsedol("B0YBLH") PRINT FNsedol("228276") PRINT FNsedol("B0YBKL") PRINT FNsedol("557910") PRINT FNsedol("B0YBKR") PRINT FNsedol("585284") PRINT FNsedol("B0YBKT") PRINT FNsedol("B00030") END DEF FNsedol(d$) LOCAL a%, i%, s%, weights%() DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9 FOR i% = 1 TO 6 a% = ASCMID$(d$,i%) - &30 s% += (a% + 7 * (a% > 9)) * weights%(i%) NEXT = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
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";
Rewrite this program in PHP while keeping its functionality equivalent to the Clojure version.
(defn sedols [xs] (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] convtonum (map #(Character/getNumericValue %) ys) check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] (str ys check)))] (map #(sedol %) xs)))
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";
Convert this Common_Lisp snippet to PHP and keep its semantics consistent.
(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6))) (assert (<= 0 start end (length sedol))) (assert (= (- end start) 6)) (loop :with checksum = 0 :for weight :in '(1 3 1 7 3 9) :for index :upfrom start :do (incf checksum (* weight (digit-char-p (char sedol index) 36))) :finally (let* ((posn (- 10 (mod checksum 10))) (head (subseq sedol start end)) (tail (digit-char posn))) (return (concatenate 'string head (list tail))))))
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";
Keep all operations the same but rewrite the snippet in PHP.
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); }
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";
Produce a functionally identical PHP code for the snippet given 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.
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";
Produce a functionally identical PHP code for the snippet given in Elixir.
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)
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";
Rewrite the snippet below in PHP so it works the same as the original F# code.
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
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";
Write the same code in PHP 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
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";
Rewrite the snippet below in PHP so it works the same as the original Forth code.
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
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";
Convert this Fortran snippet to PHP and keep its semantics consistent.
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";
Maintain the same structure and functionality when rewriting this code in PHP.
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) }
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";
Rewrite this program in PHP while keeping its functionality equivalent to the Haskell version.
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" ]
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";
Convert this Icon block to PHP, preserving its control flow 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
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";
Port the provided J code into PHP while preserving the original functionality.
sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:)
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";
Port the provided Julia code into PHP while preserving the original functionality.
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
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";
Rewrite the snippet below in PHP so it works the same as the original 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"}]
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";
Rewrite this program in PHP 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)
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";
Maintain the same structure and functionality when rewriting this code in PHP.
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" ]
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";
Can you help me rewrite this code in PHP instead of Pascal, keeping it the same logically?
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.
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";
Keep all operations the same but rewrite the snippet in PHP.
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"; }
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";
Write the same code in PHP as shown below in PowerShell.
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 }
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";
Ensure the translated PHP code behaves exactly like the original Racket snippet.
#lang racket (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS)) (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S) (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10))) (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S))) (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) (displayln (invalid-SEDOL? "B000301")) ) (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
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";
Rewrite the snippet below in PHP so it works the same as the original COBOL code.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status. DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol PIC X(6). WORKING-STORAGE SECTION. 01 sedol-file-status PIC XX. 88 sedol-file-ok VALUE "00". 01 digit-num PIC 9 COMP. 01 digit-weights-area VALUE "1317391". 03 digit-weights PIC 9 OCCURS 7 TIMES. 01 weighted-sum-parts-area. 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. 01 weighted-sum PIC 9(3) COMP. 01 check-digit PIC 9. PROCEDURE DIVISION. OPEN INPUT sedol-file PERFORM UNTIL NOT sedol-file-ok READ sedol-file AT END EXIT PERFORM END-READ MOVE FUNCTION UPPER-CASE(sedol) TO sedol PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 EVALUATE TRUE WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-IF COMPUTE weighted-sum-parts (digit-num) = (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + 10) * digit-weights (digit-num) WHEN sedol (digit-num:1) IS NUMERIC MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) BY digit-weights (digit-num) GIVING weighted-sum-parts (digit-num) WHEN OTHER DISPLAY "Invalid SEDOL: " sedol EXIT PERFORM CYCLE END-EVALUATE END-PERFORM INITIALIZE weighted-sum PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 ADD weighted-sum-parts (digit-num) TO weighted-sum END-PERFORM COMPUTE check-digit = FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) DISPLAY sedol check-digit END-PERFORM CLOSE sedol-file . END PROGRAM sedol.
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";
Port the following code from REXX to PHP with equivalent syntax and logic.
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphaDigs= '0123456789'@abcU allowable=space(translate(alphaDigs,,'AEIOU'),0) weights = 1317391 @.= arg @.1 . if @.1=='' then do @.1 = 710889 @.2 = 'B0YBKJ' @.3 = 406566 @.4 = 'B0YBLH' @.5 = 228276 @.6 = 'B0YBKL' @.7 = 557910 @.8 = 'B0YBKR' @.9 = 585284 @.10 = 'B0YBKT' @.11 = 'B00030' end do j=1 while @.j\==''; sedol=@.j L=length(sedol) if L<6 | L>7 then call ser "SEDOL isn't a valid length" if left(sedol,1)==9 then call swa 'SEDOL is reserved for end user allocation' _=verify(sedol, allowable) if _\==0 then call ser 'illegal character in SEDOL:' substr(sedol, _, 1) sum=0 do k=1 for 6 sum=sum + ( pos( substr(sedol, k, 1), alphaDigs) -1) * substr(weights, k, 1) end chkDig= (10-sum//10) // 10 r=right(sedol, 1) if L==7 & chkDig\==r then call ser sedol, 'invalid check digit:' r say 'SEDOL:' left(sedol,15) 'SEDOL + check digit ───► ' left(sedol,6)chkDig end exit sed: say; say 'SEDOL:' sedol; say; return ser: say; say '***error***' arg(1); call sed; exit 13 swa: say; say '***warning***' arg(1); say; return
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";
Generate an equivalent PHP version of this Ruby code.
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, "Invalid char c.to_i(36) end def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p e end end
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";
Write the same algorithm in PHP as shown in this Scala implementation.
val weights = listOf(1, 3, 1, 7, 3, 9, 1) fun sedol7(sedol6: String): String { if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") var sum = 0 for (i in 0..5) { val c = sedol6[i] val v = when (c) { in '0'..'9' -> c.toInt() - 48 in 'A'..'Z' -> c.toInt() - 55 else -> throw IllegalArgumentException("Argument string contains an invalid character") } sum += v * weights[i] } val check = (10 - (sum % 10)) % 10 return sedol6 + (check + 48).toChar() } fun main(args: Array<String>) { val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030") for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") }
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";
Port the provided Tcl code into PHP while preserving the original functionality.
namespace eval sedol { variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z} variable weight {1 3 1 7 3 9 1} proc checksum {alnum6} { variable chars variable weight set sum 0 set col 0 foreach char [split [string toupper [string range $alnum6 0 5]] ""] { if {[set idx [lsearch -exact $chars $char]] == -1} { error "invalid character: $char" } incr sum [expr {$idx * [lindex $weight $col]}] incr col } return [expr {(10 - ($sum % 10)) % 10}] } proc valid {alnum7} { expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]} } } proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } } set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT} set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7} foreach code $codes answer $answers { set sedol "${code}[sedol::checksum $code]" assert {$sedol eq $answer} "assertion failed: $sedol ne $answer" puts $sedol }
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";
Rewrite this program in Rust while keeping its functionality equivalent to the C version.
#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; }
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
Port the following code from C++ to Rust with equivalent syntax and logic.
#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; }
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
Produce a language-to-language conversion: from C# to Rust, same semantics.
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; }
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
Generate a Rust translation of this Java snippet without changing its computational steps.
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].*?"); } }
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
Rewrite the snippet below in Python so it works the same as the original Rust code.
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
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 following Go code into Rust without altering its purpose.
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) } } }
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len() != 6 { return None; } for c in input.chars() { if !valid_chars.contains(c) { return None; } } let mut result: u32 = input .chars() .map(|c| { if c.is_digit(10) { c as u32 - 48 } else { c as u32 - 55 } }) .zip(weights) .map(|(cnum, w)| w * cnum) .collect::<Vec<u32>>() .iter() .sum(); result = (10 - result % 10) % 10; Some(input.to_owned() + &result.to_string()) } fn main() { let inputs = vec![ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", ]; for input in inputs { println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap()); } }
Rewrite the snippet below in C# so it works the same as the original Ada code.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Please provide an equivalent version of this Ada code in C#.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Produce a functionally identical C code for the snippet given in Ada.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Translate this program into C but keep the logic exactly as in Ada.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Write a version of this Ada function in C++ with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Generate an equivalent C++ version of this Ada code.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Convert the following code from Ada to Go, ensuring the logic remains intact.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Port the provided Ada code into Go while preserving the original functionality.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Translate the given Ada code snippet into Java without altering its behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Translate the given Ada code snippet into Java without altering its behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Change the programming language of this snippet from Ada to Python without modifying what it does.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Produce a language-to-language conversion: from Ada to Python, same semantics.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Transform the following Ada implementation into VB, maintaining the same output and logic.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Transform the following Ada implementation into VB, maintaining the same output and logic.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Squeezable is procedure Squeeze (S : in String; C : in Character) is Res : String (1 .. S'Length); Len : Natural := 0; begin Put_Line ("Character to be squeezed: '" & C & "'"); Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image); for I in S'Range loop if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then Len := Len + 1; Res(Len) := S(I); end if; end loop; Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image); end Squeeze; begin Squeeze ("", ' '); Squeeze ("""If I were two-faced, would I be wearing this one?"" Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); Squeeze (" Squeeze (" Squeeze (" end Test_Squeezable;
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Generate a C translation of this AutoHotKey snippet without changing its computational steps.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Write a version of this AutoHotKey function in C with identical behavior.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Produce a functionally identical C# code for the snippet given in AutoHotKey.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Convert this AutoHotKey snippet to C# and keep its semantics consistent.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Port the provided AutoHotKey code into C++ while preserving the original functionality.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Generate an equivalent C++ version of this AutoHotKey code.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Rewrite this program in Java while keeping its functionality equivalent to the AutoHotKey version.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Convert this AutoHotKey snippet to Java and keep its semantics consistent.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Produce a language-to-language conversion: from AutoHotKey to Python, same semantics.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Change the following AutoHotKey code into Python without altering its purpose.
squeezable_string(str, char){ for i, ch in StrSplit(str){ if (ch <> prev) || !InStr(ch, char) res .= ch prev := ch } result := " (ltrim Original string:`t" StrLen(str) " characters`t«««" str "»»» Squeezable Character «««" char "»»» Resultant string:`t" StrLen(res) " characters`t«««" res "»»» )" return result }
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )