WeixiangYan/CodeTransOcean huggingface dataset:
Task: VList




Go: package main

import "fmt" 

type vList struct {
    base   *vSeg
    offset int
}

type vSeg struct {
    next *vSeg
    ele  []vEle
}


type vEle string
    

func (v vList) index(i int) (r vEle) {
    if i >= 0 { 
        i += v.offset
        for sg := v.base; sg != nil; sg = sg.next {
            if i < len(sg.ele) {
                return sg.ele[i]
            }
            i -= len(sg.ele)
        }
    }
    
    panic("index out of range")
}


func (v vList) cons(a vEle) vList {
    if v.base == nil {
        return vList{base: &vSeg{ele: []vEle{a}}}
    }
    if v.offset == 0 {
        l2 := len(v.base.ele) * 2 
        ele := make([]vEle, l2)
        ele[l2-1] = a
        return vList{&vSeg{v.base, ele}, l2 - 1}
    }
    v.offset--
    v.base.ele[v.offset] = a
    return v
}   



func (v vList) cdr() vList {
    if v.base == nil {
        
        panic("cdr on empty vList")
    }
    v.offset++
    if v.offset < len(v.base.ele) {
        return v
    }
    return vList{v.base.next, 0}
}


func (v vList) length() int {
    if v.base == nil {
        return 0
    }
    return len(v.base.ele)*2 - v.offset - 1
}


func (v vList) String() string {
    if v.base == nil {
        return "[]"
    }
    r := fmt.Sprintf("[%v", v.base.ele[v.offset])
    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
        for _, e := range sl {
            r = fmt.Sprintf("%s %v", r, e)
        }
        sg = sg.next
        if sg == nil {
            break
        }
        sl = sg.ele
    }
    return r + "]"
}


func (v vList) printStructure() {
    fmt.Println("offset:", v.offset)
    for sg := v.base; sg != nil; sg = sg.next {
        fmt.Printf("  %q\n", sg.ele) 
    }
    fmt.Println()
}


func main() {
    var v vList
    fmt.Println("zero value for type.  empty vList:", v)
    v.printStructure()

    for a := '6'; a >= '1'; a-- {
        v = v.cons(vEle(a))
    }
    fmt.Println("demonstrate cons. 6 elements added:", v)
    v.printStructure()
    
    v = v.cdr()
    fmt.Println("demonstrate cdr. 1 element removed:", v)
    v.printStructure()

    fmt.Println("demonstrate length. length =", v.length())
    fmt.Println()

    fmt.Println("demonstrate element access. v[3] =", v.index(3))
    fmt.Println()

    v = v.cdr().cdr()
    fmt.Println("show cdr releasing segment. 2 elements removed:", v)
    v.printStructure()
}
Task: Entropy_Narcissist






PHP: <?php
$h  =                             0;
$s  =   file_get_contents(__FILE__);
$l  =                    strlen($s);
foreach ( count_chars($s, 1) as $c )
                               $h -=
                       ( $c / $l ) *
                  log( $c / $l, 2 );
echo                             $h;
Task: Simple turtle graphics







Python: from turtle import *

def rectangle(width, height):
    for _ in range(2):
        forward(height)
        left(90)
        forward(width)
        left(90)
 
def square(size):
    rectangle(size, size)

def triangle(size):
    for _ in range(3):
        forward(size)
        right(120)
    
def house(size):
    right(180)
    square(size)
    triangle(size)
    right(180)
    
def barchart(lst, size):
    scale = size/max(lst)
    width = size/len(lst)
    for i in lst:
        rectangle(i*scale, width)
        penup()
        forward(width)
        pendown()
    penup()
    back(size)
    pendown()
    
clearscreen()
hideturtle()
house(150)
penup()
forward(10)
pendown()
barchart([0.5, (1/3), 2, 1.3, 0.5], 200)
penup()
back(10)
pendown()
Task: Idoneal numbers







Python: 


def is_idoneal(num):
    
    for a in range(1, num):
        for b in range(a + 1, num):
            if a * b + a + b > num:
                break
            for c in range(b + 1, num):
                sum3 = a * b + b * c + a * c
                if sum3 == num:
                    return False
                if sum3 > num:
                    break
    return True


