WeixiangYan/CodeTransOcean huggingface dataset:
Task: Reflection_List properties




Go: package main

import (
	"fmt"
	"image"
	"reflect"
)


type t struct {
	X    int
	next *t
}

func main() {
	report(t{})
	report(image.Point{})
}

func report(x interface{}) {
	t := reflect.TypeOf(x)
	n := t.NumField()
	fmt.Printf("Type %v has %d fields:\n", t, n)
	fmt.Println("Name     Type     Exported")
	for i := 0; i < n; i++ {
		f := t.Field(i)
		fmt.Printf("%-8s %-8v %-8t\n",
			f.Name,
			f.Type,
			f.PkgPath == "",
		)
	}
	fmt.Println()
}





VB: Imports System.Reflection

Module Module1

    Class TestClass
        Private privateField = 7
        Public ReadOnly Property PublicNumber = 4
        Private ReadOnly Property PrivateNumber = 2
    End Class

    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
        Return From p In obj.GetType().GetProperties(flags)
               Where p.GetIndexParameters().Length = 0
               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}
    End Function

    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})
    End Function

    Sub Main()
        Dim t As New TestClass()
        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance
        For Each prop In GetPropertyValues(t, flags)
            Console.WriteLine(prop)
        Next
        For Each field In GetFieldValues(t, flags)
            Console.WriteLine(field)
        Next
    End Sub

End Module
Task: Align columns




Go: package main

import (
    "fmt"
    "strings"
)

