WeixiangYan/CodeTransOcean huggingface dataset:
Task: Odd squarefree semiprimes


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

bool odd_square_free_semiprime(int n) {
    if ((n & 1) == 0)
        return false;
    int count = 0;
    for (int i = 3; i * i <= n; i += 2) {
        for (; n % i == 0; n /= i) {
            if (++count > 1)
                return false;
        }
    }
    return count == 1;
}

int main() {
    const int n = 1000;
    std::cout << "Odd square-free semiprimes < " << n << ":\n";
    int count = 0;
    for (int i = 1; i < n; i += 2) {
        if (odd_square_free_semiprime(i)) {
            ++count;
            std::cout << std::setw(4) << i;
            if (count % 20 == 0)
                std::cout << '\n';
        }
    }
    std::cout << "\nCount: " << count << '\n';
    return 0;
}


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

class Program { static void Main(string[] args) {
    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();
    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();
    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)
      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))
        Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : "");
    Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } }

class PG { public static IEnumerable<int> Primes(int lim) {
    var flags = new bool[lim + 1]; int j = 3;
    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
      if (!flags[j]) { yield return j;
        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Task: Polynomial synthetic division


C++: 

#include <iostream>
#include <vector>
#include <string>
#include <cmath>



std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
	std::string r = "";

	if (remainder) 
	{
		r = " r: " + std::to_string(polynomial.back());
		polynomial.pop_back();
	}

	std::string formatted = "";
	
	int degree = polynomial.size() - 1;
	int d = degree;

	for (int i : polynomial)
	{
		if (d < degree)
		{
			if (i >= 0) 
			{
				formatted += " + ";
			}
			else
			{
				formatted += " - ";
			}
		}

		formatted += std::to_string(abs(i));

		if (d > 1)
		{
			formatted += "x^" + std::to_string(d);
		}
		else if (d == 1)
		{
			formatted += "x";
		}

		d--;
	}

	return formatted;
}



std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
	std::vector<int> quotient;
	quotient = dividend;

	int normalizer = divisor[0];
	
	for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
	{
		quotient[i] /= normalizer;
		int coef = quotient[i];

		if (coef != 0) 
		{
			for (int j = 1; j < divisor.size(); j++)
			{
				quotient[i + j] += -divisor[j] * coef;
			}
        }

	}

	return quotient;
}



int main(int argc, char **argv) 
{
	std::vector<int> dividend{ 1, -12, 0, -42};
	std::vector<int> divisor{ 1, -3};

	std::cout << frmtPolynomial(dividend) << "\n";
	std::cout << frmtPolynomial(divisor) << "\n";

	std::vector<int> quotient = syntheticDiv(dividend, divisor);

	std::cout << frmtPolynomial(quotient, true) << "\n";

}


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

namespace SyntheticDivision
{
    class Program
    {
        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
        {
            List<int> output = dividend.ToList();
            int normalizer = divisor[0];

            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)
            {
                output[i] /= normalizer;

                int coef = output[i];
                if (coef != 0)
                {
                    for (int j = 1; j < divisor.Count(); j++)
                        output[i + j] += -divisor[j] * coef;
                }
            }

            int separator = output.Count() - (divisor.Count() - 1);

            return (
                output.GetRange(0, separator),
                output.GetRange(separator, output.Count() - separator)
            );
        }

        static void Main(string[] args)
        {
            List<int> N = new List<int>{ 1, -12, 0, -42 };
            List<int> D = new List<int> { 1, -3 };

            var (quotient, remainder) = extendedSyntheticDivision(N, D);
            Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" ,
                string.Join(",", N),
                string.Join(",", D),
                string.Join(",", quotient),
                string.Join(",", remainder)
            );
        }
    }
}
Task: Respond to an unknown method call


C++: class animal {
public:
  virtual void bark() 
  {
    throw "implement me: do not know how to bark";
  }
};

class elephant : public animal 
{
};

int main()
{
  elephant e;
  e.bark();  
}


C#: using System;
using System.Dynamic;

class Example : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        result = null;

        Console.WriteLine("This is {0}.", binder.Name);
        return true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        dynamic ex = new Example();

        ex.Foo();
        ex.Bar();
    }
}
Task: Inheritance_Single


C++: class Animal
{
  
};

class Dog: public Animal
{
  
};

class Lab: public Dog
{
  
};

class Collie: public Dog
{
  
};

class Cat: public Animal
{
  
};


C#: class Animal
{ 
   
  
}