row = 0
for n in range(1, 2000):
    if is_idoneal(n):
        row += 1
        print(f'{n:5}', end='\n' if row % 13 == 0 else '')
Task: Sorensen–Dice coefficient







Python: 

from multiset import Multiset


def tokenizetext(txt):
    
    arr = []
    for wrd in txt.lower().split(' '):
        arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2]
                for i in range(len(wrd)-1)])
    return Multiset(arr)


def sorenson_dice(text1, text2):
    
    bc1, bc2 = tokenizetext(text1), tokenizetext(text2)
    return 2 * len(bc1 & bc2) / (len(bc1) + len(bc2))


with open('tasklist_sorenson.txt', 'r') as fd:
    alltasks = fd.read().split('\n')

for testtext in ['Primordial primes', 'Sunkist-Giuliani formula',
                 'Sieve of Euripides', 'Chowder numbers']:
    taskvalues = sorted([(sorenson_dice(testtext, t), t)
                        for t in alltasks], reverse=True)
    print(f'\n{testtext}:')
    for (val, task) in taskvalues[:5]:
        print(f'  {val:.6f}  {task}')
Task: Solve hanging lantern problem







Python: def getLantern(arr):
    res = 0
    for i in range(0, n):
        if arr[i] != 0:
            arr[i] -= 1
            res += getLantern(arr)
            arr[i] += 1
    if res == 0:
        res = 1
    return res

a = []
n = int(input())
for i in range(0, n):
    a.append(int(input()))
print(getLantern(a))
Task: Inconsummate numbers in base 10







Python: 


def digitalsum(num):
    
    return sum(int(d) for d in str(num))


def generate_inconsummate(max_wanted):
    
    minimum_digitsums = [(10**i, int((10**i - 1) / (9 * i)))
                         for i in range(1, 15)]
    limit = 20 * min(p[0] for p in minimum_digitsums if p[1] > max_wanted)
    arr = [1] + [0] * (limit - 1)

    for dividend in range(1, limit):
        quo, rem = divmod(dividend, digitalsum(dividend))
        if rem == 0 and quo < limit:
            arr[quo] = 1
    for j, flag in enumerate(arr):
        if flag == 0:
            yield j


for i, n in enumerate(generate_inconsummate(100000)):
    if i < 50:
        print(f'{n:6}', end='\n' if (i + 1) % 10 == 0 else '')
    elif i == 999:
        print('\nThousandth inconsummate number:', n)
    elif i == 9999:
        print('\nTen-thousanth inconsummate number:', n)
    elif i == 99999:
        print('\nHundred-thousanth inconsummate number:', n)
        break
Task: Hello world_Line printer


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

int main(){
  std::ofstream lprFile;
  lprFile.open( "/dev/lp0" );
  lprFile << "Hello World!\n";
  lprFile.close();
  return 0;
}
Task: Sutherland-Hodgman polygon clipping


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

struct vec2 {
    float x = 0.0f, y = 0.0f;

    constexpr vec2 operator+(vec2 other) const {
        return vec2{x + other.x, y + other.y};
    }

    constexpr vec2 operator-(vec2 other) const {
        return vec2{x - other.x, y - other.y};
    }
};

constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }

constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }

constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }


constexpr bool is_inside(vec2 point, vec2 a, vec2 b) {
    return (cross(a - b, point) + cross(b, a)) < 0.0f;
}


constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {
    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *
           (1.0f / cross(a1 - a2, b1 - b2));
}


std::vector<vec2> suther_land_hodgman(
    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {
    if (clip_polygon.empty() || subject_polygon.empty()) {
        return {};
    }

    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};

    vec2 p1 = clip_polygon[clip_polygon.size() - 1];

    std::vector<vec2> input;

    for (vec2 p2 : clip_polygon) {
        input.clear();
        input.insert(input.end(), ring.begin(), ring.end());
        vec2 s = input[input.size() - 1];

        ring.clear();

        for (vec2 e : input) {
            if (is_inside(e, p1, p2)) {
                if (!is_inside(s, p1, p2)) {
                    ring.push_back(intersection(p1, p2, s, e));
                }

                ring.push_back(e);
            } else if (is_inside(s, p1, p2)) {
                ring.push_back(intersection(p1, p2, s, e));
            }

            s = e;
        }

        p1 = p2;
    }

    return ring;
}

