WeixiangYan/CodeTransOcean huggingface dataset:
Task: Remove duplicate elements





Java: module RetainUniqueValues
    {
    @Inject Console console;
    void run()
        {
        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];
        array = array.distinct().toArray();
        console.print($"result={array}");
        }
    }




VB: Option Explicit

Sub Main()
Dim myArr() As Variant, i As Long

    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))

    For i = LBound(myArr) To UBound(myArr)
        Debug.Print myArr(i)
    Next
End Sub

Private Function Remove_Duplicate(Arr As Variant) As Variant()
Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long

    ReDim Temp(UBound(Arr))
    For i = LBound(Arr) To UBound(Arr)
        On Error Resume Next
        myColl.Add CStr(Arr(i)), CStr(Arr(i))
        If Err.Number > 0 Then
            On Error GoTo 0
        Else
            Temp(cpt) = Arr(i)
            cpt = cpt + 1
        End If
    Next i
    ReDim Preserve Temp(cpt - 1)
    Remove_Duplicate = Temp
End Function
Task: Look-and-say sequence





Java: public static String lookandsay(String number){
	StringBuilder result= new StringBuilder();

	char repeat= number.charAt(0);
	number= number.substring(1) + " ";
	int times= 1;

	for(char actual: number.toCharArray()){
		if(actual != repeat){
			result.append(times + "" + repeat);
			times= 1;
			repeat= actual;
		}else{
			times+= 1;
		}
	}
	return result.toString();
}




VB: function looksay( n )
	dim i
	dim accum
	dim res
	dim c
	res = vbnullstring
	do
		if n = vbnullstring then exit do
		accum = 0
		c = left( n,1 )
		do while left( n, 1 ) = c
			accum = accum + 1
			n = mid(n,2)
		loop
		if accum > 0 then 
			res = res & accum & c
		end if
	loop
	looksay = res
end function
Task: Stack





Java: import java.util.Stack;

public class StackTest {
    public static void main( final String[] args ) {
        final Stack<String> stack = new Stack<String>();

        System.out.println( "New stack empty? " + stack.empty() );

        stack.push( "There can be only one" );
        System.out.println( "Pushed stack empty? " + stack.empty() );
        System.out.println( "Popped single entry: " + stack.pop() );

        stack.push( "First" );
        stack.push( "Second" );
        System.out.println( "Popped entry should be second: " + stack.pop() );

        
        stack.pop();
        stack.pop();
    }
}




VB: 





Private myStack()
Private myStackHeight As Integer


Public Function Push(aValue)
  
  myStackHeight = myStackHeight + 1
  ReDim Preserve myStack(myStackHeight)
  myStack(myStackHeight) = aValue
End Function


Public Function Pop()
  
  If myStackHeight > 0 Then
    Pop = myStack(myStackHeight)
    myStackHeight = myStackHeight - 1
  Else
    MsgBox "Pop: stack is empty!"
  End If
End Function


Public Function IsEmpty() As Boolean
  IsEmpty = (myStackHeight = 0)
End Function


Property Get Size() As Integer
  Size = myStackHeight
End Property
Task: Totient function





Java: public class TotientFunction {

    public static void main(String[] args) {
        computePhi();
        System.out.println("Compute and display phi for the first 25 integers.");
        System.out.printf("n  Phi  IsPrime%n");
        for ( int n = 1 ; n <= 25 ; n++ ) {
            System.out.printf("%2d  %2d  %b%n", n, phi[n], (phi[n] == n-1));
        }
        for ( int i = 2 ; i < 8 ; i++ ) {
            int max = (int) Math.pow(10, i);
            System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max));
        }
    }
    
    private static int countPrimes(int min, int max) {
        int count = 0;
        for ( int i = min ; i <= max ; i++ ) {
            if ( phi[i] == i-1 ) {
                count++;
            }
        }
        return count;
    }

    private static final int max = 10000000;
    private static final int[] phi = new int[max+1];

    private static final void computePhi() {
        for ( int i = 1 ; i <= max ; i++ ) {
            phi[i] = i;
        }
        for ( int i = 2 ; i <= max ; i++ ) {
            if (phi[i] < i) continue;
            for ( int j = i ; j <= max ; j += i ) {
                phi[j] -= phi[j] / i;
            }
        }
    }

}




