WeixiangYan/CodeTransOcean huggingface dataset:
Task: Pythagorean quadruples


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

constexpr int N = 2200;
constexpr int N2 = 2 * N * N;

int main() {
    using namespace std;

    vector<bool> found(N + 1);
    vector<bool> aabb(N2 + 1);

    int s = 3;

    for (int a = 1; a < N; ++a) {
        int aa = a * a;
        for (int b = 1; b < N; ++b) {
            aabb[aa + b * b] = true;
        }
    }

    for (int c = 1; c <= N; ++c) {
        int s1 = s;
        s += 2;
        int s2 = s;
        for (int d = c + 1; d <= N; ++d) {
            if (aabb[s1]) {
                found[d] = true;
            }
            s1 += s2;
            s2 += 2;
        }
    }

    cout << "The values of d <= " << N << " which can't be represented:" << endl;
    for (int d = 1; d <= N; ++d) {
        if (!found[d]) {
            cout << d << " ";
        }
    }
    cout << endl;

    return 0;
}






Python: def quad(top=2200):
    r = [False] * top
    ab = [False] * (top * 2)**2
    for a in range(1, top):
        for b in range(a, top):
            ab[a * a + b * b] = True
    s = 3
    for c in range(1, top):
        s1, s, s2 = s, s + 2, s + 2
        for d in range(c + 1, top):
            if ab[s1]:
                r[d] = True
            s1 += s2
            s2 += 2
    return [i for i, val in enumerate(r) if not val and i]
    
if __name__ == '__main__':
    n = 2200
    print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Task: Steady squares


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

bool steady(int n) {
    int mask = 1;
    for (int d = n; d != 0; d /= 10) 
        mask *= 10;
    return (n * n) % mask == n;
}
 
int main() {
    for (int i = 1; i < 10000; i++)
        if (steady(i)) printf("%4d^2 = %8d\n", i, i * i);
}






Python: print("working...")
print("Steady squares under 10.000 are:")
limit = 10000

for n in range(1,limit):
    nstr = str(n)
    nlen = len(nstr)
    square = str(pow(n,2))
    rn = square[-nlen:]
    if nstr == rn:
       print(str(n) + " " + str(square))

print("done...")
Task: Pseudo-random numbers_Middle-square method


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

using ulong = unsigned long;

class MiddleSquare {
private:
    ulong state;
    ulong div, mod;
public:
    MiddleSquare() = delete;
    MiddleSquare(ulong start, ulong length) {
        if (length % 2) throw std::invalid_argument("length must be even");
        div = mod = 1;
        for (ulong i=0; i<length/2; i++) div *= 10;
        for (ulong i=0; i<length; i++) mod *= 10;
        state = start % mod;
    }
    
    ulong next() { 
        return state = state * state / div % mod;
    }
};

int main() {
    MiddleSquare msq(675248, 6);
    for (int i=0; i<5; i++)
        std::cout << msq.next() << std::endl;
    return 0;
}






Python: seed = 675248
def random():
    global seed
    seed = int(str(seed ** 2).zfill(12)[3:9])
    return seed
for _ in range(5):
    print(random())
Task: Dice game probabilities


C++: #include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <map>


std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {
    std::map<uint32_t, uint32_t> result;
    for (uint32_t i = 1; i <= faces; ++i)
        result.emplace(i, 1);
    for (uint32_t d = 2; d <= dice; ++d) {
        std::map<uint32_t, uint32_t> tmp;
        for (const auto& p : result) {
            for (uint32_t i = 1; i <= faces; ++i)
                tmp[p.first + i] += p.second;
        }
        tmp.swap(result);
    }
    return result;
}

double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {
    auto totals1 = get_totals(dice1, faces1);
    auto totals2 = get_totals(dice2, faces2);
    double wins = 0;
    for (const auto& p1 : totals1) {
        for (const auto& p2 : totals2) {
            if (p2.first >= p1.first)
                break;
            wins += p1.second * p2.second;
        }
    }
    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);
    return wins/total;
}

int main() {
    std::cout << std::setprecision(10);
    std::cout << probability(9, 4, 6, 6) << '\n';
    std::cout << probability(5, 10, 6, 7) << '\n';
    return 0;
}






Python: from itertools import product

def gen_dict(n_faces, n_dice):
    counts = [0] * ((n_faces + 1) * n_dice)
    for t in product(range(1, n_faces + 1), repeat=n_dice):
        counts[sum(t)] += 1
    return counts, n_faces ** n_dice

