WeixiangYan/CodeTransOcean huggingface dataset:
Task: Use another language to call a function





Java: 
public class Query {
    public static boolean call(byte[] data, int[] length)
	throws java.io.UnsupportedEncodingException
    {
	String message = "Here am I";
	byte[] mb = message.getBytes("utf-8");
	if (length[0] < mb.length)
	    return false;
	length[0] = mb.length;
	System.arraycopy(mb, 0, data, 0, mb.length);
	return true;
    }
}





COBOL:        identification division.
       program-id. Query.

       environment division.
       configuration section.
       special-names.
           call-convention 0 is extern.

       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 query-result.
          05 filler value "Here I am".

       linkage section.
       01 data-reference.
          05 data-buffer   pic x occurs 0 to 8192 times
                                 depending on length-reference.
       01 length-reference usage binary-long.

       procedure division extern using data-reference length-reference.

       if length(query-result) less than or equal to length-reference
                           and length-reference less than 8193 then
           move query-result to data-reference
           move length(query-result) to length-reference
           move 1 to return-code
       end-if

       goback.
       end program Query.
Task: Colour bars_Display





Java: import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;

public class ColorFrame extends JFrame {
	public ColorFrame(int width, int height) {
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(width, height);
		this.setVisible(true);
	}

	@Override
	public void paint(Graphics g) {
		Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
				Color.pink, Color.CYAN, Color.yellow, Color.white };

		for (int i = 0; i < colors.length; i++) {
			g.setColor(colors[i]);
			g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
					/ colors.length, this.getHeight());
		}
	}

	public static void main(String args[]) {
		new ColorFrame(200, 200);
	}
}





COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. terminal-colour-bars.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  width           PIC 9(3).
       01  height          PIC 9(3).

       01  interval        PIC 9(3).

       01  colours-area.
           03  colour-values.
               05  FILLER  PIC 9 VALUE 0. 
               05  FILLER  PIC 9 VALUE 4. 
               05  FILLER  PIC 9 VALUE 2. 
               05  FILLER  PIC 9 VALUE 1. 
               05  FILLER  PIC 9 VALUE 5. 
               05  FILLER  PIC 9 VALUE 3. 
               05  FILLER  PIC 9 VALUE 6. 
               05  FILLER  PIC 9 VALUE 7. 

           03  colour-table REDEFINES colour-values.
               05  colours PIC 9 OCCURS 8 TIMES INDEXED BY colour-index.

       01  i               PIC 9(3).
       01  j               PIC 9(3).

       PROCEDURE DIVISION.
           ACCEPT width FROM COLUMNS
           ACCEPT height FROM LINES
           DIVIDE width BY 8 GIVING interval

           PERFORM VARYING i FROM 1 BY 1 UNTIL height < i
               PERFORM VARYING j FROM 1 BY 1 UNTIL width < j
                  COMPUTE colour-index = (j / interval) + 1
                  
                  IF 8 < colour-index
                      SET colour-index TO 8
                  END-IF

                  
                  
                  
                  DISPLAY SPACE AT LINE i COLUMN j
                      WITH BACKGROUND-COLOR colours (colour-index)
               END-PERFORM
           END-PERFORM

           ACCEPT i 

           GOBACK
           .
Task: Enforced immutability





Java: final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; 
immutableInt = 6; 





COBOL: ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
    SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9.
Task: Strange numbers