const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.`

type formatter struct {
    text  [][]string
    width []int
}

func newFormatter(text string) *formatter {
    var f formatter
    for _, line := range strings.Split(text, "\n") {
        words := strings.Split(line, "$")
        for words[len(words)-1] == "" {
            words = words[:len(words)-1]
        }
        f.text = append(f.text, words)
        for i, word := range words {
            if i == len(f.width) {
                f.width = append(f.width, len(word))
            } else if len(word) > f.width[i] {
                f.width[i] = len(word)
            }
        }
    }
    return &f
}

const (
    left = iota
    middle
    right
)

func (f formatter) print(j int) {
    for _, line := range f.text {
        for i, word := range line {
            fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s",
                len(word)+(f.width[i]-len(word))*j/2, word))
        }
        fmt.Println("")
    }
    fmt.Println("")
}

func main() {
    f := newFormatter(text)
    f.print(left)
    f.print(middle)
    f.print(right)
}





VB: Dim MText as QMemorystream
    MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
    MText.WriteLine "are$delineated$by$a$single$
    MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
    MText.WriteLine "column$are$separated$by$at$least$one$space."
    MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
    MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column."

DefStr TextLeft, TextRight, TextCenter
DefStr MLine, LWord, Newline = chr$(13)+chr$(10)
DefInt ColWidth(100), ColCount
DefSng NrSpaces 


MText.position = 0
for x = 0 to MText.linecount -1
    MLine = MText.ReadLine
    for y = 0 to Tally(MLine, "$")
        LWord = Field$(MLine, "$", y+1)
        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))
    next
next


MText.position = 0
for x = 0 to MText.linecount -1
    MLine = MText.ReadLine
    for y = 0 to Tally(MLine, "$")
        LWord = Field$(MLine, "$", y+1)
        NrSpaces = ColWidth(y) - len(LWord)
        
        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)
        
        TextRight = TextRight + Space$(NrSpaces+1) + LWord
        
        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))
    next
    TextLeft = TextLeft + Newline 
    TextRight = TextRight + Newline 
    TextCenter = TextCenter + Newline 
next
Task: Data Encryption Standard




Go: package main

import (
    "crypto/des"
    "encoding/hex"
    "fmt"
    "log"
)

func main() {
    key, err := hex.DecodeString("0e329232ea6d0d73")
    if err != nil {
        log.Fatal(err)
    }
    c, err := des.NewCipher(key)
    if err != nil {
        log.Fatal(err)
    }
    src, err := hex.DecodeString("8787878787878787")
    if err != nil {
        log.Fatal(err)
    }
    dst := make([]byte, des.BlockSize)
    c.Encrypt(dst, src)
    fmt.Printf("%x\n", dst)
}





VB: Imports System.IO
Imports System.Security.Cryptography

Module Module1

    
    Function ByteArrayToString(ba As Byte()) As String
        Return BitConverter.ToString(ba).Replace("-", "")
    End Function

    
    
    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()
        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

        
        Dim provider As New DESCryptoServiceProvider
        Dim transform = provider.CreateEncryptor(passwordBytes, iv)
        Dim mode = CryptoStreamMode.Write

        
        Dim memStream As New MemoryStream
        Dim cryptoStream As New CryptoStream(memStream, transform, mode)
        cryptoStream.Write(messageBytes, 0, messageBytes.Length)
        cryptoStream.FlushFinalBlock()

        
        Dim encryptedMessageBytes(memStream.Length - 1) As Byte
        memStream.Position = 0
        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)

        Return encryptedMessageBytes
    End Function

    
    
    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()
        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

        
        Dim provider As New DESCryptoServiceProvider
        Dim transform = provider.CreateDecryptor(passwordBytes, iv)
        Dim mode = CryptoStreamMode.Write

        
        Dim memStream As New MemoryStream
        Dim cryptoStream As New CryptoStream(memStream, transform, mode)
        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
        cryptoStream.FlushFinalBlock()

        
        Dim decryptedMessageBytes(memStream.Length - 1) As Byte
        memStream.Position = 0
        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)

        Return decryptedMessageBytes
    End Function

    Sub Main()
        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}
        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}

        Dim encStr = Encrypt(plainBytes, keyBytes)
        Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr))

        Dim decStr = Decrypt(encStr, keyBytes)
        Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr))
    End Sub

End Module
Task: Make a backup file




Go: package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    fn := "myth"
    bx := ".backup"
    
    var err error
    if tf, err := os.Readlink(fn); err == nil {
        fn = tf
    }
    
    var fi os.FileInfo
    if fi, err = os.Stat(fn); err != nil {
        fmt.Println(err)
        return
    }
    
    if err = os.Rename(fn, fn+bx); err != nil {
        fmt.Println(err)
        return
    }
    
    err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
    if err != nil {
        fmt.Println(err)
    }
}





VB: Public Sub backup(filename As String)
    If Len(Dir(filename)) > 0 Then
        On Error Resume Next
        Name filename As filename & ".bak"
    Else
        If Len(Dir(filename & ".lnk")) > 0 Then
            On Error Resume Next
            With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
                link = .TargetPath
                .Close
            End With
            Name link As link & ".bak"
        End If
    End If
End Sub
Public Sub main()
    backup "D:\test.txt"
End Sub
Task: Nested templated data




Go: package main

import (
    "fmt"
    "os"
    "sort"
    "strings"
    "text/template"
)

func main() {
    const t = `[[[{{index .P 1}}, {{index .P 2}}],
  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], 
  {{index .P 5}}]]