int main(int argc, char **argv) {
    
    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},
                              {350, 300}, {250, 300}, {200, 250},
                              {150, 350}, {100, 250}, {100, 200}};

    
    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};

    
    std::vector<vec2> clipped_polygon =
        suther_land_hodgman(subject_polygon, clip_polygon);

    
    std::cout << "Clipped polygon points:" << std::endl;
    for (vec2 p : clipped_polygon) {
        std::cout << "(" << p.x << ", " << p.y << ")" << std::endl;
    }

    return EXIT_SUCCESS;
}
Task: Copy a string


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

int main( ) {
   std::string original ("This is the original");
   std::string my_copy = original;
   std::cout << "This is the copy: " << my_copy << std::endl;
   original = "Now we change the original! ";
   std::cout << "my_copy still is " << my_copy << std::endl;
}
Task: Include a file


C++: 
import <iostream>;
Task: String comparison


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

template <typename T>
void demo_compare(const T &a, const T &b, const std::string &semantically) {
    std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ")
              << "exactly " << semantically << " equal." << std::endl;

    std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ")
              << semantically << "inequal." << std::endl;

    std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically
              << " ordered before " << b << '.' << std::endl;

    std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically
              << " ordered after " << b << '.' << std::endl;
}

int main(int argc, char *argv[]) {
    
    std::string a((argc > 1) ? argv[1] : "1.2.Foo");
    std::string b((argc > 2) ? argv[2] : "1.3.Bar");
    demo_compare<std::string>(a, b, "lexically");

    
    std::transform(a.begin(), a.end(), a.begin(), ::tolower);
    std::transform(b.begin(), b.end(), b.begin(), ::tolower);
    demo_compare<std::string>(a, b, "lexically");

    
    
    double numA, numB;
    std::istringstream(a) >> numA;
    std::istringstream(b) >> numB;
    demo_compare<double>(numA, numB, "numerically");
    return (a == b);
}
Task: 24 game


C++: #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;

class RPNParse
{
public:
  stack<double> stk;
  multiset<int> digits;

  void op(function<double(double,double)> f)
  {
    if(stk.size() < 2)
      throw "Improperly written expression";
    int b = stk.top(); stk.pop();
    int a = stk.top(); stk.pop();
    stk.push(f(a, b));
  }

  void parse(char c)
  {
    if(c >= '0' && c <= '9')
    {
      stk.push(c - '0');
      digits.insert(c - '0');
    }
    else if(c == '+')
      op([](double a, double b) {return a+b;});
    else if(c == '-')
      op([](double a, double b) {return a-b;});
    else if(c == '*')
      op([](double a, double b) {return a*b;});
    else if(c == '/')
      op([](double a, double b) {return a/b;});
  }

  void parse(string s)
  {
    for(int i = 0; i < s.size(); ++i)
      parse(s[i]);
  }

  double getResult()
  {
    if(stk.size() != 1)
      throw "Improperly written expression";
    return stk.top();
  }
};

int main()
{
  random_device seed;
  mt19937 engine(seed());
  uniform_int_distribution<> distribution(1, 9);
  auto rnd = bind(distribution, engine);

  multiset<int> digits;
  cout << "Make 24 with the digits: ";
  for(int i = 0; i < 4; ++i)
  {
    int n = rnd();
    cout << " " << n;
    digits.insert(n);
  }
  cout << endl;

  RPNParse parser;

  try
  {
    string input;
    getline(cin, input);
    parser.parse(input);

    if(digits != parser.digits)
      cout << "Error: Not using the given digits" << endl;
    else
    {
      double r = parser.getResult();
      cout << "Result: " << r << endl;

      if(r > 23.999 && r < 24.001)
        cout << "Good job!" << endl;
      else
        cout << "Try again." << endl;
    }
  }
  catch(char* e)
  {
    cout << "Error: " << e << endl;
  }
  return 0;
}
Task: Abbreviations, easy


C++: #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

const char* command_table =
  "Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy "
  "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
  "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
  "Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO "
  "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT "
  "READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT "
  "RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up";