VB: Private Function totient(ByVal n As Long) As Long
    Dim tot As Long: tot = n
    Dim i As Long: i = 2
    Do While i * i <= n
        If n Mod i = 0 Then
            Do While True
                n = n \ i
                If n Mod i <> 0 Then Exit Do
            Loop
            tot = tot - tot \ i
        End If
        i = i + IIf(i = 2, 1, 2)
    Loop
    If n > 1 Then
        tot = tot - tot \ n
    End If
    totient = tot
End Function

Public Sub main()
    Debug.Print " n  phi   prime"
    Debug.Print " --------------"
    Dim count As Long
    Dim tot As Integer, n As Long
    For n = 1 To 25
        tot = totient(n)
        prime = (n - 1 = tot)
        count = count - prime
        Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@")
    Next n
    Debug.Print
    Debug.Print "Number of primes up to 25     = "; Format(count, "@@@@")
    For n = 26 To 100000
        count = count - (totient(n) = n - 1)
        Select Case n
            Case 100, 1000, 10000, 100000
                Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@")
            Case Else
        End Select
    Next n
End Sub
Task: Conditional structures





Java: if (s == 'Hello World') {
    foo();
} else if (s == 'Bye World') {
    bar();
} else {
    deusEx();
}




VB: Sub C_S_If()
Dim A$, B$

    A = "Hello"
    B = "World"
    
    If A = B Then Debug.Print A & " = " & B
    
    If A = B Then
        Debug.Print A & " = " & B
    Else
        Debug.Print A & " and " & B & " are differents."
    End If
    
    If A = B Then
        Debug.Print A & " = " & B
    Else: Debug.Print A & " and " & B & " are differents."
    End If
    
    If A = B Then Debug.Print A & " = " & B _
    Else Debug.Print A & " and " & B & " are differents."    
    
    If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
    If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
Task: Sort using a custom comparator





Java: import java.util.Comparator;
import java.util.Arrays;

public class Test {
  public static void main(String[] args) {
    String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};

    Arrays.sort(strings, new Comparator<String>() {
      public int compare(String s1, String s2) {
        int c = s2.length() - s1.length();
        if (c == 0)
          c = s1.compareToIgnoreCase(s2);
        return c;
      }
    });

    for (String s: strings)
      System.out.print(s + " ");
  }
}




VB: Imports System

Module Sorting_Using_a_Custom_Comparator
    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer
        Dim result As Integer
        result = y.Length - x.Length
        If result = 0 Then
            result = String.Compare(x, y, True)
        End If
        Return result
    End Function

    Sub Main()
        Dim strings As String() = {"test", "Zoom", "strings", "a"}

        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
    End Sub
End Module
Task: Animation





Java: import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class Rotate {

    private static class State {
        private final String text = "Hello World! ";
        private int startIndex = 0;
        private boolean rotateRight = true;
    }

    public static void main(String[] args) {
        State state = new State();

        JLabel label = new JLabel(state.text);
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent event) {
                state.rotateRight = !state.rotateRight;
            }
        });

        TimerTask task = new TimerTask() {
            public void run() {
                int delta = state.rotateRight ? 1 : -1;
                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
                label.setText(rotate(state.text, state.startIndex));
            }
        };
        Timer timer = new Timer(false);
        timer.schedule(task, 0, 500);

        JFrame rot = new JFrame();
        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        rot.add(label);
        rot.pack();
        rot.setLocationRelativeTo(null);
        rot.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                timer.cancel();
            }
        });
        rot.setVisible(true);
    }

    private static String rotate(String text, int startIdx) {
        char[] rotated = new char[text.length()];
        for (int i = 0; i < text.length(); i++) {
            rotated[i] = text.charAt((i + startIdx) % text.length());
        }
        return String.valueOf(rotated);
    }
}