Java: import java.util.LinkedList;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StrangeNumbers {
    private static List<Integer> digits(int n) {
        var result = new LinkedList<Integer>();
        while (n > 0) {
            var rem = n % 10;
            result.addFirst(rem);
            n /= 10;
        }
        return result;
    }

    private static boolean isStrange(int n) {
        BiPredicate<Integer, Integer> test = (a, b) -> {
            var abs = Math.abs(a - b);
            return abs == 2 || abs == 3 || abs == 5 || abs == 7;
        };

        var xs = digits(n);
        for (int i = 1; i < xs.size(); i++) {
            if (test.negate().test(xs.get(i - 1), xs.get(i))) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        var xs = IntStream.rangeClosed(100, 500)
            .filter(StrangeNumbers::isStrange)
            .boxed()
            .collect(Collectors.toList());

        System.out.println("Strange numbers in range [100..500]");
        System.out.printf("(Total: %d)\n\n", xs.size());

        for (int i = 0; i < xs.size(); i++) {
            Integer x = xs.get(i);
            System.out.print(x);

            if ((i + 1) % 10 == 0) {
                System.out.println();
            } else {
                System.out.print(' ');
            }
        }
    }
}





COBOL:         IDENTIFICATION DIVISION.
        PROGRAM-ID. STRANGE-NUMBERS.
        
        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 COMPUTATION.
           02 NUM           PIC 999.
           02 DIGITS        REDEFINES NUM PIC 9 OCCURS 3 TIMES.
           02 DIGIT-PRIME   PIC 9.
              88 PRIME      VALUES 2 3 5 7.
           02 CUR-DIGIT     PIC 9.
        01 OUTPUT-FORMAT.
           02 N-OUT         PIC ZZ9.
        PROCEDURE DIVISION.
        BEGIN.
            PERFORM STRANGE-TEST
                VARYING NUM FROM 100 BY 1
                UNTIL NUM IS GREATER THAN 500.
            STOP RUN.
        
        STRANGE-TEST SECTION.
        BEGIN.
            SET CUR-DIGIT TO 1.
        STEP.   
            IF DIGITS(CUR-DIGIT) IS LESS THAN DIGITS(CUR-DIGIT + 1)
                SUBTRACT DIGITS(CUR-DIGIT + 1) FROM DIGITS(CUR-DIGIT) 
                    GIVING DIGIT-PRIME
            ELSE
                SUBTRACT DIGITS(CUR-DIGIT) FROM DIGITS(CUR-DIGIT + 1)
                    GIVING DIGIT-PRIME.
            IF PRIME NEXT SENTENCE ELSE GO TO DONE.
            ADD 1 TO CUR-DIGIT.
            IF CUR-DIGIT IS LESS THAN 3 GO TO STEP.
            MOVE NUM TO N-OUT.
            DISPLAY N-OUT.
        DONE. EXIT.
Task: Hofstadter Q sequence





Java: import java.util.HashMap;
import java.util.Map;

public class HofQ {
	private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{
		put(1, 1);
		put(2, 1);
	}};
	
	private static int[] nUses = new int[100001];
	
	public static int Q(int n){
		nUses[n]++;
		if(q.containsKey(n)){
			return q.get(n);
		}
		int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));
		q.put(n, ans);
		return ans;
	}
	
	public static void main(String[] args){
		for(int i = 1; i <= 10; i++){
			System.out.println("Q(" + i + ") = " + Q(i));
		}
		int last = 6;
		int count = 0;
		for(int i = 11; i <= 100000; i++){
			int curr = Q(i);
			if(curr < last) count++;
			last = curr;
			if(i == 1000) System.out.println("Q(1000) = " + curr);
		}
		System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times");
		
		
		int maxUses = 0, maxN = 0;
		for(int i = 1; i<nUses.length;i++){
			if(nUses[i] > maxUses){
				maxUses = nUses[i];
				maxN = i;
			}
		}
		System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls");
	}
}





COBOL:         IDENTIFICATION DIVISION.
        PROGRAM-ID. Q-SEQ.
        
        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 SEQ.
           02 Q         PIC 9(3) OCCURS 1000 TIMES.
           02 Q-TMP1    PIC 9(3).
           02 Q-TMP2    PIC 9(3).
           02 N         PIC 9(4).
        01 DISPLAYING.
           02 ITEM      PIC Z(3).
           02 IX        PIC Z(4).
            
        PROCEDURE DIVISION.
        MAIN-PROGRAM.    
            PERFORM GENERATE-SEQUENCE.
            PERFORM SHOW-ITEM
                VARYING N FROM 1 BY 1 
                UNTIL N IS GREATER THAN 10.
            SET N TO 1000.
            PERFORM SHOW-ITEM.
            STOP RUN.
        
        GENERATE-SEQUENCE.
            SET Q(1) TO 1.
            SET Q(2) TO 1.            
            PERFORM GENERATE-ITEM 
                VARYING N FROM 3 BY 1
                UNTIL N IS GREATER THAN 1000.
        
        GENERATE-ITEM.
            COMPUTE Q-TMP1 = N - Q(N - 1).
            COMPUTE Q-TMP2 = N - Q(N - 2).
            COMPUTE Q(N) = Q(Q-TMP1) + Q(Q-TMP2).
                        
        SHOW-ITEM.
            MOVE N TO IX.
            MOVE Q(N) TO ITEM.
            DISPLAY 'Q(' IX ') = ' ITEM.
