WeixiangYan/CodeTransOcean huggingface dataset:
Task: Matrix digital rain

C: 
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>


#define ROW_DELAY 40000


int get_rand_in_range(int min, int max)
{
  return (rand() % ((max + 1) - min) + min);
}

int main(void)
{
  
  srand(time(NULL));

  
  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

  int total_chars = sizeof(chars);

  
  initscr();
  noecho();
  curs_set(FALSE);

  start_color();
  init_pair(1, COLOR_GREEN, COLOR_BLACK);
  attron(COLOR_PAIR(1));

  int max_x = 0, max_y = 0;

  getmaxyx(stdscr, max_y, max_x);

  

  
  int columns_row[max_x];

  
  int columns_active[max_x];

  int i;

  
  for (i = 0; i < max_x; i++)
  {
    columns_row[i] = -1;
    columns_active[i] = 0;
  }

  while (1)
  {
    for (i = 0; i < max_x; i++)
    {
      if (columns_row[i] == -1)
      {
        
        columns_row[i] = get_rand_in_range(0, max_y);
        columns_active[i] = get_rand_in_range(0, 1);
      }
    }

    
    for (i = 0; i < max_x; i++)
    {
      if (columns_active[i] == 1)
      {
        
        int char_index = get_rand_in_range(0, total_chars);
        mvprintw(columns_row[i], i, "%c", chars[char_index]);
      }
      else
      {
        
        mvprintw(columns_row[i], i, " ");
      }

      columns_row[i]++;

      
      if (columns_row[i] >= max_y)
      {
        columns_row[i] = -1;
      }

      
      if (get_rand_in_range(0, 1000) == 0)
      {
        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
      }
    }

    usleep(ROW_DELAY);
    refresh();
  }

  endwin();
  return 0;
}
Task: Mian-Chowla sequence



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

static class Program {
    static int[] MianChowla(int n) {
        int[] mc = new int[n - 1 + 1];
        HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>();
        int sum; mc[0] = 1; sums.Add(2);
        for (int i = 1; i <= n - 1; i++) {
            for (int j = mc[i - 1] + 1; ; j++) {
                mc[i] = j;
                for (int k = 0; k <= i; k++) {
                    sum = mc[k] + j;
                    if (sums.Contains(sum)) { ts.Clear(); break; }
                    ts.Add(sum);
                }
                if (ts.Count > 0) { sums.UnionWith(ts); break; }
            }
        }
        return mc;
    }

    static void Main(string[] args)
    {
        const int n = 100; Stopwatch sw = new Stopwatch();
        string str = " of the Mian-Chowla sequence are:\n";
        sw.Start(); int[] mc = MianChowla(n); sw.Stop();
        Console.Write("The first 30 terms{1}{2}{0}{0}Terms 91 to 100{1}{3}{0}{0}" +
            "Computation time was {4}ms.{0}", '\n', str, string.Join(" ", mc.Take(30)),
            string.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds);
    }
}
Task: Water collected between towers



C#: class Program
{
    static void Main(string[] args)
    {
        int[][] wta = {
            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },
            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};
        string blk, lf = "\n", tb = "██", wr = "≈≈", mt = "  ";
        for (int i = 0; i < wta.Length; i++)
        {
            int bpf; blk = ""; do
            {
                string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
                {
                    if (wta[i][j] > 0)
                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }
                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
                }
                if (bpf > 0) blk = floor + lf + blk;
            } while (bpf > 0);
            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
            if (args.Length > 0) System.Console.Write("\n{0}", blk);
            System.Console.WriteLine("Block {0} retains {1,2} water units.",
                i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
        }
    }
}
Task: FASTA format



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

class Program
{
    public class FastaEntry
    {
        public string Name { get; set; }
        public StringBuilder Sequence { get; set; }
    }

    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
    {
        FastaEntry f = null;
        string line;
        while ((line = fastaFile.ReadLine()) != null)
        {
            
            if (line.StartsWith(";"))
                continue;

            if (line.StartsWith(">"))
            {
                if (f != null)
                    yield return f;
                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
            }
            else if (f != null)
                f.Sequence.Append(line);
        }
        yield return f;
    }

