Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate this program into C but keep the logic exactly as in COBOL. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Write the same code in C# as shown below in COBOL. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Translate this program into C# but keep the logic exactly as in COBOL. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Convert this COBOL snippet to C++ and keep its semantics consistent. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Change the following COBOL code into C++ without altering its purpose. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Produce a language-to-language conversion: from COBOL to Java, same semantics. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Write a version of this COBOL function in Java with identical behavior. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Change the programming language of this snippet from COBOL to Python without modifying what it does. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Rewrite the snippet below in Python so it works the same as the original COBOL code. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Convert the following code from COBOL to VB, ensuring the logic remains intact. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Translate this program into VB but keep the logic exactly as in COBOL. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Change the following COBOL code into Go without altering its purpose. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Write the same algorithm in Go as shown in this COBOL implementation. | ******************************************************************
* Author: Jay Moseley
* Date: November 10, 2019
* Purpose: Testing various subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. testSubs.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC
FUNCTION validISBN13.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 IX PIC S9(4) COMP.
01 TEST-ISBNS.
02 FILLER PIC X(14) VALUE '978-1734314502'.
02 FILLER PIC X(14) VALUE '978-1734314509'.
02 FILLER PIC X(14) VALUE '978-1788399081'.
02 FILLER PIC X(14) VALUE '978-1788399083'.
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS 4 TIMES
PIC X(14).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX > 4
DISPLAY TEST-ISBN (IX) ' ' WITH NO ADVANCING
END-DISPLAY
IF validISBN13(TEST-ISBN (IX)) = -1
DISPLAY '(bad)'
ELSE
DISPLAY '(good)'
END-IF
END-PERFORM.
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Date: May 19, 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number).
******************************************************************
IDENTIFICATION DIVISION.
FUNCTION-ID. validISBN13.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 PASSED-SIZE PIC S9(6) COMP-5.
01 IX PIC S9(4) COMP.
01 WORK-FIELDS.
02 WF-DIGIT PIC X.
02 WF-COUNT PIC 9(2).
88 WEIGHT-1 VALUE 1, 3, 5, 7, 9, 11, 13.
88 WEIGHT-3 VALUE 2, 4, 6, 8, 10, 12.
02 WF-SUM PIC S9(8) COMP.
LINKAGE SECTION.
01 PASSED-ISBN PIC X ANY LENGTH.
01 RETURN-VALUE PIC S9.
PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE.
CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-CALL.
COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM 1
BY 1
UNTIL IX GREATER THAN PASSED-SIZE
MOVE PASSED-ISBN (IX:1) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL(WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
(NUMVAL(WF-DIGIT) * 3)
END-COMPUTE
END-IF
END-IF
END-PERFORM.
IF MOD(WF-SUM, 10) = 0
MOVE +0 TO RETURN-VALUE
ELSE
MOVE -1 TO RETURN-VALUE
END-IF.
GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM EXIT POINT
END FUNCTION validISBN13.
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Produce a language-to-language conversion: from REXX to C, same semantics. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original REXX code. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Convert this REXX block to C#, preserving its control flow and logic. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Preserve the algorithm and functionality while converting the code from REXX to C#. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Convert this REXX block to C++, preserving its control flow and logic. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Rewrite the snippet below in Java so it works the same as the original REXX code. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Transform the following REXX implementation into Java, maintaining the same output and logic. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Convert the following code from REXX to Python, ensuring the logic remains intact. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Write the same algorithm in Python as shown in this REXX implementation. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Rewrite this program in VB while keeping its functionality equivalent to the REXX version. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Translate this program into VB but keep the logic exactly as in REXX. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Write the same algorithm in Go as shown in this REXX implementation. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
parse arg $
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't"
do j=1 for words($); y= word($,j)
x= space( translate(y, , '-'), 0)
L= length(x)
if L \== 13 then do; say @ISBN '13 characters: ' x; exit 13; end
if verify(x, 9876543210)\==0 then do; say @ISBN 'numeric: ' x; exit 10; end
sum= 0
do k=1 for L; #= substr(x, k, 1)
if \(k//2) then #= # * 3
sum= sum + #
end
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the Ruby version. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Convert the following code from Ruby to C#, ensuring the logic remains intact. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Ruby to C#. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Ruby code. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Produce a language-to-language conversion: from Ruby to C++, same semantics. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Convert this Ruby snippet to Java and keep its semantics consistent. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Write the same algorithm in Java as shown in this Ruby implementation. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Translate the given Ruby code snippet into Python without altering its behavior. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Produce a language-to-language conversion: from Ruby to Python, same semantics. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Write the same code in VB as shown below in Ruby. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Generate an equivalent VB version of this Ruby code. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Rewrite this program in Go while keeping its functionality equivalent to the Ruby version. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Generate an equivalent Go version of this Ruby code. | def validISBN13?(str)
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
end
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Please provide an equivalent version of this Swift code in C. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Please provide an equivalent version of this Swift code in C. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Can you help me rewrite this code in C# instead of Swift, keeping it the same logically? | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original Swift code. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Swift code. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Please provide an equivalent version of this Swift code in C++. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Produce a functionally identical Java code for the snippet given in Swift. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Rewrite the snippet below in Java so it works the same as the original Swift code. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Convert this Swift snippet to Python and keep its semantics consistent. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Preserve the algorithm and functionality while converting the code from Swift to Python. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Generate a VB translation of this Swift snippet without changing its computational steps. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Write a version of this Swift function in VB with identical behavior. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Maintain the same structure and functionality when rewriting this code in Go. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Convert the following code from Swift to Go, ensuring the logic remains intact. | func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
return false
}
let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
.reduce(0, +)
return sum % 10 == 0
}
let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Can you help me rewrite this code in C instead of Tcl, keeping it the same logically? | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Produce a language-to-language conversion: from Tcl to C, same semantics. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
|
Please provide an equivalent version of this Tcl code in C#. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Write a version of this Tcl function in C# with identical behavior. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
|
Produce a language-to-language conversion: from Tcl to C++, same semantics. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Transform the following Tcl implementation into C++, maintaining the same output and logic. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Tcl version. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Keep all operations the same but rewrite the snippet in Java. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
|
Convert this Tcl snippet to Python and keep its semantics consistent. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Please provide an equivalent version of this Tcl code in Python. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Generate an equivalent VB version of this Tcl code. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Port the following code from Tcl to VB with equivalent syntax and logic. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| arraybase 1
dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"}
for n = 1 to isbn[?]
sum = 0
isbnStr = isbn[n]
isbnStr = replace(isbnStr, "-", "")
isbnStr = replace(isbnStr, " ", "")
for m = 1 to length(isbnStr)
if m mod 2 = 0 then
num = 3 * int(mid(isbnStr, m, 1))
else
num = int(mid(isbnStr, m, 1))
end if
sum += num
next m
if sum mod 10 = 0 then
print isbn[n]; ": good"
else
print isbn[n]; ": bad"
end if
next n
|
Maintain the same structure and functionality when rewriting this code in Go. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Generate a Go translation of this Tcl snippet without changing its computational steps. | proc validISBN13 code {
regsub -all {\D} $code "" code ;
if {[string length $code] == 13} {
set sum 0
set fac 1
foreach digit [split $code ""] {
set sum [expr {$sum + $digit * $fac}]
set fac [expr {$fac == 1? 3: 1}]
}
if {$sum % 10 == 0} {return true}
}
return false
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} {puts $test:[validISBN13 $test]}
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
|
Transform the following C implementation into Rust, maintaining the same output and logic. | #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Convert this C snippet to Rust and keep its semantics consistent. | #include <stdio.h>
int check_isbn13(const char *isbn) {
int ch = *isbn, count = 0, sum = 0;
for ( ; ch != 0; ch = *++isbn, ++count) {
if (ch == ' ' || ch == '-') {
--count;
continue;
}
if (ch < '0' || ch > '9') {
return 0;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
}
if (count != 13) return 0;
return !(sum%10);
}
int main() {
int i;
const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"};
for (i = 0; i < 4; ++i) {
printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad");
}
return 0;
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Convert this C++ block to Rust, preserving its control flow and logic. | #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Convert this C# snippet to Rust and keep its semantics consistent. | using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Preserve the algorithm and functionality while converting the code from C# to Rust. | using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Write a version of this Java function in Rust with identical behavior. | public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Ensure the translated Python code behaves exactly like the original Rust snippet. | fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Write a version of this Rust function in VB with identical behavior. | fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
| Module Module1
Function CheckISBN13(code As String) As Boolean
code = code.Replace("-", "").Replace(" ", "")
If code.Length <> 13 Then
Return False
End If
Dim sum = 0
For Each i_d In code.Select(Function(digit, index) (index, digit))
Dim index = i_d.index
Dim digit = i_d.digit
If Char.IsDigit(digit) Then
sum += (Asc(digit) - Asc("0")) * If(index Mod 2 = 0, 1, 3)
Else
Return False
End If
Next
Return sum Mod 10 = 0
End Function
Sub Main()
Console.WriteLine(CheckISBN13("978-1734314502"))
Console.WriteLine(CheckISBN13("978-1734314509"))
Console.WriteLine(CheckISBN13("978-1788399081"))
Console.WriteLine(CheckISBN13("978-1788399083"))
End Sub
End Module
|
Convert this Go block to Rust, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Change the following Rust code into Python without altering its purpose. | fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = .strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")
|
Keep all operations the same but rewrite the snippet in Rust. | #include <iostream>
bool check_isbn13(std::string isbn) {
int count = 0;
int sum = 0;
for (auto ch : isbn) {
if (ch == ' ' || ch == '-') {
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
if (count & 1) {
sum += 3 * (ch - '0');
} else {
sum += ch - '0';
}
count++;
}
if (count != 13) {
return false;
}
return sum % 10 == 0;
}
int main() {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" };
for (auto isbn : isbns) {
std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n';
}
return 0;
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Can you help me rewrite this code in Rust instead of Java, keeping it the same logically? | public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = Integer.parseInt(in.substring(0,3));
if (pre!=978)return false;
String postStr = in.substring(4);
if (postStr.length()!=10)return false;
int post = Integer.parseInt(postStr);
int sum = 38;
for(int x = 0; x<10;x+=2)
sum += (postStr.charAt(x)-48)*3 + ((postStr.charAt(x+1)-48));
if(sum%10==0) return true;
return false;
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Rewrite the snippet below in Rust so it works the same as the original Go code. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
le := utf8.RuneCountInString(isbn)
if le != 13 {
return false
}
sum := int32(0)
for i, c := range isbn {
if c < '0' || c > '9' {
return false
}
if i%2 == 0 {
sum += c - '0'
} else {
sum += 3 * (c - '0')
}
}
return sum%10 == 0
}
func main() {
isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt.Printf("%s: %s\n", isbn, res)
}
}
| fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
|
Maintain the same structure and functionality when rewriting this code in VB. | fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([1, 3].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
| Module Module1
Function CheckISBN13(code As String) As Boolean
code = code.Replace("-", "").Replace(" ", "")
If code.Length <> 13 Then
Return False
End If
Dim sum = 0
For Each i_d In code.Select(Function(digit, index) (index, digit))
Dim index = i_d.index
Dim digit = i_d.digit
If Char.IsDigit(digit) Then
sum += (Asc(digit) - Asc("0")) * If(index Mod 2 = 0, 1, 3)
Else
Return False
End If
Next
Return sum Mod 10 = 0
End Function
Sub Main()
Console.WriteLine(CheckISBN13("978-1734314502"))
Console.WriteLine(CheckISBN13("978-1734314509"))
Console.WriteLine(CheckISBN13("978-1788399081"))
Console.WriteLine(CheckISBN13("978-1788399083"))
End Sub
End Module
|
Produce a functionally identical C# code for the snippet given in Ada. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Change the programming language of this snippet from Ada to C# without modifying what it does. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Ensure the translated C code behaves exactly like the original Ada snippet. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Transform the following Ada implementation into C, maintaining the same output and logic. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Ada snippet. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Port the provided Ada code into C++ while preserving the original functionality. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Ada version. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Write a version of this Ada function in Java with identical behavior. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Change the programming language of this snippet from Ada to Java without modifying what it does. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Change the programming language of this snippet from Ada to Python without modifying what it does. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Can you help me rewrite this code in Python instead of Ada, keeping it the same logically? | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Ensure the translated VB code behaves exactly like the original Ada snippet. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Write the same algorithm in VB as shown in this Ada implementation. | with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with GNAT.Calendar.Time_IO;
procedure Days_Between_Dates is
function Days_Between (Lower_Date : in Ada.Calendar.Time;
Higher_Date : in Ada.Calendar.Time) return Integer
is
use Ada.Calendar;
Diff : constant Duration := Higher_Date - Lower_Date;
begin
return Integer (Diff / Day_Duration'Last);
end Days_Between;
procedure Put_Days_Between (Lower_Date : in String;
Higher_Date : in String;
Comment : in String)
is
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use GNAT.Calendar.Time_IO;
Diff : constant Integer := Days_Between (Lower_Date => Value (Lower_Date),
Higher_Date => Value (Higher_Date));
begin
Put ("Days between " & Lower_Date & " and " & Higher_Date & " is ");
Put (Diff, Width => 5);
Put (" days
Put (Comment);
New_Line;
end Put_Days_Between;
begin
Put_Days_Between ("1995-11-21", "1995-11-21", "Identical dates");
Put_Days_Between ("2019-01-01", "2019-01-02", "Positive span");
Put_Days_Between ("2019-01-02", "2019-01-01", "Negative span");
Put_Days_Between ("2019-01-01", "2019-03-01", "Non-leap year");
Put_Days_Between ("2020-01-01", "2020-03-01", "Leap year");
Put_Days_Between ("1902-01-01", "1968-12-25", "Past");
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in C. | daysBetweenDates: function [startDate, endDate][
a: to :date.format: "dd/MM/yyyy" startDate
b: to :date.format: "dd/MM/yyyy" endDate
return abs b\days - a\days
]
print [
"days between the two dates:"
daysBetweenDates "01/01/2019" "19/10/2019"
]
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Change the following Arturo code into C without altering its purpose. | daysBetweenDates: function [startDate, endDate][
a: to :date.format: "dd/MM/yyyy" startDate
b: to :date.format: "dd/MM/yyyy" endDate
return abs b\days - a\days
]
print [
"days between the two dates:"
daysBetweenDates "01/01/2019" "19/10/2019"
]
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Port the following code from Arturo to C# with equivalent syntax and logic. | daysBetweenDates: function [startDate, endDate][
a: to :date.format: "dd/MM/yyyy" startDate
b: to :date.format: "dd/MM/yyyy" endDate
return abs b\days - a\days
]
print [
"days between the two dates:"
daysBetweenDates "01/01/2019" "19/10/2019"
]
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Change the programming language of this snippet from Arturo to C++ without modifying what it does. | daysBetweenDates: function [startDate, endDate][
a: to :date.format: "dd/MM/yyyy" startDate
b: to :date.format: "dd/MM/yyyy" endDate
return abs b\days - a\days
]
print [
"days between the two dates:"
daysBetweenDates "01/01/2019" "19/10/2019"
]
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.