VB: VERSION 5.00
Begin VB.Form Form1
   Begin VB.Timer Timer1
      Interval = 250
   End
   Begin VB.Label Label1
      AutoSize = -1  
      Caption  = "Hello World! "
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False


Private goRight As Boolean

Private Sub Label1_Click()
    goRight = Not goRight
End Sub

Private Sub Timer1_Timer()
    If goRight Then
        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)
    Else
        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)
    End If
    Label1.Caption = x
End Sub
Task: List comprehensions





Java: 
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
    static void main(String... args){
        System.out.println(run(20));
    }

    static List<List<Integer>> run(int n){
        return
            
            
            range(1, n).mapToObj(
                x -> range(x, n).mapToObj(
                    y -> range(y, n).mapToObj(
                        z -> new Integer[]{x, y, z}
                    )
                )
            )
                .flatMap(identity())
                .flatMap(identity())
                
                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
                
                .map(Arrays::asList)
                
                .collect(toList())
        ;
    }
}




VB: Module ListComp
    Sub Main()
        Dim ts = From a In Enumerable.Range(1, 20) _
                 From b In Enumerable.Range(a, 21 - a) _
                 From c In Enumerable.Range(b, 21 - b) _
                 Where a * a + b * b = c * c _
                 Select New With { a, b, c }
        
        For Each t In ts
            System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
        Next
    End Sub
End Module
Task: Sorting algorithms_Selection sort





Java: public static void sort(int[] nums){
	for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
		int smallest = Integer.MAX_VALUE;
		int smallestAt = currentPlace+1;
		for(int check = currentPlace; check<nums.length;check++){
			if(nums[check]<smallest){
				smallestAt = check;
				smallest = nums[check];
			}
		}
		int temp = nums[currentPlace];
		nums[currentPlace] = nums[smallestAt];
		nums[smallestAt] = temp;
	}
}




VB: Function Selection_Sort(s)
	arr = Split(s,",")
	For i = 0 To UBound(arr)
		For j = i To UBound(arr)
			temp = arr(i)
			If arr(j) < arr(i) Then
				arr(i) = arr(j)
				arr(j) = temp
			End If
		Next
	Next
	Selection_Sort = (Join(arr,","))
End Function

WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
Task: Apply a callback to an array





Java: public class ArrayCallback7 {

    interface IntConsumer {
        void run(int x);
    }

    interface IntToInt {
        int run(int x);
    }

    static void forEach(int[] arr, IntConsumer consumer) {
        for (int i : arr) {
            consumer.run(i);
        }
    }

    static void update(int[] arr, IntToInt mapper) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = mapper.run(arr[i]);
        }
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        forEach(numbers, new IntConsumer() {
            public void run(int x) {
                System.out.println(x);
            }
        });

        update(numbers, new IntToInt() {
            @Override
            public int run(int x) {
                return x * x;
            }
        });

        forEach(numbers, new IntConsumer() {
            public void run(int x) {
                System.out.println(x);
            }
        });
    }
}




VB: Option Explicit

Sub Main()
Dim arr, i
    
    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    
    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
    
    
    Debug.Print Join(arr, ", ")
End Sub

Private Function Fibonacci(N) As Variant
    If N <= 1 Then
        Fibonacci = N
    Else
        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
    End If
End Function
Task: Case-sensitivity of identifiers





Java: String dog = "Benjamin"; 
String Dog = "Samba";    
String DOG = "Bernie";   
@Inject Console console;
console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");




VB: Public Sub case_sensitivity()
    
    
    
    Dim DOG As String
    DOG = "Benjamin"
    DOG = "Samba"
    DOG = "Bernie"
    Debug.Print "There is just one dog named " & DOG
