WeixiangYan/CodeTransOcean huggingface dataset:
Task: Hofstadter Figure-Figure sequences


C++: #include <iomanip>
#include <iostream>
#include <set>
#include <vector>

using namespace std;

unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
    auto n = rlistSize > slistSize ? rlistSize : slistSize;
    auto rlist = new vector<unsigned> { 1, 3, 7 };
    auto slist = new vector<unsigned> { 2, 4, 5, 6 };
    auto list = rlistSize > 0 ? rlist : slist;
    auto target_size = rlistSize > 0 ? rlistSize : slistSize;

    while (list->size() > target_size) list->pop_back();

    while (list->size() < target_size)
    {
        auto lastIndex = rlist->size() - 1;
        auto lastr = (*rlist)[lastIndex];
        auto r = lastr + (*slist)[lastIndex];
        rlist->push_back(r);
        for (auto s = lastr + 1; s < r && list->size() < target_size;)
            slist->push_back(s++);
    }

    auto v = (*list)[n - 1];
    delete rlist;
    delete slist;
    return v;
}

ostream& operator<<(ostream& os, const set<unsigned>& s)
{
    cout << '(' << s.size() << "):";
    auto i = 0;
    for (auto c = s.begin(); c != s.end();)
    {
        if (i++ % 20 == 0) os << endl;
        os << setw(5) << *c++;
    }
    return os;
}

int main(int argc, const char* argv[])
{
    const auto v1 = atoi(argv[1]);
    const auto v2 = atoi(argv[2]);
    set<unsigned> r, s;
    for (auto n = 1; n <= v2; n++)
    {
        if (n <= v1)
            r.insert(hofstadter(n, 0));
        s.insert(hofstadter(0, n));
    }
    cout << "R" << r << endl;
    cout << "S" << s << endl;

    int m = max(*r.rbegin(), *s.rbegin());
    for (auto n = 1; n <= m; n++)
        if (r.count(n) == s.count(n))
            clog << "integer " << n << " either in both or neither set" << endl;

    return 0;
}


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

namespace HofstadterFigureFigure
{
	class HofstadterFigureFigure
	{
		readonly List<int> _r = new List<int>() {1};
		readonly List<int> _s = new List<int>();

		public IEnumerable<int> R()
		{
			int iR = 0;
			while (true)
			{
				if (iR >= _r.Count)
				{
					Advance();
				}
				yield return _r[iR++];
			}
		}

		public IEnumerable<int> S()
		{
			int iS = 0;
			while (true)
			{
				if (iS >= _s.Count)
				{
					Advance();
				}
				yield return _s[iS++];
			}
		}

		private void Advance()
		{
			int rCount = _r.Count;
			int oldR = _r[rCount - 1];
			int sVal;
			
			
			switch (rCount)
			{
				case 1:
					sVal = 2;
					break;
				case 2:
					sVal = 4;
					break;
				default:
					sVal = _s[rCount - 1];
					break;
			}
			_r.Add(_r[rCount - 1] + sVal);
			int newR = _r[rCount];
			for (int iS = oldR + 1; iS < newR; iS++)
			{
				_s.Add(iS);
			}
		}
	}

	class Program
	{
		static void Main()
		{
			var hff = new HofstadterFigureFigure();
			var rs = hff.R();
			var arr = rs.Take(40).ToList();

			foreach(var v in arr.Take(10))
			{
				Console.WriteLine("{0}", v);
			}

			var hs = new HashSet<int>(arr);
			hs.UnionWith(hff.S().Take(960));
			Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops!  Something's wrong!");
		}
	}
}
Task: Anonymous recursion


C++: double fib(double n)
{
  if(n < 0)
  {
    throw "Invalid argument passed to fib";
  }
  else
  {
    struct actual_fib
    {
        static double calc(double n)
        {
          if(n < 2)
          {
            return n;
          }
          else
          {
            return calc(n-1) + calc(n-2);
          }
        }
    };

    return actual_fib::calc(n);
  }
}


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);
}
Task: Create a file


C++: #include <direct.h>
#include <fstream>

int main() {
    std::fstream f("output.txt", std::ios::out);
    f.close();
    f.open("/output.txt", std::ios::out);
    f.close();

    _mkdir("docs");
    _mkdir("/docs");

    return 0;
}


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");
    }
}
Task: Delegates


C++: #include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>