class command {
public:
    command(const std::string&, size_t);
    const std::string& cmd() const { return cmd_; }
    size_t min_length() const { return min_len_; }
    bool match(const std::string&) const;
private:
    std::string cmd_;
    size_t min_len_;
};


command::command(const std::string& cmd, size_t min_len)
    : cmd_(cmd), min_len_(min_len) {}


bool command::match(const std::string& str) const {
    size_t olen = str.length();
    return olen >= min_len_ && olen <= cmd_.length()
        && cmd_.compare(0, olen, str) == 0;
}


void uppercase(std::string& str) {
    std::transform(str.begin(), str.end(), str.begin(),
        [](unsigned char c) -> unsigned char { return std::toupper(c); });
}

size_t get_min_length(const std::string& str) {
    size_t len = 0, n = str.length();
    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
        ++len;
    return len;
}

class command_list {
public:
    explicit command_list(const char*);
    const command* find_command(const std::string&) const;
private:
    std::vector<command> commands_;
};

command_list::command_list(const char* table) {
    std::vector<command> commands;
    std::istringstream is(table);
    std::string word;
    while (is >> word) {
        
        size_t len = get_min_length(word);
        
        uppercase(word);
        commands_.push_back(command(word, len));
    }
}

const command* command_list::find_command(const std::string& word) const {
    auto iter = std::find_if(commands_.begin(), commands_.end(),
        [&word](const command& cmd) { return cmd.match(word); });
    return (iter != commands_.end()) ? &*iter : nullptr;
}

std::string test(const command_list& commands, const std::string& input) {
    std::string output;
    std::istringstream is(input);
    std::string word;
    while (is >> word) {
        if (!output.empty())
            output += ' ';
        uppercase(word);
        const command* cmd_ptr = commands.find_command(word);
        if (cmd_ptr)
            output += cmd_ptr->cmd();
        else
            output += "*error*";
    }
    return output;
}

int main() {
    command_list commands(command_table);
    std::string input("riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin");
    std::string output(test(commands, input));
    std::cout << " input: " << input << '\n';
    std::cout << "output: " << output << '\n';
    return 0;
}
Task: Superellipse




Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)


func superEllipse(dc *gg.Context, n float64, a int) {
    hw := float64(dc.Width() / 2)
    hh := float64(dc.Height() / 2)

    
    y := make([]float64, a+1)
    for x := 0; x <= a; x++ {
        aa := math.Pow(float64(a), n)
        xx := math.Pow(float64(x), n)
        y[x] = math.Pow(aa-xx, 1.0/n)
    }

    
    for x := a; x >= 0; x-- {
        dc.LineTo(hw+float64(x), hh-y[x])
    }
    for x := 0; x <= a; x++ {
        dc.LineTo(hw+float64(x), hh+y[x])
    }
    for x := a; x >= 0; x-- {
        dc.LineTo(hw-float64(x), hh+y[x])
    }
    for x := 0; x <= a; x++ {
        dc.LineTo(hw-float64(x), hh-y[x])
    }

    dc.SetRGB(1, 1, 1) 
    dc.Fill()
}

func main() {
    dc := gg.NewContext(500, 500)
    dc.SetRGB(0, 0, 0) 
    dc.Clear()
    superEllipse(dc, 2.5, 200)
    dc.SavePNG("superellipse.png")
}
Task: Koch curve




Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)

var dc = gg.NewContext(512, 512)

func koch(x1, y1, x2, y2 float64, iter int) {
    angle := math.Pi / 3 
    x3 := (x1*2 + x2) / 3
    y3 := (y1*2 + y2) / 3
    x4 := (x1 + x2*2) / 3
    y4 := (y1 + y2*2) / 3
    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)
    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)
    if iter > 0 {
        iter--
        koch(x1, y1, x3, y3, iter)
        koch(x3, y3, x5, y5, iter)
        koch(x5, y5, x4, y4, iter)
        koch(x4, y4, x2, y2, iter)
    } else {
        dc.LineTo(x1, y1)
        dc.LineTo(x3, y3)
        dc.LineTo(x5, y5)
        dc.LineTo(x4, y4)
        dc.LineTo(x2, y2)
    }
}