End Sub
Task: Loops_Downward for





Java: for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}




VB: For i = 10 To 0 Step -1
   Debug.Print i
Next i
Task: Write entire file





Java: import java.io.*;

public class Test {

    public static void main(String[] args) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
            bw.write("abc");
        }
    }
}




VB: Option Explicit

Const strName As String = "MyFileText.txt"
Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _
           "The reverse of Read entire file—for when you want to update or " & vbCrLf & _
           "create a file which you would read in its entirety all at once."

Sub Main()
Dim Nb As Integer

Nb = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb
    Print #1, Text
Close #Nb
End Sub
Task: Loops_For





Java: for (Integer i = 0; i < 5; i++) {
    String line = '';

    for (Integer j = 0; j < i; j++) {
        line += '*';
    }

    System.debug(line);
}

List<String> lines = new List<String> {
    '*',
    '**',
    '***',
    '****',
    '*****'
};

for (String line : lines) {
    System.debug(line);
}




VB: Public OutConsole As Scripting.TextStream
For i = 0 To 4
    For j = 0 To i
        OutConsole.Write "*"
    Next j 
    OutConsole.WriteLine
Next i
Task: Non-continuous subsequences





Java: public class NonContinuousSubsequences {

    public static void main(String args[]) {
        seqR("1234", "", 0, 0);
    }

    private static void seqR(String s, String c, int i, int added) {
        if (i == s.length()) {
            if (c.trim().length() > added)
                System.out.println(c);
        } else {
            seqR(s, c + s.charAt(i), i + 1, added + 1);
            seqR(s, c + ' ', i + 1, added);
        }
    }
}




VB: 

Function noncontsubseq(l)
    Dim  i, j, g, n, r, s, w, m
    Dim  a, b, c
    n = Ubound(l)
    For s = 0 To n-2
        For g = s+1 To n-1
            a = "["
            For i = s To g-1
                a = a & l(i) & ", "
            Next 
            For w = 1 To n-g
                r = n+1-g-w
                For i = 1 To 2^r-1 Step 2
                    b = a
                    For j = 0 To r-1
                        If i And 2^j Then b=b & l(g+w+j) & ", "
                    Next 
                    c = (Left(b, Len(b)-1))
                    WScript.Echo Left(c, Len(c)-1) & "]"
					m = m+1
                Next 
            Next 
        Next 
    Next 
    noncontsubseq = m
End Function 

list = Array("1", "2", "3", "4")
WScript.Echo "List: [" & Join(list, ", ") & "]"
nn = noncontsubseq(list)
WScript.Echo nn & " non-continuous subsequences"
Task: Twin primes





Java: import java.math.BigInteger;
import java.util.Scanner;

public class twinPrimes {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Search Size: ");
        BigInteger max = input.nextBigInteger();
        int counter = 0;
        for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
            }
        }
        System.out.println(counter + " twin prime pairs.");
    }
    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
                return false;
            }
        }
        return true;
    }
}




VB: Function IsPrime(x As Long) As Boolean
    Dim i As Long
    If x Mod 2 = 0 Then
        Exit Function
    Else
        For i = 3 To Int(Sqr(x)) Step 2
            If x Mod i = 0 Then Exit Function
        Next i
    End If
    IsPrime = True
End Function

Function TwinPrimePairs(max As Long) As Long
    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long
    p2 = True
    For i = 5 To max Step 2
        p1 = p2
        p2 = IsPrime(i)
        If p1 And p2 Then count = count + 1
    Next i
    TwinPrimePairs = count
End Function

Sub Test(x As Long)
    Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x))
End Sub

Sub Main()
    Test 10
    Test 100
    Test 1000
    Test 10000
    Test 100000
    Test 1000000
    Test 10000000
End Sub
Task: Roots of unity