    static void Main(string[] args)
    {
        try
        {
            using (var fastaFile = new StreamReader("fasta.txt"))
            {
                foreach (FastaEntry f in ParseFasta(fastaFile))
                    Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e);
        }
        Console.ReadLine();
    }
}
Task: Kahan summation



C#: using System;

namespace KahanSummation {
    class Program {
        static float KahanSum(params float[] fa) {
            float sum = 0.0f;
            float c = 0.0f;
            foreach (float f in fa) {
                float y = f - c;
                float t = sum + y;
                c = (t - sum) - y;
                sum = t;
            }

            return sum;
        }

        static float Epsilon() {
            float eps = 1.0f;
            while (1.0f + eps != 1.0f) eps /= 2.0f;
            return eps;
        }

        static void Main(string[] args) {
            float a = 1.0f;
            float b = Epsilon();
            float c = -b;
            Console.WriteLine("Epsilon      = {0}", b);
            Console.WriteLine("(a + b) + c  = {0}", (a + b) + c);
            Console.WriteLine("Kahan sum    = {0}", KahanSum(a, b, c));
        }
    }
}
Task: Two identical strings



C#: using System; using static System.Console;
class Program { static void Main() { int c = 0, lmt = 1000;
    for (int n = 1, p = 2, k; n <= lmt; n++)
      if ((k = n + n * (p += n >= p ? p : 0)) > lmt) break;
      else Console.Write("{0,3} ({1,-10})  {2}", k,
          Convert.ToString(k, 2), ++c % 5 == 0 ? "\n" : "");
    Write("\nFound {0} numbers whose base 2 representation is the " +
      "concatenation of two identical binary strings.", c); } }
Task: Sum of first n cubes



C#: using System; using static System.Console;
class Program { static void Main(string[] args) {
    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)
      Write("{0,-7}{1}",s, (i+=i==3?-4:1)==0?"\n":" "); } }
Task: Copy a string



C#: string src = "Hello";
string dst = src;
Task: Loops_Infinite



C#: while (true)
{
    Console.WriteLine("SPAM");
}
Task: Function definition



C#: static double multiply(double a, double b)
{
    return a * b;
}
Task: Successive prime differences



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

public static class SuccessivePrimeDifferences {

    public static void Main() {
        var primes = GeneratePrimes(1_000_000).ToList();
        foreach (var d in new[] {
            new [] { 2 },
            new [] { 1 },
            new [] { 2, 2 },
            new [] { 2, 4 },
            new [] { 4, 2 },
            new [] { 6, 4, 2 },
        }) {
            IEnumerable<int> first = null, last = null;
            int count = 0;
            foreach (var grp in FindDifferenceGroups(d)) {
                if (first == null) first = grp;
                last = grp;
                count++;
            }
            Console.WriteLine($"{$"({string.Join(", ", first)})"}, {$"({string.Join(", ", last)})"}, {count}");
        }

        IEnumerable<IEnumerable<int>> FindDifferenceGroups(int[] diffs) {
            for (int pi = diffs.Length; pi < primes.Count; pi++)
                if (Range(0, diffs.Length).All(di => primes[pi-diffs.Length+di+1] - primes[pi-diffs.Length+di] == diffs[di]))
                    yield return Range(pi - diffs.Length, diffs.Length + 1).Select(i => primes[i]);
        }

        IEnumerable<int> GeneratePrimes(int lmt) {
            bool[] comps = new bool[lmt + 1];
            comps[0] = comps[1] = true;
            yield return 2; yield return 3;
            for (int j = 4; j <= lmt; j += 2) comps[j] = true;
            for (int j = 9; j <= lmt; j += 6) comps[j] = true;
            int i = 5, d = 4, rt = (int)Math.Sqrt(lmt);
            for ( ; i <= rt; i += (d = 6 - d))
                if (!comps[i]) {
                    yield return i;
                    for (int j = i * i, k = i << 1; j <= lmt; j += k)
                        comps[j] = true;
                }
            for ( ; i <= lmt; i += (d = 6 - d)) if (!comps[i]) yield return i;
        }
    }
}
Task: 10001th prime