class Dog : Animal
{ 
   
  
}

class Lab : Dog
{ 
   
  
}

class Collie : Dog
{ 
  
  
}

class Cat : Animal
{ 
  
  
}
Task: Polymorphism


C++: #include <cstdio>
#include <cstdlib>

class Point {
protected:
    int x, y;

public:
    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
    Point(const Point &p) : x(p.x), y(p.y) {}
    virtual ~Point() {}
    const Point& operator=(const Point &p) {
        if (this != &p) {
            x = p.x;
            y = p.y;
        }
        return *this;
    }
    int getX() { return x; }
    int getY() { return y; }
    void setX(int x0) { x = x0; }
    void setY(int y0) { y = y0; }
    virtual void print() { printf("Point\n"); }
};

class Circle: public Point {
private:
    int r;

public:
    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
    virtual ~Circle() {}
    const Circle& operator=(const Circle &c) {
        if (this != &c) {
            x = c.x;
            y = c.y;
            r = c.r;
        }
        return *this;
    }
    int getR() { return r; }
    void setR(int r0) { r = r0; }
    virtual void print() { printf("Circle\n"); }
};

int main() {
    Point *p = new Point();
    Point *c = new Circle();
    p->print();
    c->print();
    delete p;
    delete c;

    return EXIT_SUCCESS;
}


C#: using System;
class Point
{
  protected int x, y;
  public Point() : this(0) {}
  public Point(int x) : this(x,0) {}
  public Point(int x, int y) { this.x = x; this.y = y; }
  public int X { get { return x; } set { x = value; } }
  public int Y { get { return y; } set { y = value; } }
  public virtual void print() { System.Console.WriteLine("Point"); }
}

public class Circle : Point
{
  private int r;
  public Circle(Point p) : this(p,0) { }
  public Circle(Point p, int r) : base(p) { this.r = r; }
  public Circle() : this(0) { }
  public Circle(int x) : this(x,0) { }
  public Circle(int x, int y) : this(x,y,0) { }
  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }
  public int R { get { return r; } set { r = value; } }
  public override void print() { System.Console.WriteLine("Circle"); }
 
  public static void main(String args[])
  {
    Point p = new Point();
    Point c = new Circle();
    p.print();
    c.print();
  }
}
Task: Kosaraju


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

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    auto it = v.cbegin();
    auto end = v.cend();

    os << "[";
    if (it != end) {
        os << *it;
        it = std::next(it);
    }
    while (it != end) {
        os << ", " << *it;
        it = std::next(it);
    }
    return os << "]";
}

std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
    
    auto size = g.size();
    std::vector<bool> vis(size);           
    std::vector<int> l(size);              
    auto x = size;                         
    std::vector<std::vector<int>> t(size); 

    
    std::function<void(int)> visit;
    visit = [&](int u) {
        if (!vis[u]) {
            vis[u] = true;
            for (auto v : g[u]) {
                visit(v);
                t[v].push_back(u); 
            }
            l[--x] = u;
        }
    };

    
    for (int i = 0; i < g.size(); ++i) {
        visit(i);
    }
    std::vector<int> c(size); 

    
    std::function<void(int, int)> assign;
    assign = [&](int u, int root) {
        if (vis[u]) { 
            vis[u] = false;
            c[u] = root;
            for (auto v : t[u]) {
                assign(v, root);
            }
        }
    };

    
    for (auto u : l) {
        assign(u, u);
    }

    return c;
}

std::vector<std::vector<int>> g = {
    {1},
    {2},
    {0},
    {1, 2, 4},
    {3, 5},
    {2, 6},
    {5},
    {4, 6, 7},
};

int main() {
    using namespace std;

    cout << kosaraju(g) << endl;

    return 0;
}


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

class Node
{
	public enum Colors
	{
		Black, White, Gray
	}

	public Colors color { get; set; }
	public int N { get; }
	
	public Node(int n)
	{
		N = n;
		color = Colors.White;
	}
}

class Graph
{
	public HashSet<Node> V { get; }
	public Dictionary<Node, HashSet<Node>> Adj { get; }

	
	
	
	public void Kosaraju()
	{
		var L = new HashSet<Node>();

		Action<Node> Visit = null;
		Visit = (u) =>
		{
			if (u.color == Node.Colors.White)
			{
				u.color = Node.Colors.Gray;

				foreach (var v in Adj[u])
					Visit(v);

				L.Add(u);
			}
		};

		Action<Node, Node> Assign = null;
		Assign = (u, root) =>
		{
			if (u.color != Node.Colors.Black)
			{
				if (u == root)
					Console.Write("SCC: ");

				Console.Write(u.N + " ");
				u.color = Node.Colors.Black;

				foreach (var v in Adj[u])
					Assign(v, root);

				if (u == root)
					Console.WriteLine();
			}
		};

		foreach (var u in V)
			Visit(u);

		foreach (var u in L)
			Assign(u, u);
	}
}
Task: Entropy_Narcissist


