WeixiangYan/CodeTransOcean huggingface dataset:
Task: Tokenize a string with escaping


C++: #include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

vector<string> tokenize(const string& input, char seperator, char escape) {
    vector<string> output;
    string token;

    bool inEsc = false;
    for (char ch : input) {
        if (inEsc) {
            inEsc = false;
        } else if (ch == escape) {
            inEsc = true;
            continue;
        } else if (ch == seperator) {
            output.push_back(token);
            token = "";
            continue;
        }
        token += ch;
    }
    if (inEsc)
        throw new invalid_argument("Invalid terminal escape");

    output.push_back(token);
    return output;
}

int main() {
    string sample = "one^|uno||three^^^^|four^^^|^cuatro|";

    cout << sample << endl;
    cout << '[';
    for (auto t : tokenize(sample, '|', '^')) {
        cout << '"' << t << "\", ";
    }
    cout << ']' << endl;

    return 0;
}







VB: Private Function tokenize(s As String, sep As String, esc As String) As Collection
    Dim ret As New Collection
    Dim this As String
    Dim skip As Boolean
     
    If Len(s) <> 0 Then
        For i = 1 To Len(s)
            si = Mid(s, i, 1)
            If skip Then
                this = this & si
                skip = False
            Else
                If si = esc Then
                    skip = True
                Else
                    If si = sep Then
                        ret.Add this
                        this = ""
                    Else
                        this = this & si
                    End If
                End If
            End If
        Next i
        ret.Add this
    End If
    Set tokenize = ret
End Function

Public Sub main()
    Dim out As Collection
    Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
    Dim outstring() As String
    ReDim outstring(out.Count - 1)
    For i = 0 To out.Count - 1
        outstring(i) = out(i + 1)
    Next i
    Debug.Print Join(outstring, ", ")
End Sub
Task: Hello world_Text


C++: #include <iostream>

int main () {
  std::cout << "Hello world!" << std::endl;
}







VB: Public Sub hello_world_text
    Debug.Print "Hello World!"
End Sub
Task: Primality by trial division


C++: #include <cmath>

bool is_prime(unsigned int n)
{
    if (n <= 1)
        return false;
    if (n == 2)
        return true;
    for (unsigned int i = 2; i <= sqrt(n); ++i)
        if (n % i == 0)
            return false;
    return true;
}







VB: Option Explicit

Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
   Do
      i = i + 1
      If IsPrime(i) Then
         t(count) = i
         count = count + 1
      End If
   Loop While count <= UBound(t)
   Debug.Print Join(t, ", ")
End Sub

Function IsPrime(Nb As Long) As Boolean
   If Nb = 2 Then
      IsPrime = True
   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
      Exit Function
   Else
      Dim i As Long
      For i = 3 To Sqr(Nb) Step 2
         If Nb Mod i = 0 Then Exit Function
      Next
      IsPrime = True
   End If
End Function
Task: Evaluate binomial coefficients


C++: double Factorial(double nValue)
   {
       double result = nValue;
       double result_next;
       double pc = nValue;
       do
       {
           result_next = result*(pc-1);
           result = result_next;
           pc--;
       }while(pc>2);
       nValue = result;
       return nValue;
   }

double binomialCoefficient(double n, double k)
   {
       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;
       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;
       return Factorial(n) /(Factorial(k)*Factorial((n - k)));
   }







VB: Function binomial(n,k)
	binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function

Function factorial(n)
	If n = 0 Then
		factorial = 1
	Else
		For i = n To 1 Step -1
			If i = n Then
				factorial = n
			Else
				factorial = factorial * i
			End If
		Next
	End If
End Function


WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3)
WScript.StdOut.WriteLine
Task: Collections


C++: int a[5]; 
a[0] = 1; 

int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; 

#include <string>
std::string strings[4]; 
                        







VB: Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"
Task: Bitwise operations