C#: using System; class Program {

  static bool isprime(uint p ) { if ((p & 1) == 0) return p == 2;
    if ((p % 3) == 0) return p == 3;
    for (uint i = 5, d = 4; i * i <= p; i += (d = 6 - d))
      if (p % i == 0) return false; return true; }
 
  static uint prime(uint n) { uint p, d, pn;
    for (p = 5, d = 4, pn = 2; pn < n; p += (d = 6 - d))
      if (isprime(p)) pn++; return p - d; }

  static void Main(string[] args) {
    Console.WriteLine("One-at-a-time trial division vs sieve of Eratosthenes");
    var sw = System.Diagnostics.Stopwatch.StartNew();
    var t = prime(10001); sw.Stop(); double e1, e2;
    Console.Write("{0:n0} {1} ms", prime(10001),
      e1 = sw.Elapsed.TotalMilliseconds);
    sw.Restart(); uint n = 105000, i, j; var pr = new uint[10100];
    pr[0] = 2; pr[1] = 3; uint pc = 2, r, d, ii;
    var pl = new bool[n + 1]; r = (uint)Math.Sqrt(n);
    for (i = 9; i < n; i += 6) pl[i] = true;
    for (i = 5, d = 4; i <= r; i += (d = 6 - d)) if (!pl[i]) {
      pr[pc++] = i; for (j = i * i, ii = i << 1; j <= n; j += ii)
        pl[j] = true; }
    for ( ;i <= n; i += (d = 6 - d)) if (!pl[i]) pr[pc++] = i;
    t = pr[10000]; sw.Stop();
    Console.Write("  {0:n0} {1} μs  {2:0.000} times faster", t,
      (e2 = sw.Elapsed.TotalMilliseconds) * 1000.0, e1 / e2); } }
Task: Range consolidation




Go: package main

import (
    "fmt"
    "math"
    "sort"
)

type Range struct{ Lower, Upper float64 }

func (r Range) Norm() Range {
    if r.Lower > r.Upper {
        return Range{r.Upper, r.Lower}
    }
    return r
}

func (r Range) String() string {
    return fmt.Sprintf("[%g, %g]", r.Lower, r.Upper)
}

func (r1 Range) Union(r2 Range) []Range {
    if r1.Upper < r2.Lower {
        return []Range{r1, r2}
    }
    r := Range{r1.Lower, math.Max(r1.Upper, r2.Upper)}
    return []Range{r}
}

func consolidate(rs []Range) []Range {
    for i := range rs {
        rs[i] = rs[i].Norm()
    }
    le := len(rs)
    if le < 2 {
        return rs
    }
    sort.Slice(rs, func(i, j int) bool {
        return rs[i].Lower < rs[j].Lower
    })
    if le == 2 {
        return rs[0].Union(rs[1])
    }
    for i := 0; i < le-1; i++ {
        for j := i + 1; j < le; j++ {
            ru := rs[i].Union(rs[j])
            if len(ru) == 1 {
                rs[i] = ru[0]
                copy(rs[j:], rs[j+1:])
                rs = rs[:le-1]
                le--
                i--
                break
            }
        }
    }
    return rs
}

func main() {
    rss := [][]Range{
        {{1.1, 2.2}},
        {{6.1, 7.2}, {7.2, 8.3}},
        {{4, 3}, {2, 1}},
        {{4, 3}, {2, 1}, {-1, -2}, {3.9, 10}},
        {{1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6}},
    }
    for _, rs := range rss {
        s := fmt.Sprintf("%v", rs)
        fmt.Printf("%40s => ", s[1:len(s)-1])
        rs2 := consolidate(rs)
        s = fmt.Sprintf("%v", rs2)
        fmt.Println(s[1 : len(s)-1])
    }
}
Task: Pascal matrix generation




Go: package main

import (
    "fmt"
    "strings"
)

func binomial(n, k int) int {
    if n < k {
        return 0
    }
    if n == 0 || k == 0 {
        return 1
    }
    num := 1
    for i := k + 1; i <= n; i++ {
        num *= i
    }
    den := 1
    for i := 2; i <= n-k; i++ {
        den *= i
    }
    return num / den
}