C++: #include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

string readFile (string path) {
    string contents;
    string line;
    ifstream inFile(path);
    while (getline (inFile, line)) {
        contents.append(line);
        contents.append("\n");
    }
    inFile.close();
    return contents;
}

double entropy (string X) {
    const int MAXCHAR = 127;
    int N = X.length();
    int count[MAXCHAR];
    double count_i;
    char ch;
    double sum = 0.0;
    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
    for (int pos = 0; pos < N; pos++) {
        ch = X[pos];
        count[(int)ch]++;
    }
    for (int n_i = 0; n_i < MAXCHAR; n_i++) {
        count_i = count[n_i];
        if (count_i > 0) sum -= count_i / N * log2(count_i / N);
    }
    return sum;
}

int main () {
    cout<<entropy(readFile("entropy.cpp"));
    return 0;
}






Python: import math
from collections import Counter

def entropy(s):
    p, lns = Counter(s), float(len(s))
    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())

with open(__file__) as f:
    b=f.read()
    
print(entropy(b))
Task: DNS query


C++: #include <Rcpp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace Rcpp ;


CharacterVector getNameInfo(std::string fqdn) {

  struct addrinfo hints, *res, *res0;
	int error;
	char host[NI_MAXHOST];

  memset(&hints, 0, sizeof hints);
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
	if (error) { return(NA_STRING);	}

  int i = 0 ;
	for (res = res0; res; res = res->ai_next) {
  	error = getnameinfo(res->ai_addr, res->ai_addrlen,
		    host, sizeof host, NULL, 0, NI_NUMERICHOST);
		if (!error) { i++ ; }
	}

  CharacterVector results(i) ;

  i = 0;

  for (res = res0; res; res = res->ai_next) {
		error = getnameinfo(res->ai_addr, res->ai_addrlen,
		    host, sizeof host, NULL, 0, NI_NUMERICHOST);
		if (!error) { results[i++] = host ; }
	}

  freeaddrinfo(res0);

  return(results) ;

}






Python: >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194
Task: Seven-sided dice from five-sided dice


C++: template<typename F> class fivetoseven
{
public:
  fivetoseven(F f): d5(f), rem(0), max(1) {}
  int operator()();
private:
  F d5;
  int rem, max;
};

template<typename F>
 int fivetoseven<F>::operator()()
{
  while (rem/7 == max/7)
  {
    while (max < 7)
    {
      int rand5 = d5()-1;
      max *= 5;
      rem = 5*rem + rand5;
    }

    int groups = max / 7;
    if (rem >= 7*groups)
    {
      rem -= 7*groups;
      max -= 7*groups;
    }
  }

  int result = rem % 7;
  rem /= 7;
  max /= 7;
  return result+1;
}

int d5()
{
  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;
}

fivetoseven<int(*)()> d7(d5);

int main()
{
  srand(time(0));
  test_distribution(d5, 1000000, 0.001);
  test_distribution(d7, 1000000, 0.001);
}






Python: from random import randint

def dice5():
    return randint(1, 5)

def dice7():
    r = dice5() + dice5() * 5 - 6
    return (r % 7) + 1 if r < 21 else dice7()
Task: Solve the no connection puzzle


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

std::vector<std::pair<int, int>> connections = {
    {0, 2}, {0, 3}, {0, 4}, 
    {1, 3}, {1, 4}, {1, 5}, 
    {6, 2}, {6, 3}, {6, 4}, 
    {7, 3}, {7, 4}, {7, 5}, 
    {2, 3}, {3, 4}, {4, 5}, 
};
std::array<int, 8> pegs;
int num = 0;

void printSolution() {
    std::cout << "----- " << num++ << " -----\n";
    std::cout << "  "  << pegs[0] << ' ' << pegs[1] << '\n';
    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n';
    std::cout << "  "  << pegs[6] << ' ' << pegs[7] << '\n';
    std::cout << '\n';
}