def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
    c1, p1 = gen_dict(n_sides1, n_dice1)
    c2, p2 = gen_dict(n_sides2, n_dice2)
    p12 = float(p1 * p2)

    return sum(p[1] * q[1] / p12
               for p, q in product(enumerate(c1), enumerate(c2))
               if p[0] > q[0])

print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)
Task: First-class functions_Use numbers analogously


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

int main()
{
  double x  = 2.0;
  double xi = 0.5;
  double y  = 4.0;
  double yi = 0.25;
  double z  = x + y;
  double zi = 1.0 / ( x + y );

  const std::array values{x, y, z};
  const std::array inverses{xi, yi, zi};

  auto multiplier = [](double a, double b)
  {
    return [=](double m){return a * b * m;};
  };

  for(size_t i = 0; i < values.size(); ++i)
  {
    auto new_function = multiplier(values[i], inverses[i]);
    double value = new_function(i + 1.0);
    std::cout << value << "\n"; 
  }
}






Python: IDLE 2.6.1      
>>> 
>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25
>>> 
>>> z  = x + y
>>> zi = 1.0 / (x + y)
>>> 
>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)
>>> 
>>> numlist = [x, y, z]
>>> numlisti = [xi, yi, zi]
>>> 
>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]
[0.5, 0.5, 0.5]
>>>
Task: Almkvist-Giullera formula for pi


C++: #include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/gmp.hpp>
#include <iomanip>
#include <iostream>

namespace mp = boost::multiprecision;
using big_int = mp::mpz_int;
using big_float = mp::cpp_dec_float_100;
using rational = mp::mpq_rational;

big_int factorial(int n) {
    big_int result = 1;
    for (int i = 2; i <= n; ++i)
        result *= i;
    return result;
}


big_int almkvist_giullera(int n) {
    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /
           (pow(factorial(n), 6) * 3);
}

int main() {
    std::cout << "n |                  Integer portion of nth term\n"
              << "------------------------------------------------\n";
    for (int n = 0; n < 10; ++n)
        std::cout << n << " | " << std::setw(44) << almkvist_giullera(n)
                  << '\n';

    big_float epsilon(pow(big_float(10), -70));
    big_float prev = 0, pi = 0;
    rational sum = 0;
    for (int n = 0;; ++n) {
        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));
        sum += term;
        pi = sqrt(big_float(1 / sum));
        if (abs(pi - prev) < epsilon)
            break;
        prev = pi;
    }
    std::cout << "\nPi to 70 decimal places is:\n"
              << std::fixed << std::setprecision(70) << pi << '\n';
}






Python: import mpmath as mp

with mp.workdps(72):

    def integer_term(n):
        p = 532 * n * n + 126 * n + 9
        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)

    def exponent_term(n):
        return -(mp.mpf("6.0") * n + 3)

    def nthterm(n):
        return integer_term(n) * mp.mpf("10.0")**exponent_term(n)


    for n in range(10):
        print("Term ", n, '  ', int(integer_term(n)))


    def almkvist_guillera(floatprecision):
        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
        for n in range(100000000):
            nextadd = summed + nthterm(n)
            if abs(nextadd - summed) < 10.0**(-floatprecision):
                break

            summed = nextadd

        return nextadd


    print('\nπ to 70 digits is ', end='')
    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
    print('mpmath π is       ', end='')
    mp.nprint(mp.pi, 71)
Task: Consecutive primes with ascending or descending differences


C++: #include <cstdint>
#include <iostream>
#include <vector>
#include <primesieve.hpp>

void print_diffs(const std::vector<uint64_t>& vec) {
    for (size_t i = 0, n = vec.size(); i != n; ++i) {
        if (i != 0)
            std::cout << " (" << vec[i] - vec[i - 1] << ") ";
        std::cout << vec[i];
    }
    std::cout << '\n';
}

int main() {
    std::cout.imbue(std::locale(""));
    std::vector<uint64_t> asc, desc;
    std::vector<std::vector<uint64_t>> max_asc, max_desc;
    size_t max_asc_len = 0, max_desc_len = 0;
    uint64_t prime;
    const uint64_t limit = 1000000;
    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {
        size_t alen = asc.size();
        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])
            asc.erase(asc.begin(), asc.end() - 1);
        asc.push_back(prime);
        if (asc.size() >= max_asc_len) {
            if (asc.size() > max_asc_len) {
                max_asc_len = asc.size();
                max_asc.clear();
            }
            max_asc.push_back(asc);
        }
        size_t dlen = desc.size();
        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])
            desc.erase(desc.begin(), desc.end() - 1);
        desc.push_back(prime);
        if (desc.size() >= max_desc_len) {
            if (desc.size() > max_desc_len) {
                max_desc_len = desc.size();
                max_desc.clear();
            }
            max_desc.push_back(desc);
        }
    }
    std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n";
    for (const auto& v : max_asc)
        print_diffs(v);
    std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n";
    for (const auto& v : max_desc)
        print_diffs(v);
    return 0;
}