C#: static void bitwise(int a, int b)
        {
            Console.WriteLine("a and b is {0}", a & b);
            Console.WriteLine("a or b is {0}", a | b);
            Console.WriteLine("a xor b is {0}", a ^ b);
            Console.WriteLine("not a is {0}", ~a);
            Console.WriteLine("a lshift b is {0}", a << b);
            Console.WriteLine("a arshift b is {0}", a >> b); 
                                                             
            uint c = (uint)a;
            Console.WriteLine("c rshift b is {0}", c >> b); 
                                                            
            
        }




PHP: function bitwise($a, $b)
{
    function zerofill($a,$b) { 
        if($a>=0) return $a>>$b;
        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens
        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); 

    echo '$a AND $b: ' . $a & $b . '\n';
    echo '$a OR $b: ' . $a | $b . '\n';
    echo '$a XOR $b: ' . $a ^ $b . '\n';
    echo 'NOT $a: ' . ~$a . '\n';
    echo '$a << $b: ' . $a << $b . '\n'; // left shift  
    echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}
Task: Read a file line by line



C#: foreach (string readLine in File.ReadLines("FileName"))
  DoSomething(readLine);




PHP: <?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
    $line = rtrim($line);      // removes linebreaks and spaces at end
    echo strrev($line) . "\n"; // reverse line and upload it
}
Task: Non-decimal radices_Convert



C#: public static class BaseConverter {

    
    
    
    
    
    
    public static long stringToLong(string s, int b) {

        if ( b < 2 || b > 36 )
            throw new ArgumentException("Base must be between 2 and 36", "b");

        checked {

            int slen = s.Length;
            long result = 0;
            bool isNegative = false;

            for ( int i = 0; i < slen; i++ ) {

                char c = s[i];
                int num;

                if ( c == '-' ) {
                    
                    if ( i != 0 )
                        throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s");

                    isNegative = true;
                    continue;
                }

                if ( c > 0x2F && c < 0x3A )
                    
                    num = c - 0x30;
                else if ( c > 0x40 && c < 0x5B )
                    
                    
                    num = c - 0x37;  
                else if ( c > 0x60 && c < 0x7B )
                    
                    
                    num = c - 0x57;  
                else
                    throw new ArgumentException("The string contains an invalid character '" + c + "'", "s");

                

                if ( num >= b )
                    throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s");

                

                result *= b;
                result += num;

            }

            if ( isNegative )
                result = -result;

            return result;

        }

    }

    
    
    
    
    
    
    public static string longToString(long n, int b) {
        
        
        
        
        if ( b < 2 || b > 36 )
            throw new ArgumentException("Base must be between 2 and 36", "b");

        

        if ( b == 10 )
            return n.ToString();

        checked {
            long longBase = b;
            
            StringBuilder sb = new StringBuilder();
            
            if ( n < 0 ) {
                
                n = -n;
                sb.Append('-');
            }
            
            long div = 1;
            while ( n / div >= b )
                
                
                div *= b;
            
            while ( true ) {
                byte digit = (byte) (n / div);
            
                if ( digit < 10 )
                    
                    sb.Append((char) (digit + 0x30));
                else
                    
                    sb.Append((char) (digit + 0x57));  
            
                if ( div == 1 )
                    
                    break;
            
                n %= div;
                div /= b;
            }
            
            return sb.ToString();
        }

    }

}




PHP: base_convert("26", 10, 16); // returns "1a"
Task: Walk a directory_Recursively



C#: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace RosettaRecursiveDirectory
{
    class Program
    {
        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
        {
            var directoryStack = new Stack<DirectoryInfo>();
            directoryStack.Push(new DirectoryInfo(rootPath));
            while (directoryStack.Count > 0)
            {
                var dir = directoryStack.Pop();
                try
                {
                    foreach (var i in dir.GetDirectories())
                        directoryStack.Push(i);
                }
                catch (UnauthorizedAccessException) {
                    continue; 
                }
                foreach (var f in dir.GetFiles().Where(Pattern)) 
                    yield return f;
            }
        }
        static void Main(string[] args)
        {
            
            foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
                Console.WriteLine(file.FullName);
            Console.WriteLine("Done.");
        }
    }
}