func pascalUpperTriangular(n int) [][]int {
    m := make([][]int, n)
    for i := 0; i < n; i++ {
        m[i] = make([]int, n)
        for j := 0; j < n; j++ {
            m[i][j] = binomial(j, i)
        }
    }
    return m
}

func pascalLowerTriangular(n int) [][]int {
    m := make([][]int, n)
    for i := 0; i < n; i++ {
        m[i] = make([]int, n)
        for j := 0; j < n; j++ {
            m[i][j] = binomial(i, j)
        }
    }
    return m
}

func pascalSymmetric(n int) [][]int {
    m := make([][]int, n)
    for i := 0; i < n; i++ {
        m[i] = make([]int, n)
        for j := 0; j < n; j++ {
            m[i][j] = binomial(i+j, i)
        }
    }
    return m
}

func printMatrix(title string, m [][]int) {
    n := len(m)
    fmt.Println(title)
    fmt.Print("[")
    for i := 0; i < n; i++ {
        if i > 0 {
            fmt.Print(" ")
        }
        mi := strings.Replace(fmt.Sprint(m[i]), " ", ", ", -1)
        fmt.Print(mi)
        if i < n-1 {
            fmt.Println(",")
        } else {
            fmt.Println("]\n")
        }
    }
}

func main() {
    printMatrix("Pascal upper-triangular matrix", pascalUpperTriangular(5))
    printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
    printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}
Task: Mad Libs




Go: package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    pat := regexp.MustCompile("<.+?>")
    if len(os.Args) != 2 {
        fmt.Println("usage: madlib <story template file>")
        return
    }
    b, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmpl := string(b)
    s := []string{}          
    m := map[string]string{} 
    for _, p := range pat.FindAllString(tmpl, -1) {
        if _, ok := m[p]; !ok {
            m[p] = ""
            s = append(s, p)
        }
    }
    fmt.Println("Enter replacements:")
    br := bufio.NewReader(os.Stdin)
    for _, p := range s {
        for {
            fmt.Printf("%s: ", p[1:len(p)-1])
            r, isPre, err := br.ReadLine()
            if err != nil {
                log.Fatal(err)
            }
            if isPre {
                log.Fatal("you're not playing right. :P")
            }
            s := strings.TrimSpace(string(r))
            if s == "" {
                fmt.Println("  hmm?")
                continue
            }
            m[p] = s
            break
        }
    }
    fmt.Println("\nYour story:\n")
    fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
        return m[p]
    }))
}
Task: Shortest common supersequence




Go: package main

import (
    "fmt"
    "strings"
)

func lcs(x, y string) string {
    xl, yl := len(x), len(y)
    if xl == 0 || yl == 0 {
        return ""
    }
    x1, y1 := x[:xl-1], y[:yl-1]
    if x[xl-1] == y[yl-1] {
        return fmt.Sprintf("%s%c", lcs(x1, y1), x[xl-1])
    }
    x2, y2 := lcs(x, y1), lcs(x1, y)
    if len(x2) > len(y2) {
        return x2
    } else {
        return y2
    }
}

func scs(u, v string) string {
    ul, vl := len(u), len(v)
    lcs := lcs(u, v)
    ui, vi := 0, 0
    var sb strings.Builder
    for i := 0; i < len(lcs); i++ {
        for ui < ul && u[ui] != lcs[i] {
            sb.WriteByte(u[ui])
            ui++
        }
        for vi < vl && v[vi] != lcs[i] {
            sb.WriteByte(v[vi])
            vi++
        }
        sb.WriteByte(lcs[i])
        ui++
        vi++
    }
    if ui < ul {
        sb.WriteString(u[ui:])
    }
    if vi < vl {
        sb.WriteString(v[vi:])
    }
    return sb.String()
}

func main() {
    u := "abcbdab"
    v := "bdcaba"
    fmt.Println(scs(u, v))
}
Task: Long year




Go: package main

import (
    "fmt"
    "time"
)