func main() {
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    koch(100, 100, 400, 400, 4)
    dc.SetRGB(0, 0, 1) 
    dc.SetLineWidth(2)
    dc.Stroke()
    dc.SavePNG("koch.png")
}
Task: Benford's law





Java: import java.math.BigInteger;
import java.util.Locale;

public class BenfordsLaw {

    private static BigInteger[] generateFibonacci(int n) {
        BigInteger[] fib = new BigInteger[n];
        fib[0] = BigInteger.ONE;
        fib[1] = BigInteger.ONE;
        for (int i = 2; i < fib.length; i++) {
            fib[i] = fib[i - 2].add(fib[i - 1]);
        }
        return fib;
    }

    public static void main(String[] args) {
        BigInteger[] numbers = generateFibonacci(1000);

        int[] firstDigits = new int[10];
        for (BigInteger number : numbers) {
            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
        }

        for (int i = 1; i < firstDigits.length; i++) {
            System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
        }
    }
}
Task: Additive primes





Java: public class additivePrimes {

    public static void main(String[] args) {
        int additive_primes = 0;
        for (int i = 2; i < 500; i++) {
            if(isPrime(i) && isPrime(digitSum(i))){
                additive_primes++;
                System.out.print(i + " ");
            }
        }
        System.out.print("\nFound " + additive_primes + " additive primes less than 500");
    }

    static boolean isPrime(int n) {
        int counter = 1;
        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {
            return false;
        }
        while (counter * 6 - 1 <= Math.sqrt(n)) {
            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {
                return false;
            } else {
                counter++;
            }
        }
        return true;
    }

    static int digitSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }
}
Task: Inverted syntax


C++: class invertedAssign {
  int data;
public:
  invertedAssign(int data):data(data){}
  int getData(){return data;}
  void operator=(invertedAssign& other) const {
    other.data = this->data;
  }
};


#include <iostream>

int main(){
  invertedAssign a = 0;
  invertedAssign b = 42;
  std::cout << a.getData() << ' ' << b.getData() << '\n';

  b = a;

  std::cout << a.getData() << ' ' << b.getData() << '\n';
}
Task: XXXX redacted


C++: #include <iostream>

using namespace std;

string redact(const string &source, const string &word, bool partial, bool insensitive, bool overkill) {
    string temp = source;

    auto different = [insensitive](char s, char w) {
        if (insensitive) {
            return toupper(s) != toupper(w);
        } else {
            return s != w;
        }
    };

    auto isWordChar = [](char c) {
        return c == '-' || isalpha(c);
    };

    for (size_t i = 0; i < temp.length() - word.length() + 1; i++) {
        bool match = true;
        for (size_t j = 0; j < word.length(); j++) {
            if (different(temp[i + j], word[j])) {
                match = false;
                break;
            }
        }
        if (match) {
            auto beg = i;
            auto end = i + word.length();

            if (!partial) {
                if (beg > 0 && isWordChar(temp[beg - 1])) {
                    continue;
                }
                if (end < temp.length() && isWordChar(temp[end])) {
                    continue;
                }
            }
            if (overkill) {
                while (beg > 0 && isWordChar(temp[beg - 1])) {
                    beg--;
                }
                while (end < temp.length() && isWordChar(temp[end])) {
                    end++;
                }
            }

            for (size_t k = beg; k < end; k++) {
                temp[k] = 'X';
            }
        }
    }

    return temp;
}

void example(const string &source, const string &word) {
    std::cout << "Redact " << word << '\n';
    std::cout << "[w|s|n] " << redact(source, word, false, false, false) << '\n';
    std::cout << "[w|i|n] " << redact(source, word, false, true, false) << '\n';
    std::cout << "[p|s|n] " << redact(source, word, true, false, false) << '\n';
    std::cout << "[p|i|n] " << redact(source, word, true, true, false) << '\n';
    std::cout << "[p|s|o] " << redact(source, word, true, false, true) << '\n';
    std::cout << "[p|i|o] " << redact(source, word, true, true, true) << '\n';
    std::cout << '\n';
}

int main() {
    string text = "Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom";
    example(text, "Tom");
    example(text, "tom");
    return 0;
}