Task: Count occurrences of a substring





Java: public class CountSubstring {
	public static int countSubstring(String subStr, String str){
		return (str.length() - str.replace(subStr, "").length()) / subStr.length();
	}
	
	public static void main(String[] args){
		System.out.println(countSubstring("th", "the three truths"));
		System.out.println(countSubstring("abab", "ababababab"));
		System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
	}
}





COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. testing.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  occurrences             PIC 99.

       PROCEDURE DIVISION.
           INSPECT "the three truths" TALLYING occurrences FOR ALL "th"
           DISPLAY occurrences

           MOVE 0 TO occurrences
           INSPECT "ababababab" TALLYING occurrences FOR ALL "abab"
           DISPLAY occurrences
           
           MOVE 0 TO occurrences
           INSPECT "abaabba*bbaba*bbab" TALLYING occurrences
               FOR ALL "a*b"
           DISPLAY occurrences

           GOBACK
           .
Task: Hickerson series of almost integers





Java: import java.math.*;

public class Hickerson {

    final static String LN2 = "0.693147180559945309417232121458";

    public static void main(String[] args) {
        for (int n = 1; n <= 17; n++)
            System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
    }

    static boolean almostInteger(int n) {
        BigDecimal a = new BigDecimal(LN2);
        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));

        long f = n;
        while (--n > 1)
            f *= n;

        BigDecimal b = new BigDecimal(f);
        b = b.divide(a, MathContext.DECIMAL128);

        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);

        return c.toString().matches("0|9");
    }
}





COBOL:        >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. hickerson-series.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
    FUNCTION ALL INTRINSIC
    .
DATA DIVISION.
WORKING-STORAGE SECTION.
01  n                                   PIC 99 COMP.

01  h                                   PIC Z(19)9.9(10).

01  First-Decimal-Digit-Pos             CONSTANT 22.

PROCEDURE DIVISION.
    PERFORM VARYING n FROM 0 BY 1 UNTIL n > 17
        COMPUTE h = FACTORIAL(n) / (2 * LOG(2) ** (n + 1))
        DISPLAY "h(" n ") = " h " which is " NO ADVANCING
        IF h (First-Decimal-Digit-Pos:1) = "0" OR "9"
            DISPLAY "an almost integer."
        ELSE
            DISPLAY "not an almost integer."
        END-IF
    END-PERFORM
    .
END PROGRAM hickerson-series.
Task: Sorting algorithms_Stooge sort





Java: import java.util.Arrays;

public class Stooge {
    public static void main(String[] args) {
        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};
        stoogeSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void stoogeSort(int[] L) {
        stoogeSort(L, 0, L.length - 1);
    }

    public static void stoogeSort(int[] L, int i, int j) {
        if (L[j] < L[i]) {
            int tmp = L[i];
            L[i] = L[j];
            L[j] = tmp;
        }
        if (j - i > 1) {
            int t = (j - i + 1) / 3;
            stoogeSort(L, i, j - t);
            stoogeSort(L, i + t, j);
            stoogeSort(L, i, j - t);
        }
    }
}





COBOL:        >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. stooge-sort-test.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  Arr-Len                             CONSTANT 7.

01  arr-area                            VALUE "00004001000020000005000230000000000".
    03  arr-elt                         PIC 9(5) OCCURS Arr-Len TIMES
                                        INDEXED BY arr-idx.

PROCEDURE DIVISION.
    DISPLAY "Unsorted: " NO ADVANCING
    PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx
        DISPLAY arr-elt (arr-idx) " " NO ADVANCING
    END-PERFORM
    DISPLAY SPACE

    CALL "stooge-sort" USING arr-area, OMITTED, OMITTED

    DISPLAY "Sorted:   " NO ADVANCING
    PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx
        DISPLAY arr-elt (arr-idx) " " NO ADVANCING
    END-PERFORM
    DISPLAY SPACE
    .