Java: import java.util.Locale;

public class Test {

    public static void main(String[] a) {
        for (int n = 2; n < 6; n++)
            unity(n);
    }

    public static void unity(int n) {
        System.out.printf("%n%d: ", n);

        
        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {

            double real = Math.cos(angle); 

            if (Math.abs(real) < 1.0E-3)
                real = 0.0; 

            double imag = Math.sin(angle); 

            if (Math.abs(imag) < 1.0E-3)
                imag = 0.0;

            System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
        }
    }
}




VB: Public Sub roots_of_unity()
    For n = 2 To 9
        Debug.Print n; "th roots of 1:"
        For r00t = 0 To n - 1
            Debug.Print "   Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
                Sin(2 * WorksheetFunction.Pi() * r00t / n))
        Next r00t
        Debug.Print
    Next n
End Sub
Task: Sorting algorithms_Bubble sort





Java: public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
    boolean changed = false;
    do {
        changed = false;
        for (int a = 0; a < comparable.length - 1; a++) {
            if (comparable[a].compareTo(comparable[a + 1]) > 0) {
                E tmp = comparable[a];
                comparable[a] = comparable[a + 1];
                comparable[a + 1] = tmp;
                changed = true;
            }
        }
    } while (changed);
}




VB:   Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  sortable.Shuffle() 
  Dim swapped As Boolean
  Do
    Dim index, bound As Integer
    bound = sortable.Ubound

    While index < bound
      If sortable(index) > sortable(index + 1) Then
        Dim s As Integer = sortable(index)
        sortable.Remove(index)
        sortable.Insert(index + 1, s)
        swapped = True
      End If
      index = index + 1
    Wend
    
  Loop Until Not swapped
Task: File input_output





Java: import java.io.*;

public class FileIODemo {
  public static void main(String[] args) {
    try {
      FileInputStream in = new FileInputStream("input.txt");
      FileOutputStream out = new FileOutputStream("ouput.txt");
      int c;
      while ((c = in.read()) != -1) {
        out.write(c);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e){
      e.printStackTrace();
    }
  }
}




VB: Sub WriteToFile(input As FolderItem, output As FolderItem)
  Dim tis As TextInputStream
  Dim tos As TextOutputStream
  tis = tis.Open(input)
  tos = tos.Create(output)
  While Not tis.EOF
    tos.WriteLine(tis.ReadLine)
  Wend
  tis.Close
  tos.Close
End Sub
Task: Arithmetic_Integer





Java: import java.util.Scanner;

public class IntegerArithmetic {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        int sum = a + b;        
        int difference = a - b; 
        int product = a * b;    
        int division = a / b;   
        int remainder = a % b;  

        System.out.println("a + b = " + sum);
        System.out.println("a - b = " + difference);
        System.out.println("a * b = " + product);
        System.out.println("quotient of a / b = " + division);   
        System.out.println("remainder of a / b = " + remainder);   
    }
}




VB: START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
    PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
    GOTO START
END IF
PRINT
PRINT "             Sum = "; a + b
PRINT "      Difference = "; a - b
PRINT "         Product = "; a * b

PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT "       Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT "  Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END
Task: Matrix transposition





Java: import java.util.Arrays;
public class Transpose{
       public static void main(String[] args){
               double[][] m = {{1, 1, 1, 1},
                               {2, 4, 8, 16},
                               {3, 9, 27, 81},
                               {4, 16, 64, 256},
                               {5, 25, 125, 625}};
               double[][] ans = new double[m[0].length][m.length];
               for(int rows = 0; rows < m.length; rows++){
                       for(int cols = 0; cols < m[0].length; cols++){
                               ans[cols][rows] = m[rows][cols];
                       }
               }
               for(double[] i:ans){
                       System.out.println(Arrays.toString(i));
               }
       }
}




VB: Function transpose(m As Variant) As Variant
    transpose = WorksheetFunction.transpose(m)
End Function