func main() {
    centuries := []string{"20th", "21st", "22nd"}
    starts := []int{1900, 2000, 2100} 
    for i := 0; i < len(centuries); i++ {
        var longYears []int
        fmt.Printf("\nLong years in the %s century:\n", centuries[i])
        for j := starts[i]; j < starts[i] + 100; j++ {
            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
            if _, week := t.ISOWeek(); week == 53 {
                longYears = append(longYears, j)
            }
        }
        fmt.Println(longYears)
    }
}
Task: Mian-Chowla sequence




Go: package main

import "fmt"

func contains(is []int, s int) bool {
    for _, i := range is {
        if s == i {
            return true
        }
    }
    return false
}

func mianChowla(n int) []int {
    mc := make([]int, n)
    mc[0] = 1
    is := []int{2}
    var sum int
    for i := 1; i < n; i++ {
        le := len(is)
    jloop:
        for j := mc[i-1] + 1; ; j++ {
            mc[i] = j
            for k := 0; k <= i; k++ {
                sum = mc[k] + j
                if contains(is, sum) {
                    is = is[0:le]
                    continue jloop
                }
                is = append(is, sum)
            }
            break
        }
    }
    return mc
}

func main() {
    mc := mianChowla(100)
    fmt.Println("The first 30 terms of the Mian-Chowla sequence are:")
    fmt.Println(mc[0:30])
    fmt.Println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
    fmt.Println(mc[90:100])
}
Task: Water collected between towers




Go: package main

import "fmt"