Python: from sympy import sieve

primelist = list(sieve.primerange(2,1000000))

listlen = len(primelist)



pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]

while pindex < listlen:

    diff = primelist[pindex] - primelist[pindex-1]
    if diff > old_diff:
        curr_list.append(primelist[pindex])
        if len(curr_list) > len(longest_list):
            longest_list = curr_list
    else:
        curr_list = [primelist[pindex-1],primelist[pindex]]
        
    old_diff = diff
    pindex += 1
    
print(longest_list)



pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]

while pindex < listlen:

    diff = primelist[pindex] - primelist[pindex-1]
    if diff < old_diff:
        curr_list.append(primelist[pindex])
        if len(curr_list) > len(longest_list):
            longest_list = curr_list
    else:
        curr_list = [primelist[pindex-1],primelist[pindex]]
        
    old_diff = diff
    pindex += 1
    
print(longest_list)
Task: Literals_Floating point


C++: #include <iostream>

int main()
{
  
  auto double1 = 2.5;

  
  auto float1 = 2.5f;

  
  auto longdouble1 = 2.5l;

  
  auto double2 = 2.5e-3;
  auto float2 = 2.5e3f;

  
  auto double3 = 0x1p4;
  auto float3 = 0xbeefp-8f;

  std::cout << "\ndouble1: " << double1;
  std::cout << "\nfloat1: " << float1;
  std::cout << "\nlongdouble1: " << longdouble1;
  std::cout << "\ndouble2: " << double2;
  std::cout << "\nfloat2: " << float2;
  std::cout << "\ndouble3: " << double3;
  std::cout << "\nfloat3: " << float3;
  std::cout << "\n";
}






Python: 2.3    
.3     
.3e4   
.3e+34 
.3e-34 
2.e34
Task: Break OO privacy


C++: #include <iostream>

class CWidget; 

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); 
  CWidget(const CWidget&); 
  CWidget& operator=(const CWidget&); 
public:
  CWidget(CFactory& parent);
  ~CWidget();
};


CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}


CWidget* CFactory::GetWidget()
{
  
  return new CWidget(*this);
}


CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}






Python: >>> class MyClassName:
	__private = 123
	non_private = __private * 2

	
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
  File "<pyshell
    mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
Task: Long year


C++: #include <stdio.h>
#include <math.h>



int p(int year) {
	return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}

int is_long_year(int year) {
	return p(year) == 4 || p(year - 1) == 3;
}

void print_long_years(int from, int to) {
	for (int year = from; year <= to; ++year) {
		if (is_long_year(year)) {
			printf("%d ", year);
		}
	}
}

int main() {

	printf("Long (53 week) years between 1800 and 2100\n\n");
	print_long_years(1800, 2100);
	printf("\n");
	return 0;
}






Python: 

from datetime import date



def longYear(y):
    
    return 52 < date(y, 12, 28).isocalendar()[1]




def main():
    
    for year in [
            x for x in range(2000, 1 + 2100)
            if longYear(x)
    ]:
        print(year)



if __name__ == '__main__':
    main()
Task: Associative array_Merging


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

template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
    map_type result(update);
    result.insert(original.begin(), original.end());
    return result;
}

int main() {
    typedef std::map<std::string, std::string> map;
    map original{
        {"name", "Rocket Skates"},
        {"price", "12.75"},
        {"color", "yellow"}
    };
    map update{
        {"price", "15.25"},
        {"color", "red"},
        {"year", "1974"}
    };
    map merged(merge(original, update));
    for (auto&& i : merged)
        std::cout << "key: " << i.first << ", value: " << i.second << '\n';
    return 0;
}






Python: base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}

result = {**base, **update}

print(result)
Task: Metallic ratios


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

const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };

template<const uint N>
void lucas(ulong b) {
    std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: ";
    auto x0 = 1L, x1 = 1L;
    std::cout << x0 << ", " << x1;
    for (auto i = 1u; i <= N - 1 - 1; i++) {
        auto x2 = b * x1 + x0;
        std::cout << ", " << x2;
        x0 = x1;
        x1 = x2;
    }
    std::cout << std::endl;
}