`
    type S struct {
        P map[int]string
    }

    var s S
    s.P = map[int]string{
        0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'",
        4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'",
    }
    tmpl := template.Must(template.New("").Parse(t))
    tmpl.Execute(os.Stdout, s)

    var unused []int
    for k, _ := range s.P {
        if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) {
            unused = append(unused, k)
        }
    }
    sort.Ints(unused)
    fmt.Println("\nThe unused payloads have indices of :", unused)
}





VB: Public Sub test()
    Dim t(2) As Variant
    t(0) = [{1,2}]
    t(1) = [{3,4,1}]
    t(2) = 5
    p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}]
    Dim q(6) As Boolean
    For i = LBound(t) To UBound(t)
        If IsArray(t(i)) Then
            For j = LBound(t(i)) To UBound(t(i))
                q(t(i)(j)) = True
                t(i)(j) = p(t(i)(j) + 1)
            Next j
        Else
            q(t(i)) = True
            t(i) = p(t(i) + 1)
        End If
    Next i
    For i = LBound(t) To UBound(t)
        If IsArray(t(i)) Then
            Debug.Print Join(t(i), ", ")
        Else
            Debug.Print t(i)
        End If
    Next i
    For i = LBound(q) To UBound(q)
        If Not q(i) Then Debug.Print p(i + 1); " is not used"
    Next i
End Sub
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;
}



Go: package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "math"
    "os"
    "runtime"
)

func main() {
    _, src, _, _ := runtime.Caller(0)
    fmt.Println("Source file entropy:", entropy(src))
    fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}

func entropy(file string) float64 {
    d, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    var f [256]float64
    for _, b := range d {
        f[b]++
    }
    hm := 0.
    for _, c := range f {
        if c > 0 {
            hm += c * math.Log2(c)
        }
    }
    l := float64(len(d))
    return math.Log2(l) - hm/l
}
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) ;

}



Go: package main

import (
    "fmt"
    "net"
)

func main() {
    if addrs, err := net.LookupHost("www.kame.net"); err == nil {
        fmt.Println(addrs)
    } else {
        fmt.Println(err)
    }
}
Task: Peano curve


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

class peano_curve {
public:
    void write(std::ostream& out, int size, int length, int order);
private:
    static std::string rewrite(const std::string& s);
    void line(std::ostream& out);
    void execute(std::ostream& out, const std::string& s);
    double x_;
    double y_;
    int angle_;
    int length_;
};

void peano_curve::write(std::ostream& out, int size, int length, int order) {
    length_ = length;
    x_ = length;
    y_ = length;
    angle_ = 90;
    out << "<svg xmlns='http:
        << size << "' height='" << size << "'>\n";
    out << "<rect width='100%' height='100%' fill='white'/>\n";
    out << "<path stroke-width='1' stroke='black' fill='none' d='";
    std::string s = "L";
    for (int i = 0; i < order; ++i)
        s = rewrite(s);
    execute(out, s);
    out << "'/>\n</svg>\n";
}

std::string peano_curve::rewrite(const std::string& s) {
    std::string t;
    for (char c : s) {
        switch (c) {
        case 'L':
            t += "LFRFL-F-RFLFR+F+LFRFL";
            break;
        case 'R':
            t += "RFLFR+F+LFRFL-F-RFLFR";
            break;
        default:
            t += c;
            break;
        }
    }
    return t;
}

void peano_curve::line(std::ostream& out) {
    double theta = (3.14159265359 * angle_)/180.0;
    x_ += length_ * std::cos(theta);
    y_ += length_ * std::sin(theta);
    out << " L" << x_ << ',' << y_;
}

void peano_curve::execute(std::ostream& out, const std::string& s) {
    out << 'M' << x_ << ',' << y_;
    for (char c : s) {
        switch (c) {
        case 'F':
            line(out);
            break;
        case '+':
            angle_ = (angle_ + 90) % 360;
            break;
        case '-':
            angle_ = (angle_ - 90) % 360;
            break;
        }
    }
}

int main() {
    std::ofstream out("peano_curve.svg");
    if (!out) {
        std::cerr << "Cannot open output file\n";
        return 1;
    }
    peano_curve pc;
    pc.write(out, 656, 8, 4);
    return 0;
}



Go: package main

import "github.com/fogleman/gg"

var points []gg.Point

const width = 81

func peano(x, y, lg, i1, i2 int) {
    if lg == 1 {
        px := float64(width-x) * 10
        py := float64(width-y) * 10
        points = append(points, gg.Point{px, py})
        return
    }
    lg /= 3
    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)
    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)
    peano(x+lg, y+lg, lg, i1, 1-i2)
    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)
    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)
    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)
    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)
    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)
    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)
}

func main() {
    peano(0, 0, width, 0, 0)
    dc := gg.NewContext(820, 820)
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    for _, p := range points {
        dc.LineTo(p.X, p.Y)
    }
    dc.SetRGB(1, 0, 1) 
    dc.SetLineWidth(1)
    dc.Stroke()
    dc.SavePNG("peano.png")
}
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);
}



Go: package main

import (
    "fmt"
    "math"
    "math/rand"
    "time"
)


func dice5() int {
    return rand.Intn(5) + 1
}


func dice7() (i int) {
    for {
        i = 5*dice5() + dice5()
        if i < 27 {
            break
        }
    }
    return (i / 3) - 1
}










func distCheck(f func() int, n int,
    repeats int, delta float64) (max float64, flatEnough bool) {
    count := make([]int, n)
    for i := 0; i < repeats; i++ {
        count[f()-1]++
    }
    expected := float64(repeats) / float64(n)
    for _, c := range count {
        max = math.Max(max, math.Abs(float64(c)-expected))
    }
    return max, max < delta
}


func main() {
    rand.Seed(time.Now().UnixNano())
    const calls = 1000000
    max, flatEnough := distCheck(dice7, 7, calls, 500)
    fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
    max, flatEnough = distCheck(dice7, 7, calls, 500)
    fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}
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;
}



Go: package main

import (
	"fmt"
	"strings"
)

func main() {
	p, tests, swaps := Solution()
	fmt.Println(p)
	fmt.Println("Tested", tests, "positions and did", swaps, "swaps.")
}



const conn = `
       A   B
      /|\ /|\
     / | X | \
    /  |/ \|  \
   C - D - E - F
    \  |\ /|  /
     \ | X | /
      \|/ \|/
       G   H`

var connections = []struct{ a, b int }{
	{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}, 
}

type pegs [8]int




func (p *pegs) Valid() bool {
	for _, c := range connections {
		if absdiff(p[c.a], p[c.b]) <= 1 {
			return false
		}
	}
	return true
}





func Solution() (p *pegs, tests, swaps int) {
	var recurse func(int) bool
	recurse = func(i int) bool {
		if i >= len(p)-1 {
			tests++
			return p.Valid()
		}
		
		for j := i; j < len(p); j++ {
			swaps++
			p[i], p[j] = p[j], p[i]
			if recurse(i + 1) {
				return true
			}
			p[i], p[j] = p[j], p[i]
		}
		return false
	}
	p = &pegs{1, 2, 3, 4, 5, 6, 7, 8}
	recurse(0)
	return
}

func (p *pegs) String() string {
	return strings.Map(func(r rune) rune {
		if 'A' <= r && r <= 'H' {
			return rune(p[r-'A'] + '0')
		}
		return r
	}, conn)
}

func absdiff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
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;
}



Go: package main

import "fmt"

func main() {
    var row, col int
    fmt.Print("enter rows cols: ")
    fmt.Scan(&row, &col)

    
    a := make([][]int, row)
    for i := range a {
        a[i] = make([]int, col)
    }

    
    fmt.Println("a[0][0] =", a[0][0])

    
    a[row-1][col-1] = 7

    
    fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])

    
    a = nil
    
}
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;
}



Go: package main

import (
    "fmt"
    "math/big"
)

var one = big.NewInt(1)

func crt(a, n []*big.Int) (*big.Int, error) {
    p := new(big.Int).Set(n[0])
    for _, n1 := range n[1:] {
        p.Mul(p, n1)
    }
    var x, q, s, z big.Int
    for i, n1 := range n {
        q.Div(p, n1)
        z.GCD(nil, &s, n1, &q)
        if z.Cmp(one) != 0 {
            return nil, fmt.Errorf("%d not coprime", n1)
        }
        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
    }
    return x.Mod(&x, p), nil
}

func main() {
    n := []*big.Int{
        big.NewInt(3),
        big.NewInt(5),
        big.NewInt(7),
    }
    a := []*big.Int{
        big.NewInt(2),
        big.NewInt(3),
        big.NewInt(2),
    }
    fmt.Println(crt(a, n))
}