PHP: function findFiles($dir = '.', $pattern = '/./'){
  $prefix = $dir . '/';
  $dir = dir($dir);
  while (false !== ($file = $dir->read())){
    if ($file === '.' || $file === '..') continue;
    $file = $prefix . $file;
    if (is_dir($file)) findFiles($file, $pattern);
    if (preg_match($pattern, $file)){
      echo $file . "\n";
    }
  }
}
findFiles('./foo', '/\.bar$/');
Task: CRC-32



C#:     
    
    
    public class Crc32
    {
        #region Constants
        
        
        
        private const UInt32 s_generator = 0xEDB88320;
        #endregion

        #region Constructors
        
        
        
        public Crc32()
        {
            
            m_checksumTable = Enumerable.Range(0, 256).Select(i =>
            {
                var tableEntry = (uint)i;
                for (var j = 0; j < 8; ++j)
                {
                    tableEntry = ((tableEntry & 1) != 0)
                        ? (s_generator ^ (tableEntry >> 1)) 
                        : (tableEntry >> 1);
                }
                return tableEntry;
            }).ToArray();
        }
        #endregion

        #region Methods
        
        
        
        
        
        public UInt32 Get<T>(IEnumerable<T> byteStream)
        {
            try
            {
                
                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => 
                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));
            }
            catch (FormatException e)
            {
                throw new CrcException("Could not read the stream out as bytes.", e);
            }
            catch (InvalidCastException e)
            {
                throw new CrcException("Could not read the stream out as bytes.", e);
            }
            catch (OverflowException e)
            {
                throw new CrcException("Could not read the stream out as bytes.", e);
            }
        }
        #endregion

        #region Fields
        
        
        
        private readonly UInt32[] m_checksumTable;

        #endregion
    }




PHP: printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
Task: Classes



C#: public class MyClass
{
    public MyClass()
    {
    }
    public void SomeMethod()
    {
    }
    private int _variable;
    public int Variable
    {
        get { return _variable; }
        set { _variable = value; }
    }
    public static void Main()
    {
        
        MyClass instance = new MyClass();
        
        instance.SomeMethod();
        
        instance.Variable = 99;
        
        System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
    }
}




PHP: class MyClass {
    public static $classVar;
    public $instanceVar; // can also initialize it here
    function __construct() {
        $this->instanceVar = 0;
    }
    function someMethod() {
        $this->instanceVar = 1;
        self::$classVar = 3;
    }
}
$myObj = new MyClass();
Task: Kaprekar numbers



C#: using System;
using System.Collections.Generic;

public class KaprekarNumbers {

    
    
    
    public static void Main() {
        int count = 0;

        foreach ( ulong i in _kaprekarGenerator(999999) ) {
            Console.WriteLine(i);
            count++;
        }

        Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
    }

    
    
    
    
    
    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {

        ulong next = 1;

        
        yield return next;

        for ( next = 2; next <= max; next++ ) {

            ulong square = next * next;

            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
                
                

                
                if ( square <= check )
                    break;

                
                
                
                
                

                ulong r = square % check;
                ulong q = (square - r) / check;

                if ( r != 0 && q + r == next ) {
                    yield return next;
                    break;
                }
            }

        }

    }

}




PHP: set_time_limit(300);

print_r(array_filter(range(1, 10000), 'isKaprekar'));
echo count(array_filter(range(1, 1000000), 'isKaprekar'));

function isKaprekar($n) {
    $a = $n * $n; 
    $b = bcmod("$a", "10");
    for ($d = 1, $t = 0; $a > 0; $d *= 10) {
        $b += $t * $d;
        if ($b > $n) break;
        $a = floor($a / 10);
        if ($b && $a + $b == $n) 
            return true;
        $t = bcmod("$a", "10");
    }
    return false;
}
Task: Anonymous recursion