template<const ushort P>
void metallic(ulong b) {
    using namespace boost::multiprecision;
    using bfloat = number<cpp_dec_float<P+1>>;
    bfloat x0(1), x1(1);
    auto prev = bfloat(1).str(P+1);
    for (auto i = 0u;;) {
        i++;
        bfloat x2(b * x1 + x0);
        auto thiz = bfloat(x2 / x1).str(P+1);
        if (prev == thiz) {
            std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl;
            break;
        }
        prev = thiz;
        x0 = x1;
        x1 = x2;
    }
}

int main() {
    for (auto b = 0L; b < 10L; b++) {
        lucas<15>(b);
        metallic<32>(b);
    }
    std::cout << "Golden ratio, where b = 1:" << std::endl;
    metallic<256>(1);

    return 0;
}






Python: from itertools import count, islice
from _pydecimal import getcontext, Decimal

def metallic_ratio(b):
    m, n = 1, 1
    while True:
        yield m, n
        m, n = m*b + n, m

def stable(b, prec):
    def to_decimal(b):
        for m,n in metallic_ratio(b):
            yield Decimal(m)/Decimal(n)

    getcontext().prec = prec
    last = 0
    for i,x in zip(count(), to_decimal(b)):
        if x == last:
            print(f'after {i} iterations:\n\t{x}')
            break
        last = x

for b in range(4):
    coefs = [n for _,n in islice(metallic_ratio(b), 15)]
    print(f'\nb = {b}: {coefs}')
    stable(b, 32)

print(f'\nb = 1 with 256 digits:')
stable(1, 256)
Task: Associative array_Iteration


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

int main() {
  std::map<std::string, int> dict {
    {"One", 1},
    {"Two", 2},
    {"Three", 7}
  };

  dict["Three"] = 3;

  std::cout << "One: " << dict["One"] << std::endl;
  std::cout << "Key/Value pairs: " << std::endl;
  for(auto& kv: dict) {
    std::cout << "  " << kv.first << ": " << kv.second << std::endl;
  }

  return 0;
}






Python: myDict = { "hello": 13,
	   "world": 31,
	   "!"    : 71 }


for key, value in myDict.items():
    print ("key = %s, value = %s" % (key, value))


for key in myDict:
    print ("key = %s" % key)

for key in myDict.keys():
    print ("key = %s" % key)


for value in myDict.values():
    print ("value = %s" % value)
Task: Define a primitive data type


C++: #include <stdexcept>

class tiny_int
{
public:
  tiny_int(int i):
    value(i)
  {
    if (value < 1)
      throw std::out_of_range("tiny_int: value smaller than 1");
    if (value > 10)
      throw std::out_of_range("tiny_int: value larger than 10");
  }
  operator int() const
  {
    return value;
  }
  tiny_int& operator+=(int i)
  {
    
    
    *this = value + i;
    return *this;
  }
  tiny_int& operator-=(int i)
  {
    *this = value - i;
    return *this;
  }
  tiny_int& operator*=(int i)
  {
    *this = value * i;
    return *this;
  }
  tiny_int& operator/=(int i)
  {
    *this = value / i;
    return *this;
  }
  tiny_int& operator<<=(int i)
  {
    *this = value << i;
    return *this;
  }
  tiny_int& operator>>=(int i)
  {
    *this = value >> i;
    return *this;
  }
  tiny_int& operator&=(int i)
  {
    *this = value & i;
    return *this;
  }
  tiny_int& operator|=(int i)
  {
    *this = value | i;
    return *this;
  }
private:
  unsigned char value; 
};






Python: >>> class num(int):
    def __init__(self, b):
        if 1 <= b <= 10:
            return int.__init__(self+0)
        else:
            raise ValueError,"Value %s should be >=0 and <= 10" % b

        
>>> x = num(3)
>>> x = num(11)

Traceback (most recent call last):
  File "<pyshell
    x = num(11)
  File "<pyshell
    raise ValueError,"Value %s should be >=0 and <= 10" % b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>>
Task: Arithmetic derivative


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

#include <boost/multiprecision/cpp_int.hpp>

template <typename IntegerType>
IntegerType arithmetic_derivative(IntegerType n) {
    bool negative = n < 0;
    if (negative)
        n = -n;
    if (n < 2)
        return 0;
    IntegerType sum = 0, count = 0, m = n;
    while ((m & 1) == 0) {
        m >>= 1;
        count += n;
    }
    if (count > 0)
        sum += count / 2;
    for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {
        count = 0;
        while (m % p == 0) {
            m /= p;
            count += n;
        }
        if (count > 0)
            sum += count / p;
        sq += (p + 1) << 2;
    }
    if (m > 1)
        sum += n / m;
    if (negative)
        sum = -sum;
    return sum;
}