func maxl(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := 0; i < len(hm);i++{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func maxr(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := len(hm) - 1 ; i >= 0;i--{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func min(a,b []int)  []int {
	res := make([]int,len(a))
	for i := 0; i < len(a);i++{
		if a[i] >= b[i]{
			res[i] = b[i]
		}else {
			res[i] = a[i]
		}
	}
	return res
}
func diff(hm, min []int) []int {
	res := make([]int,len(hm))
	for i := 0; i < len(hm);i++{
		if min[i] > hm[i]{
			res[i] = min[i] - hm[i]
		}
	}
	return res
}
func sum(a []int) int {
	res := 0
	for i := 0; i < len(a);i++{
		res += a[i]
	}
	return res
}

func waterCollected(hm []int) int {
	maxr := maxr(hm)
	maxl := maxl(hm)
	min := min(maxr,maxl)
	diff := diff(hm,min)
	sum := sum(diff)
	return sum
}


func main() {
	fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
	fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
	fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
	fmt.Println(waterCollected([]int{5, 5, 5, 5}))
	fmt.Println(waterCollected([]int{5, 6, 7, 8}))
	fmt.Println(waterCollected([]int{8, 7, 7, 6}))
	fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
Task: FASTA format




Go: package main

import (
        "bufio"
        "fmt"
        "os"
)

func main() {
        f, err := os.Open("rc.fasta")
        if err != nil {
                fmt.Println(err)
                return
        }
        defer f.Close()
        s := bufio.NewScanner(f)
        headerFound := false
        for s.Scan() {
                line := s.Text()
                switch {
                case line == "":
                        continue
                case line[0] != '>':
                        if !headerFound {
                                fmt.Println("missing header")
                                return
                        }
                        fmt.Print(line)
                case headerFound:
                        fmt.Println()
                        fallthrough
                default:
                        fmt.Printf("%s: ", line[1:])
                        headerFound = true
                }
        }
        if headerFound {
                fmt.Println()
        }
        if err := s.Err(); err != nil {
                fmt.Println(err)
        }
}
Task: MAC vendor lookup




Go: package main

import (
	"net/http"
	"fmt"
	"io/ioutil"
)

func macLookUp(mac string) (res string){
	resp, _ := http.Get("http:
	body, _ := ioutil.ReadAll(resp.Body)
	res = string(body)
	return
}

func main()  {
	fmt.Println(macLookUp("FC-A1-3E"))
	fmt.Println(macLookUp("FC:FB:FB:01:FA:21"))
	fmt.Println(macLookUp("BC:5F:F4"))
}
Task: Magic 8-ball




Go: package main

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"math/rand"
	"os"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	answers := [...]string{
		"It is certain", "It is decidedly so", "Without a doubt",
		"Yes, definitely", "You may rely on it", "As I see it, yes",
		"Most likely", "Outlook good", "Signs point to yes", "Yes",
		"Reply hazy, try again", "Ask again later",
		"Better not tell you now", "Cannot predict now",
		"Concentrate and ask again", "Don't bet on it",
		"My reply is no", "My sources say no", "Outlook not so good",
		"Very doubtful",
	}
	const prompt = "\n? : "
	fmt.Print("Please enter your question or a blank line to quit.\n" + prompt)
	sc := bufio.NewScanner(os.Stdin)
	for sc.Scan() {
		question := sc.Bytes()
		question = bytes.TrimSpace(question)
		if len(question) == 0 {
			break
		}
		answer := answers[rand.Intn(len(answers))]
		fmt.Printf("\n%s\n"+prompt, answer)
	}
	if err := sc.Err(); err != nil {
		log.Fatal(err)
	}
}
Task: Validate International Securities Identification Number




Go: package main

import "regexp"

var r = regexp.MustCompile(`^[A-Z]{2}[A-Z0-9]{9}\d$`)

var inc = [2][10]int{
	{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
	{0, 2, 4, 6, 8, 1, 3, 5, 7, 9},
}

func ValidISIN(n string) bool {
	if !r.MatchString(n) {
		return false
	}
	var sum, p int
	for i := 10; i >= 0; i-- {
		p = 1 - p
		if d := n[i]; d < 'A' {
			sum += inc[p][d-'0']
		} else {
			d -= 'A'
			sum += inc[p][d%10]
			p = 1 - p
			sum += inc[p][d/10+1]
		}
	}
	sum += int(n[11] - '0')
	return sum%10 == 0
}
Task: Orbital elements




Go: package main

import (
    "fmt"
    "math"
)

type vector struct{ x, y, z float64 }

func (v vector) add(w vector) vector {
    return vector{v.x + w.x, v.y + w.y, v.z + w.z}
}

func (v vector) mul(m float64) vector {
    return vector{v.x * m, v.y * m, v.z * m}
}

func (v vector) div(d float64) vector {
    return v.mul(1.0 / d)
}

func (v vector) abs() float64 {
    return math.Sqrt(v.x*v.x + v.y*v.y + v.z*v.z)
}

func (v vector) String() string {
    return fmt.Sprintf("(%g, %g, %g)", v.x, v.y, v.z)
}

func orbitalStateVectors(
    semimajorAxis, eccentricity, inclination, longitudeOfAscendingNode,
    argumentOfPeriapsis, trueAnomaly float64) (position vector, speed vector) {

    i := vector{1, 0, 0}
    j := vector{0, 1, 0}
    k := vector{0, 0, 1}

    mulAdd := func(v1, v2 vector, x1, x2 float64) vector {
        return v1.mul(x1).add(v2.mul(x2))
    }

    rotate := func(i, j vector, alpha float64) (vector, vector) {
        return mulAdd(i, j, math.Cos(alpha), math.Sin(alpha)),
            mulAdd(i, j, -math.Sin(alpha), math.Cos(alpha))
    }

    i, j = rotate(i, j, longitudeOfAscendingNode)
    j, _ = rotate(j, k, inclination)
    i, j = rotate(i, j, argumentOfPeriapsis)

    l := 2.0
    if eccentricity != 1.0 {
        l = 1.0 - eccentricity*eccentricity
    }
    l *= semimajorAxis
    c := math.Cos(trueAnomaly)
    s := math.Sin(trueAnomaly)
    r := l / (1.0 + eccentricity*c)
    rprime := s * r * r / l
    position = mulAdd(i, j, c, s).mul(r)
    speed = mulAdd(i, j, rprime*c-r*s, rprime*s+r*c)
    speed = speed.div(speed.abs())
    speed = speed.mul(math.Sqrt(2.0/r - 1.0/semimajorAxis))
    return
}

func main() {
    long := 355.0 / (113.0 * 6.0)
    position, speed := orbitalStateVectors(1.0, 0.1, 0.0, long, 0.0, 0.0)
    fmt.Println("Position :", position)
    fmt.Println("Speed    :", speed)
}