bool valid() {
    for (size_t i = 0; i < connections.size(); i++) {
        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {
            return false;
        }
    }
    return true;
}

void solution(int le, int ri) {
    if (le == ri) {
        if (valid()) {
            printSolution();
        }
    } else {
        for (size_t i = le; i <= ri; i++) {
            std::swap(pegs[le], pegs[i]);
            solution(le + 1, ri);
            std::swap(pegs[le], pegs[i]);
        }
    }
}

int main() {
    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };
    solution(0, pegs.size() - 1);
    return 0;
}






Python: from __future__ import print_function
from itertools import permutations
from enum import Enum

A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')

connections = ((A, C), (A, D), (A, E),
               (B, D), (B, E), (B, F),
               (G, C), (G, D), (G, E),
               (H, D), (H, E), (H, F),
               (C, D), (D, E), (E, F))


def ok(conn, perm):
    
    this, that = (c.value - 1 for c in conn)
    return abs(perm[this] - perm[that]) != 1


def solve():
    return [perm for perm in permutations(range(1, 9))
            if all(ok(conn, perm) for conn in connections)]


if __name__ == '__main__':
    solutions = solve()
    print("A, B, C, D, E, F, G, H =", ', '.join(str(i) for i in solutions[0]))
Task: Create a two-dimensional array at runtime


C++: #include <iostream>

int main()
{
  
  int dim1, dim2;
  std::cin >> dim1 >> dim2;

  
  double* array_data = new double[dim1*dim2];
  double** array = new double*[dim1];
  for (int i = 0; i < dim1; ++i)
    array[i] = array_data + dim2*i;

  
  array[0][0] = 3.5;

  
  std::cout << array[0][0] << std::endl;

  
  delete[] array;
  delete[] array_data;

  return 0;
}






Python: width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
Task: Chinese remainder theorem


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

template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {
	_Ty b0 = b;
	_Ty x0 = 0;
	_Ty x1 = 1;

	if (b == 1) {
		return 1;
	}

	while (a > 1) {
		_Ty q = a / b;
		_Ty amb = a % b;
		a = b;
		b = amb;

		_Ty xqx = x1 - q * x0;
		x1 = x0;
		x0 = xqx;
	}

	if (x1 < 0) {
		x1 += b0;
	}

	return x1;
}

template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {
	_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });

	_Ty sm = 0;
	for (int i = 0; i < n.size(); i++) {
		_Ty p = prod / n[i];
		sm += a[i] * mulInv(p, n[i]) * p;
	}

	return sm % prod;
}

int main() {
	vector<int> n = { 3, 5, 7 };
	vector<int> a = { 2, 3, 2 };
 
	cout << chineseRemainder(n,a) << endl;
 
	return 0;
}






Python: 
def chinese_remainder(n, a):
    sum = 0
    prod = reduce(lambda a, b: a*b, n)

    for n_i, a_i in zip(n, a):
        p = prod / n_i
        sum += a_i * mul_inv(p, n_i) * p
    return sum % prod


def mul_inv(a, b):
    b0 = b
    x0, x1 = 0, 1
    if b == 1: return 1
    while a > 1:
        q = a / b
        a, b = b, a%b
        x0, x1 = x1 - q * x0, x0
    if x1 < 0: x1 += b0
    return x1

if __name__ == '__main__':
    n = [3, 5, 7]
    a = [2, 3, 2]
    print chinese_remainder(n, a)
Task: Pi


C++: #include <iostream>
#include <boost/multiprecision/cpp_int.hpp>

using namespace boost::multiprecision;

class Gospers
{
    cpp_int q, r, t, i, n;

public:    

    
    Gospers() : q{1}, r{0}, t{1}, i{1}
    {
        ++*this; 
    }

    
    Gospers& operator++()
    {
        n = (q*(27*i-12)+5*r) / (5*t);

        while(n != (q*(675*i-216)+125*r)/(125*t))
        {
            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
            q = i*(2*i-1)*q;
            t = 3*(3*i+1)*(3*i+2)*t;
            i++;

            n = (q*(27*i-12)+5*r) / (5*t);
        }

        q = 10*q;
        r = 10*r-10*n*t;

        return *this;
    }

    
    int operator*()
    {
        return (int)n;
    }
};

int main()
{
    Gospers g;

    std::cout << *g << ".";  

    for(;;) 
    {
        std::cout << *++g;  
    }
}