int main() {
    using boost::multiprecision::int128_t;

    for (int n = -99, i = 0; n <= 100; ++n, ++i) {
        std::cout << std::setw(4) << arithmetic_derivative(n)
                  << ((i + 1) % 10 == 0 ? '\n' : ' ');
    }

    int128_t p = 10;
    std::cout << '\n';
    for (int i = 0; i < 20; ++i, p *= 10) {
        std::cout << "D(10^" << std::setw(2) << i + 1
                  << ") / 7 = " << arithmetic_derivative(p) / 7 << '\n';
    }
}






Python: from sympy.ntheory import factorint

def D(n):
    if n < 0:
        return -D(-n)
    elif n < 2:
        return 0
    else:
        fdict = factorint(n)
        if len(fdict) == 1 and 1 in fdict: 
            return 1
        return sum([n * e // p for p, e in fdict.items()])

for n in range(-99, 101):
    print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '')

print()
for m in range(1, 21):
    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
Task: Permutations with some identical elements


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

int main() {
    std::string str("AABBBC");
    int count = 0;
    do {
        std::cout << str << (++count % 10 == 0 ? '\n' : ' ');
    } while (std::next_permutation(str.begin(), str.end()));
}






Python: 

from itertools import permutations

numList = [2,3,1]

baseList = []

for i in numList:
    for j in range(0,i):
        baseList.append(i)

stringDict = {'A':2,'B':3,'C':1}

baseString=""

for i in stringDict:
    for j in range(0,stringDict[i]):
        baseString+=i

print("Permutations for " + str(baseList) + " : ")
[print(i) for i in set(permutations(baseList))]

print("Permutations for " + baseString + " : ")
[print(i) for i in set(permutations(baseString))]
Task: Penrose tiling


C++: #include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>

int main() {
    std::ofstream out("penrose_tiling.svg");
    if (!out) {
        std::cerr << "Cannot open output file.\n";
        return EXIT_FAILURE;
    }
    std::string penrose("[N]++[N]++[N]++[N]++[N]");
    for (int i = 1; i <= 4; ++i) {
        std::string next;
        for (char ch : penrose) {
            switch (ch) {
            case 'A':
                break;
            case 'M':
                next += "OA++PA----NA[-OA----MA]++";
                break;
            case 'N':
                next += "+OA--PA[---MA--NA]+";
                break;
            case 'O':
                next += "-MA++NA[+++OA++PA]-";
                break;
            case 'P':
                next += "--OA++++MA[+PA++++NA]--NA";
                break;
            default:
                next += ch;
                break;
            }
        }
        penrose = std::move(next);
    }
    const double r = 30;
    const double pi5 = 0.628318530717959;
    double x = r * 8, y = r * 8, theta = pi5;
    std::set<std::string> svg;
    std::stack<std::tuple<double, double, double>> stack;
    for (char ch : penrose) {
        switch (ch) {
        case 'A': {
            double nx = x + r * std::cos(theta);
            double ny = y + r * std::sin(theta);
            std::ostringstream line;
            line << std::fixed << std::setprecision(3) << "<line x1='" << x
                 << "' y1='" << y << "' x2='" << nx << "' y2='" << ny << "'/>";
            svg.insert(line.str());
            x = nx;
            y = ny;
        } break;
        case '+':
            theta += pi5;
            break;
        case '-':
            theta -= pi5;
            break;
        case '[':
            stack.push({x, y, theta});
            break;
        case ']':
            std::tie(x, y, theta) = stack.top();
            stack.pop();
            break;
        }
    }
    out << "<svg xmlns='http:
        << "' width='" << r * 16 << "'>\n"
        << "<rect height='100%' width='100%' fill='black'/>\n"
        << "<g stroke='rgb(255,165,0)'>\n";
    for (const auto& line : svg)
        out << line << '\n';
    out << "</g>\n</svg>\n";
    return EXIT_SUCCESS;
}






Python: def penrose(depth):
    print(	<g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)">
		<use href="
		<use href="
	</g>
	<g id="B{d+1}">
		<use href="
		<use href="
	</g>	<g id="G">
		<use href="
		<use href="
	</g>
  </defs>
  <g transform="scale(2, 2)">
	<use href="
	<use href="
	<use href="
	<use href="
	<use href="
  </g>
</svg>''')

penrose(6)