using namespace std;
using namespace std::tr1;
using std::tr1::function;


class IDelegate
{
public:
    virtual ~IDelegate() {}
};


class IThing
{
public:
    virtual ~IThing() {}
    virtual std::string Thing() = 0;
};


class DelegateA : virtual public IDelegate
{
};
 

class DelegateB : public IThing, public IDelegate
{
    std::string Thing()
    {
        return "delegate implementation";
    }
};
 
class Delegator
{
public:
    std::string Operation()
    {
        if(Delegate) 
           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
            
            return pThing->Thing();
        
        return "default implementation";
    }
 
    shared_ptr<IDelegate> Delegate;
};
 
int main()
{
    shared_ptr<DelegateA> delegateA(new DelegateA());
    shared_ptr<DelegateB> delegateB(new DelegateB());
    Delegator delegator;
 
    
    std::cout << delegator.Operation() << std::endl;
 
    
    delegator.Delegate = delegateA;
    std::cout << delegator.Operation() << std::endl;
 
    
    delegator.Delegate = delegateB;
    std::cout << delegator.Operation() << std::endl;


}


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());
        }
    }
}
Task: Enforced immutability


C++: #include <iostream>

class MyOtherClass
{
public:
  const int m_x;
  MyOtherClass(const int initX = 0) : m_x(initX) { }

};

int main()
{
  MyOtherClass mocA, mocB(7);

  std::cout << mocA.m_x << std::endl; 
  std::cout << mocB.m_x << std::endl; 

  
  

  return 0;
}


C#: readonly DateTime now = DateTime.Now;
Task: Spiral matrix


C++: #include <vector>
#include <memory>	
#include <cmath>	
#include <iostream>
#include <iomanip>	

using namespace std;

typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;

auto_ptr< IntTable > getSpiralArray( int dimension )
{
	auto_ptr< IntTable > spiralArrayPtr( new IntTable(
		dimension, IntRow( dimension ) ) );

	int numConcentricSquares = static_cast< int >( ceil(
		static_cast< double >( dimension ) / 2.0 ) );

	int j;
	int sideLen = dimension;
	int currNum = 0;

	for ( int i = 0; i < numConcentricSquares; i++ )
	{
		
		for ( j = 0; j < sideLen; j++ )
			( *spiralArrayPtr )[ i ][ i + j ] = currNum++;

		
		for ( j = 1; j < sideLen; j++ )
			( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;

		
		for ( j = sideLen - 2; j > -1; j-- )
			( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;

		
		for ( j = sideLen - 2; j > 0; j-- )
			( *spiralArrayPtr )[ i + j ][ i ] = currNum++;

		sideLen -= 2;
	}

	return spiralArrayPtr;
}

void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
{
	size_t dimension = spiralArrayPtr->size();

	int fieldWidth = static_cast< int >( floor( log10(
		static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;

	size_t col;
	for ( size_t row = 0; row < dimension; row++ )
	{
		for ( col = 0; col < dimension; col++ )
			cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
		cout << endl;
	}
}

int main()
{
	printSpiralArray( getSpiralArray( 5 ) );
}


C#: public int[,] Spiral(int n) {
    int[,] result = new int[n, n];

    int pos = 0;
    int count = n;
    int value = -n;
    int sum = -1;

    do {
        value = -1 * value / n;
        for (int i = 0; i < count; i++) {
            sum += value;
            result[sum / n, sum % n] = pos++;
        }
        value *= n;
        count--;
        for (int i = 0; i < count; i++) {
            sum += value;
            result[sum / n, sum % n] = pos++;
        }
    } while (count > 0);

    return result;
}



public void PrintArray(int[,] array) {
    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;

    for (int i = 0; i < array.GetLength(0); i++) {
        for (int j = 0; j < array.GetLength(1); j++) {
            Console.Write(array[i, j].ToString().PadLeft(n, ' '));
        }
        Console.WriteLine();
    }
}
Task: Command-line arguments


C++: #include <iostream>

int main(int argc, char* argv[])
{
  std::cout << "This program is named " << argv[0] << std::endl;
  std::cout << "There are " << argc-1 << " arguments given." << std::endl;
  for (int i = 1; i < argc; ++i)
    std::cout << "the argument #" << i << " is " << argv[i] << std::endl;

  return 0;
}


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]));
        }
    }
}
Task: Array concatenation


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