C#: static int Fib(int n)
{
    if (n < 0) throw new ArgumentException("Must be non negativ", "n");
 
    Func<int, int> fib = null; 
    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;
    return fib(n);
}




PHP: <?php
function fib($n) {
    if ($n < 0)
        throw new Exception('Negative numbers not allowed');
    $f = function($n) { // This function must be called using call_user_func() only
        if ($n < 2)
            return 1;
        else {
            $g = debug_backtrace()[1]['args'][0];
            return call_user_func($g, $n-1) + call_user_func($g, $n-2);
        }
    };
    return call_user_func($f, $n);
}
echo fib(8), "\n";
?>
Task: Create a file



C#: using System;
using System.IO;

class Program {
    static void Main(string[] args) {
        File.Create("output.txt");
        File.Create(@"\output.txt");

        Directory.CreateDirectory("docs");
        Directory.CreateDirectory(@"\docs");
    }
}




PHP: <?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?>
Task: Delegates



C#: using System;

interface IOperable
{
    string Operate();
}

class Inoperable
{
}

class Operable : IOperable
{
    public string Operate()
    {
        return "Delegate implementation.";
    }
}

class Delegator : IOperable
{
    object Delegate;

    public string Operate()
    {
        var operable = Delegate as IOperable;
        return operable != null ? operable.Operate() : "Default implementation.";
    }

    static void Main()
    {
        var delegator = new Delegator();
        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
        {
            delegator.Delegate = @delegate;
            Console.WriteLine(delegator.Operate());
        }
    }
}




PHP: class Delegator {
  function __construct() {
    $this->delegate = NULL ;
  }
  function operation() {
    if(method_exists($this->delegate, "thing"))
      return $this->delegate->thing() ;
    return 'default implementation' ;
  }
}

class Delegate {
  function thing() {
    return 'Delegate Implementation' ;
  }
}

$a = new Delegator() ;
print "{$a->operation()}\n" ;

$a->delegate = 'A delegate may be any object' ;
print "{$a->operation()}\n" ;

$a->delegate = new Delegate() ;
print "{$a->operation()}\n" ;
Task: Command-line arguments



C#: using System;

namespace RosettaCode {
    class Program {
        static void Main(string[] args) {
            for (int i = 0; i < args.Length; i++)
                Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));
        }
    }
}




PHP: <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
Task: Array concatenation



C#: using System;

namespace RosettaCode
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3 };
            int[] b = { 4, 5, 6 };

            int[] c = new int[a.Length + b.Length];
            a.CopyTo(c, 0);
            b.CopyTo(c, a.Length);

            foreach(int n in c)
            {
                Console.WriteLine(n.ToString());
            }
        }
    }
}




PHP: $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
Task: User input_Text



C#: using System;

namespace C_Sharp_Console {

    class example {

        static void Main() {
            string word;
            int num;
            
            Console.Write("Enter an integer: ");
            num = Console.Read();
            Console.Write("Enter a String: ");
            word = Console.ReadLine();
        }
    }
}




PHP: #!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);
Task: First-class functions



C#: using System;

class Program
{
    static void Main(string[] args)
    {
        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));

        var functionTuples = new[]
        {
            (forward: Math.Sin, backward: Math.Asin),
            (forward: Math.Cos, backward: Math.Acos),
            (forward: cube,     backward: croot)
        };

        foreach (var ft in functionTuples)
        {
            Console.WriteLine(ft.backward(ft.forward(0.5)));
        }
    }
}




PHP: $compose = function ($f, $g) {
    return function ($x) use ($f, $g) {
        return $f($g($x));
    };
};

$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });
$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });

for ($i = 0; $i < 3; $i++) {
    $f = $compose($inv[$i], $fn[$i]);
    echo $f(0.5), PHP_EOL;
}
Task: Proper divisors



C#: namespace RosettaCode.ProperDivisors
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal static class Program
    {
        private static IEnumerable<int> ProperDivisors(int number)
        {
            return
                Enumerable.Range(1, number / 2)
                    .Where(divisor => number % divisor == 0);
        }

        private static void Main()
        {
            foreach (var number in Enumerable.Range(1, 10))
            {
                Console.WriteLine("{0}: {{{1}}}", number,
                    string.Join(", ", ProperDivisors(number)));
            }

            var record = Enumerable.Range(1, 20000).Select(number => new
            {
                Number = number,
                Count = ProperDivisors(number).Count()
            }).OrderByDescending(currentRecord => currentRecord.Count).First();
            Console.WriteLine("{0}: {1}", record.Number, record.Count);
        }
    }
}




PHP: <?php
function ProperDivisors($n) {
  yield 1;
  $large_divisors = [];
  for ($i = 2; $i <= sqrt($n); $i++) {
    if ($n % $i == 0) {
      yield $i;
      if ($i*$i != $n) {
        $large_divisors[] = $n / $i;
      }
    }
  }
  foreach (array_reverse($large_divisors) as $i) {
    yield $i;
  }
}

assert([1, 2, 4, 5, 10, 20, 25, 50] ==
        iterator_to_array(ProperDivisors(100)));

foreach (range(1, 10) as $n) {
  echo "$n =>";
  foreach (ProperDivisors($n) as $divisor) {
    echo " $divisor";
  }
  echo "\n";
}

$divisorsCount = [];
for ($i = 1; $i < 20000; $i++) {
  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;
}
ksort($divisorsCount);

echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n";
echo "They have ", key($divisorsCount), " divisors.\n";
Task: Regular expressions



C#: using System;
using System.Text.RegularExpressions;

class Program {
    static void Main(string[] args) {
        string str = "I am a string";

        if (new Regex("string$").IsMatch(str)) {
            Console.WriteLine("Ends with string.");
        }

        str = new Regex(" a ").Replace(str, " another ");
        Console.WriteLine(str);
    }
}




PHP: $string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
    echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Task: Hash from two arrays



C#: static class Program
{
    static void Main()
    {
        System.Collections.Hashtable h = new System.Collections.Hashtable();

        string[] keys = { "foo", "bar", "val" };
        string[] values = { "little", "miss", "muffet" };

        System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");

        for (int i = 0; i < keys.Length; i++)
        {
            h.Add(keys[i], values[i]);
        }
    }
}




PHP: $keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);
Task: Arrays



C#:  int[] numbers = new int[10];




PHP: $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];
Task: Sierpinski carpet



C#: using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static List<string> NextCarpet(List<string> carpet)
    {
        return carpet.Select(x => x + x + x)
                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
                     .Concat(carpet.Select(x => x + x + x)).ToList();
    }

    static List<string> SierpinskiCarpet(int n)
    {
        return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
    }

    static void Main(string[] args)
    {
        foreach (string s in SierpinskiCarpet(3))
            Console.WriteLine(s);
    }
}




PHP: <?php

function isSierpinskiCarpetPixelFilled($x, $y) {
    while (($x > 0) or ($y > 0)) {
        if (($x % 3 == 1) and ($y % 3 == 1)) {
            return false;
        }
        $x /= 3;
        $y /= 3;
    }
    return true;
}

function sierpinskiCarpet($order) {
    $size = pow(3, $order);
    for ($y = 0 ; $y < $size ; $y++) {
        for ($x = 0 ; $x < $size ; $x++) {
            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
        }
        echo PHP_EOL;
    }
}

for ($order = 0 ; $order <= 3 ; $order++) {
    echo 'N=', $order, PHP_EOL;
    sierpinskiCarpet($order);
    echo PHP_EOL;
}