Python: def calcPi():
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    while True:
        if 4*q+r-t < n*t:
            yield n
            nr = 10*(r-n*t)
            n  = ((10*(3*q+r))//t)-10*n
            q  *= 10
            r  = nr
        else:
            nr = (2*q+r)*l
            nn = (q*(7*k)+2+(r*l))//(t*l)
            q  *= k
            t  *= l
            l  += 2
            k += 1
            n  = nn
            r  = nr

import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
    sys.stdout.write(str(d))
    i += 1
    if i == 40: print(""); i = 0
Task: Hofstadter Q sequence


C++: #include <iostream>
 
int main() {
   const int size = 100000;
   int hofstadters[size] = { 1, 1 };  
   for (int i = 3 ; i < size; i++) 
      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +
                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];
   std::cout << "The first 10 numbers are: ";
   for (int i = 0; i < 10; i++) 
      std::cout << hofstadters[ i ] << ' ';
   std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl;
   int less_than_preceding = 0;
   for (int i = 0; i < size - 1; i++)
      if (hofstadters[ i + 1 ] < hofstadters[ i ]) 
	     less_than_preceding++;
   std::cout << "In array of size: " << size << ", ";
   std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl;
   return 0;
}






Python: def q(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return q.seq[n]
    except IndexError:
        ans = q(n - q(n - 1)) + q(n - q(n - 2))
        q.seq.append(ans)
        return ans
q.seq = [None, 1, 1]

if __name__ == '__main__':
    first10 = [q(i) for i in range(1,11)]
    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
    print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
    assert q(1000) == 502, "Q(1000) value error"
    print("Q(1000) =", q(1000))
Task: Y combinator


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

template <typename F>
struct RecursiveFunc {
	std::function<F(RecursiveFunc)> o;
};

template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
	RecursiveFunc<std::function<B(A)>> r = {
		std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {
			return f(std::function<B(A)>([w](A x) {
				return w.o(w)(x);
			}));
		})
	};
	return r.o(r);
}

typedef std::function<int(int)> Func;
typedef std::function<Func(Func)> FuncFunc;
FuncFunc almost_fac = [](Func f) {
	return Func([f](int n) {
		if (n <= 1) return 1;
		return n * f(n - 1);
	});
};

FuncFunc almost_fib = [](Func f) {
	return Func([f](int n) {
	 	if (n <= 2) return 1;
		return  f(n - 1) + f(n - 2);
	});
};

int main() {
	auto fib = Y(almost_fib);
	auto fac = Y(almost_fac);
	std::cout << "fib(10) = " << fib(10) << std::endl;
	std::cout << "fac(10) = " << fac(10) << std::endl;
	return 0;
}






Python: >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Task: Return multiple values


C++: #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>

std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
   const auto maximum = std::max_element(numbers, numbers + num);
   const auto minimum = std::min_element(numbers, numbers + num);
   return std::make_tuple(*minimum, *maximum) ;
}

int main( ) {
   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
   int min{};
   int max{};
   std::tie(min, max) = minmax(numbers.data(), numbers.size());
   std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}






Python: def addsub(x, y):
  return x + y, x - y
Task: Van Eck sequence


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

class van_eck_generator {
public:
    int next() {
        int result = last_term;
        auto iter = last_pos.find(last_term);
        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
        last_pos[last_term] = index;
        last_term = next_term;
        ++index;
        return result;
    }
private:
    int index = 0;
    int last_term = 0;
    std::map<int, int> last_pos;
};

int main() {
    van_eck_generator gen;
    int i = 0;
    std::cout << "First 10 terms of the Van Eck sequence:\n";
    for (; i < 10; ++i)
        std::cout << gen.next() << ' ';
    for (; i < 990; ++i)
        gen.next();
    std::cout << "\nTerms 991 to 1000 of the sequence:\n";
    for (; i < 1000; ++i)
        std::cout << gen.next() << ' ';
    std::cout << '\n';
    return 0;
}






Python: def van_eck():
    n, seen, val = 0, {}, 0
    while True:
        yield val
        last = {val: n}
        val = n - seen.get(val, n)
        seen.update(last)
        n += 1

if __name__ == '__main__':
    print("Van Eck: first 10 terms:  ", list(islice(van_eck(), 10)))
    print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
Task: Loops_Continue


C++: for(int i = 1;i <= 10; i++){
   cout << i;
   if(i % 5 == 0){
      cout << endl;
      continue;
   }
   cout << ", ";
}






Python: for i in range(1, 11):
    if i % 5 == 0:
        print(i)
        continue
    print(i, end=', ')