int main()
{
  std::vector<int> a(3), b(4);
  a[0] = 11; a[1] = 12; a[2] = 13;
  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;

  a.insert(a.end(), b.begin(), b.end());

  for (int i = 0; i < a.size(); ++i)
    std::cout << "a[" << i << "] = " << a[i] << "\n";
}


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());
            }
        }
    }
}
Task: User input_Text


C++: #include <iostream>
#include <string>
using namespace std;

int main()
{
     
     
     long int integer_input;
     string string_input;
     cout << "Enter an integer:  ";
     cin >> integer_input;
     cout << "Enter a string:  ";
     cin >> string_input;
     return 0;
}


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();
        }
    }
}
Task: Cartesian product of two or more lists


C++: #include <iostream>
#include <vector>
#include <algorithm>

void print(const std::vector<std::vector<int>>& v) {
  std::cout << "{ ";
  for (const auto& p : v) {
    std::cout << "(";
    for (const auto& e : p) {
      std::cout << e << " ";
    }
    std::cout << ") ";
  }
  std::cout << "}" << std::endl;
}

auto product(const std::vector<std::vector<int>>& lists) {
  std::vector<std::vector<int>> result;
  if (std::find_if(std::begin(lists), std::end(lists), 
    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
    return result;
  }
  for (auto& e : lists[0]) {
    result.push_back({ e });
  }
  for (size_t i = 1; i < lists.size(); ++i) {
    std::vector<std::vector<int>> temp;
    for (auto& e : result) {
      for (auto f : lists[i]) {
        auto e_tmp = e;
        e_tmp.push_back(f);
        temp.push_back(e_tmp);
      }
    }
    result = temp;
  }
  return result;
}

int main() {
  std::vector<std::vector<int>> prods[] = {
    { { 1, 2 }, { 3, 4 } },
    { { 3, 4 }, { 1, 2} },
    { { 1, 2 }, { } },
    { { }, { 1, 2 } },
    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
    { { 1, 2, 3 }, { 30 }, { 500, 100 } },
    { { 1, 2, 3 }, { }, { 500, 100 } }
  };
  for (const auto& p : prods) {
    print(product(p));
  }
  std::cin.ignore();
  std::cin.get();
  return 0;
}


C#: using System;
public class Program
{
    public static void Main()
    {
        int[] empty = new int[0];
        int[] list1 = { 1, 2 };
        int[] list2 = { 3, 4 };
        int[] list3 = { 1776, 1789 };
        int[] list4 = { 7, 12 };
        int[] list5 = { 4, 14, 23 };
        int[] list6 = { 0, 1 };
        int[] list7 = { 1, 2, 3 };
        int[] list8 = { 30 };
        int[] list9 = { 500, 100 };
        
        foreach (var sequenceList in new [] {
            new [] { list1, list2 },
            new [] { list2, list1 },
            new [] { list1, empty },
            new [] { empty, list1 },
            new [] { list3, list4, list5, list6 },
            new [] { list7, list8, list9 },
            new [] { list7, empty, list9 }
        }) {
            var cart = sequenceList.CartesianProduct()
                .Select(tuple => $"({string.Join(", ", tuple)})");
            Console.WriteLine($"{{{string.Join(", ", cart)}}}");
        }
    }
}

public static class Extensions
{
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
        return sequences.Aggregate(
            emptyProduct,
            (accumulator, sequence) =>
            from acc in accumulator
            from item in sequence
            select acc.Concat(new [] { item }));
    }
}
Task: First-class functions


C++: #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
 
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;

typedef function<double(double)> FunType;

vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };

template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
    return [f,g](A x) { return f(g(x)); };
}

int main() {
    vector<FunType> composedFuns;
    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};

    transform(B.begin(), B.end(),
                A.begin(),
                back_inserter(composedFuns),
                compose<double, double, double>);

    for (auto num: exNums)
        for (auto fun: composedFuns)
            cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;

    return 0;
}


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)));
        }
    }
}
Task: Proper divisors


C++: #include <vector>
#include <iostream>
#include <algorithm>

std::vector<int> properDivisors ( int number ) {
   std::vector<int> divisors ;
   for ( int i = 1 ; i < number / 2 + 1 ; i++ )
      if ( number % i == 0 )
	 divisors.push_back( i ) ;
   return divisors ;
}