END PROGRAM stooge-sort-test.
    

IDENTIFICATION DIVISION.
PROGRAM-ID. stooge-sort RECURSIVE.

DATA DIVISION.
LOCAL-STORAGE SECTION.
01  Arr-Len                             CONSTANT 7.

01  i                                   PIC 99 COMP.
01  j                                   PIC 99 COMP.

01  temp                                PIC 9(5).

01  t                                   PIC 99 COMP.

LINKAGE SECTION.
01  arr-area.
    03  arr-elt                         PIC 9(5) OCCURS Arr-Len TIMES.

01  i-val                               PIC 99 COMP.
01  j-val                               PIC 99 COMP.

PROCEDURE DIVISION USING arr-area, OPTIONAL i-val, OPTIONAL j-val.
    IF i-val IS OMITTED
        MOVE 1 TO i
    ELSE
        MOVE i-val TO i
    END-IF
    IF j-val IS OMITTED
        MOVE Arr-Len TO j
    ELSE
        MOVE j-val TO j
    END-IF
    
    IF arr-elt (j) < arr-elt (i)
        MOVE arr-elt (i) TO temp
        MOVE arr-elt (j) TO arr-elt (i)
        MOVE temp TO arr-elt (j)
    END-IF   
    
    IF j - i + 1 >= 3
        COMPUTE t = (j - i + 1) / 3
        SUBTRACT t FROM j
        CALL "stooge-sort" USING arr-area, CONTENT i, j
        ADD t TO i, j
        CALL "stooge-sort" USING arr-area, CONTENT i, j
        SUBTRACT t FROM i, j
        CALL "stooge-sort" USING arr-area, CONTENT i, j
    END-IF
    .
END PROGRAM stooge-sort.
Task: McNuggets problem





Java: public class McNuggets {

    public static void main(String... args) {
        int[] SIZES = new int[] { 6, 9, 20 };
        int MAX_TOTAL = 100;
        
        int numSizes = SIZES.length;
        int[] counts = new int[numSizes];
        int maxFound = MAX_TOTAL + 1;
        boolean[] found = new boolean[maxFound];
        int numFound = 0;
        int total = 0;
        boolean advancedState = false;
        do {
            if (!found[total]) {
                found[total] = true;
                numFound++;
            }
            
            
            advancedState = false;
            for (int i = 0; i < numSizes; i++) {
                int curSize = SIZES[i];
                if ((total + curSize) > MAX_TOTAL) {
                    
                    total -= counts[i] * curSize;
                    counts[i] = 0;
                }
                else {
                    
                    counts[i]++;
                    total += curSize;
                    advancedState = true;
                    break;
                }
            }
            
        } while ((numFound < maxFound) && advancedState);
        
        if (numFound < maxFound) {
            
            for (int i = MAX_TOTAL; i >= 0; i--) {
                if (!found[i]) {
                    System.out.println("Largest non-McNugget number in the search space is " + i);
                    break;
                }
            }
        }
        else {
            System.out.println("All numbers in the search space are McNugget numbers");
        }
        
        return;
    }
}





COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID.  MCNUGGETS.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 NUGGETS.
          03 NUGGET-FLAGS     PIC X OCCURS 100 TIMES.
             88 IS-NUGGET     VALUE 'X'.

       01 A                   PIC 999.
       01 B                   PIC 999.
       01 C                   PIC 999.

       PROCEDURE DIVISION.
       BEGIN.
           MOVE SPACES TO NUGGETS.
           PERFORM A-LOOP VARYING A FROM 0 BY 6
               UNTIL A IS GREATER THAN 100.
           MOVE 100 TO A.

       FIND-LARGEST.
           IF IS-NUGGET(A), SUBTRACT 1 FROM A, GO TO FIND-LARGEST.
           DISPLAY 'Largest non-McNugget number: ', A.
           STOP RUN.
 
       A-LOOP.
           PERFORM B-LOOP VARYING B FROM A BY 9
               UNTIL B IS GREATER THAN 100.

       B-LOOP.
           PERFORM C-LOOP VARYING C FROM B BY 20
               UNTIL C IS GREATER THAN 100.
 
       C-LOOP.
           IF C IS NOT EQUAL TO ZERO, MOVE 'X' TO NUGGET-FLAGS(C).