int main( ) {
   std::vector<int> divisors ;
   unsigned int maxdivisors = 0 ;
   int corresponding_number = 0 ;
   for ( int i = 1 ; i < 11 ; i++ ) {
      divisors =  properDivisors ( i ) ;
      std::cout << "Proper divisors of " << i << ":\n" ;
      for ( int number : divisors ) { 
	 std::cout << number << " " ;
      }
      std::cout << std::endl ;
      divisors.clear( ) ;
   }
   for ( int i = 11 ; i < 20001 ; i++ ) {
      divisors =  properDivisors ( i ) ;
      if ( divisors.size( ) > maxdivisors ) {
	 maxdivisors = divisors.size( ) ;
	 corresponding_number = i ;
      }
      divisors.clear( ) ;
   }

   std::cout << "Most divisors has " << corresponding_number <<
      " , it has " << maxdivisors << " divisors!\n" ; 
   return 0 ;
}


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);
        }
    }
}
Task: XML_Output


C++: #include <vector>
#include <utility>
#include <iostream>
#include <boost/algorithm/string.hpp>

std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;

int main( ) {
   std::vector<std::string> names , remarks ;
   names.push_back( "April" ) ;
   names.push_back( "Tam O'Shantor" ) ;
   names.push_back ( "Emily" ) ;
   remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ;
   remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ;
   remarks.push_back( "Short & shrift" ) ;
   std::cout << "This is in XML:\n" ;
   std::cout << create_xml( names , remarks ) << std::endl ;
   return 0 ;
}

std::string create_xml( std::vector<std::string> & names ,
      std::vector<std::string> & remarks ) {
   std::vector<std::pair<std::string , std::string> > entities ;
   entities.push_back( std::make_pair( "&" , "&amp;" ) ) ;
   entities.push_back( std::make_pair( "<" , "&lt;" ) ) ;
   entities.push_back( std::make_pair( ">" , "&gt;" ) ) ;
   std::string xmlstring ( "<CharacterRemarks>\n" ) ;
   std::vector<std::string>::iterator vsi = names.begin( ) ;
   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;
   for ( ; vsi != names.end( ) ; vsi++ ) {
      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
	 boost::replace_all ( *vsi , vs->first , vs->second ) ;
      }
   }
   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {
      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
	 boost::replace_all ( *vsi , vs->first , vs->second ) ;
      }
   }
   for ( int i = 0 ; i < names.size( ) ; i++ ) {
      xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">")
	 .append( remarks[ i ] ).append( "</Character>\n" ) ;
   }
   xmlstring.append( "</CharacterRemarks>" ) ;
   return xmlstring ;
}


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

class Program
{
    static string CreateXML(Dictionary<string, string> characterRemarks)
    {
        var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key)));
        var xml = new XElement("CharacterRemarks", remarks);
        return xml.ToString();
    }

    static void Main(string[] args)
    {
        var characterRemarks = new Dictionary<string, string>
        {
            { "April", "Bubbly: I'm > Tam and <= Emily" },
            { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" },
            { "Emily", "Short & shrift" }
        };

        string xml = CreateXML(characterRemarks);
        Console.WriteLine(xml);
    }
}
Task: Regular expressions


C++: #include <iostream>
#include <string>
#include <iterator>
#include <regex>

int main()
{
  std::regex re(".* string$");
  std::string s = "Hi, I am a string";

  
  if (std::regex_match(s, re))
    std::cout << "The string matches.\n";
  else
    std::cout << "Oops - not found?\n";

  
  std::regex re2(" a.*a");
  std::smatch match;
  if (std::regex_search(s, match, re2))
  {
    std::cout << "Matched " << match.length()
              << " characters starting at " << match.position() << ".\n";
    std::cout << "Matched character sequence: \""
              << match.str() << "\"\n";
  }
  else
  {
    std::cout << "Oops - not found?\n";
  }

  
  std::string dest_string;
  std::regex_replace(std::back_inserter(dest_string),
                       s.begin(), s.end(),
                       re2,
                       "'m now a changed");
  std::cout << dest_string << std::endl;
}


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);
    }
}
Task: Hash from two arrays


C++: #include <unordered_map>
#include <string>

int main()
{
  std::string keys[] = { "1", "2", "3" };
  std::string vals[] = { "a", "b", "c" };
 
  std::unordered_map<std::string, std::string> hash;
  for( int i = 0 ; i < 3 ; i++ )
     hash[ keys[i] ] = vals[i] ;
}


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]);
        }
    }
}