Task: Idiomatically determine all the lowercase and uppercase letters





Java: import java.util.stream.IntStream;

public class Letters {
    public static void main(String[] args) throws Exception {
        System.out.print("Upper case: ");
        IntStream.rangeClosed(0, 0x10FFFF)
                 .filter(Character::isUpperCase)
                 .limit(72)
                 .forEach(n -> System.out.printf("%c", n));
        System.out.println("...");

        System.out.print("Lower case: ");
        IntStream.rangeClosed(0, 0x10FFFF)
                 .filter(Character::isLowerCase)
                 .limit(72)
                 .forEach(n -> System.out.printf("%c", n));
        System.out.println("...");
    }
}





COBOL:        identification division.
       program-id. determine.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 tx pic x.
       01 lower-8bit pic x(256).
       01 upper-8bit pic x(256).

      
      
      

       01 low-slide usage index.
       01 high-slide usage index.

       procedure division.
       determining.

      
       set low-slide to 0
       set high-slide to 0
       perform varying tally from 1 by 1 until tally > 256
           move char(tally) to tx
           if tx is alphabetic-lower then
               set low-slide up by 1
               move tx to lower-8bit(low-slide:1)
           end-if
           if tx is alphabetic-upper then
               set high-slide up by 1
               move tx to upper-8bit(high-slide:1)
           end-if
       end-perform
       if low-slide equal 0 then
           display "no lower case letters detected" upon syserr
       else
           display lower-8bit(1:low-slide)
       end-if
       if high-slide equal 0 then
           display "no upper case letters detected" upon syserr
       else
           display upper-8bit(1:high-slide)        
       end-if

      
      

      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      

       goback.
       end program determine.
Task: Hello world_Newbie





Java: public class HelloWorld {
    public static void main(String[] args) {
        
        System.out.println("Hello world!");
    }
}





COBOL: program-id. hello-world.

procedure division.
  display "Hello, World!"

  goback
  .
Task: Loops_Infinite





Java: while (true) {
   System.out.println("SPAM");
}





COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. Spam.

       PROCEDURE DIVISION.
           PERFORM UNTIL 1 <> 1
               DISPLAY "SPAM"
           END-PERFORM

           GOBACK
           .
Task: Function definition





Java: module MultiplyExample
    {
    static <Value extends Number> Value multiply(Value n1, Value n2)
        {
        return n1 * n2;
        }

    void run()
        {
        (Int i1, Int i2) = (7, 3);
        Int i3 = multiply(i1, i2);
        (Double d1, Double d2) = (2.7182818, 3.1415);
        Double d3 = multiply(d1, d2);
        @Inject Console console;
        console.print($"{i1}*{i2}={i3}, {d1}*{d2}={d3}");
        }
    }





COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. myTest.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  x   PIC 9(3) VALUE 3.
       01  y   PIC 9(3) VALUE 2.
       01  z   PIC 9(9).
       PROCEDURE DIVISION.
           CALL "myMultiply" USING 
               BY CONTENT x, BY CONTENT y, 
               BY REFERENCE z.
           DISPLAY z.
           STOP RUN.
       END PROGRAM myTest.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. myMultiply.
       DATA DIVISION.
       LINKAGE SECTION.
       01  x   PIC 9(3).
       01  y   PIC 9(3).
       01  z   PIC 9(9).
       PROCEDURE DIVISION USING x, y, z.
           MULTIPLY x BY y GIVING z.
           EXIT PROGRAM.
       END PROGRAM myMultiply.
Task: Create a file on magnetic tape





Java: import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class CreateFile {
    public static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file");
            Files.write(path, Collections.singletonList("Hello World!"));
        } else {
            Path path = Paths.get("/dev/tape");
            Files.write(path, Collections.singletonList("Hello World!"));
        }
    }
}





COBOL:        >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. MAKE-TAPE-FILE.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT TAPE-FILE
        ASSIGN "./TAPE.FILE"
        ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD TAPE-FILE.
01 TAPE-FILE-RECORD PIC X(51).

PROCEDURE DIVISION.
    OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE
    WRITE TAPE-FILE-RECORD 
        FROM "COBOL treats tape files and text files identically."
    END-WRITE
    STOP RUN.