WeixiangYan/CodeTransOcean huggingface dataset:
Task: Harmonic series


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

using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;

class harmonic_generator {
public:
    rational next() {
        rational result = term_;
        term_ += rational(1, ++n_);
        return result;
    }
    void reset() {
        n_ = 1;
        term_ = 1;
    }
private:
    integer n_ = 1;
    rational term_ = 1;
};

int main() {
    std::cout << "First 20 harmonic numbers:\n";
    harmonic_generator hgen;
    for (int i = 1; i <= 20; ++i)
        std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
    
    rational h;
    for (int i = 1; i <= 80; ++i)
        h = hgen.next();
    std::cout << "\n100th harmonic number: " << h << "\n\n";

    int n = 1;
    hgen.reset();
    for (int i = 1; n <= 10; ++i) {
        if (hgen.next() > n)
            std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
    }
}








COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. HARMONIC.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 VARS.
          03 N           PIC 9(5) VALUE ZERO.
          03 HN          PIC 9(2)V9(12) VALUE ZERO.
          03 INT         PIC 99 VALUE ZERO.
       01 OUT-VARS.
          03 POS         PIC Z(4)9.
          03 FILLER      PIC X(3) VALUE SPACES.
          03 H-OUT       PIC Z9.9(12).

       PROCEDURE DIVISION.
       BEGIN.
           DISPLAY "First 20 harmonic numbers:"
           PERFORM SHOW-HARMONIC 20 TIMES.
           DISPLAY SPACES.
           MOVE ZERO TO N, HN.
           DISPLAY "First harmonic number to exceed whole number:"
           PERFORM EXCEED-INT 10 TIMES.
           STOP RUN.

       SHOW-HARMONIC.
           PERFORM NEXT-HARMONIC.
           MOVE HN TO H-OUT.
           DISPLAY H-OUT.

       EXCEED-INT.
           ADD 1 TO INT.
           PERFORM NEXT-HARMONIC UNTIL HN IS GREATER THAN INT.
           MOVE N TO POS.
           MOVE HN TO H-OUT.
           DISPLAY OUT-VARS.

       NEXT-HARMONIC.
           ADD 1 TO N.
           COMPUTE HN = HN + 1 / N.
Task: Smallest square that begins with n


C++: #include <iostream>

void f(int n) {
    if (n < 1) {
        return;
    }

    int i = 1;
    while (true) {
        int sq = i * i;
        while (sq > n) {
            sq /= 10;
        }
        if (sq == n) {
            printf("%3d %9d %4d\n", n, i * i, i);
            return;
        }
        i++;
    }
}

int main() {
    std::cout << "Prefix    n^2    n\n";
    for (int i = 0; i < 50; i++) {
        f(i);
    }

    return 0;
}








COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. SMALLEST-SQUARE-BEGINS-WITH-N.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 N            PIC 99.
       01 SQUARE-NO    PIC 999.
       01 SQUARE       PIC 9(5).
       01 OUT-FMT      PIC Z(4)9.

       PROCEDURE DIVISION.
       BEGIN.
           PERFORM SMALLEST-SQUARE THRU SQUARE-START-TEST
               VARYING N FROM 1 BY 1 UNTIL N IS EQUAL TO 50.
           STOP RUN.

       SMALLEST-SQUARE.
           MOVE ZERO TO SQUARE-NO.
       SQUARE-LOOP.
           ADD 1 TO SQUARE-NO.
           MULTIPLY SQUARE-NO BY SQUARE-NO GIVING SQUARE.
       SQUARE-START-TEST.
           IF SQUARE IS GREATER THAN N
               DIVIDE 10 INTO SQUARE
               GO TO SQUARE-START-TEST.
           IF SQUARE IS NOT EQUAL TO N
               GO TO SQUARE-LOOP.
           MULTIPLY SQUARE-NO BY SQUARE-NO GIVING OUT-FMT.
           DISPLAY OUT-FMT.
Task: Strange plus numbers


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

const std::vector<bool> p{
    false, false, true,  true,  false,
    true,  false, true,  false, false,
    false, true,  false, true,  false,
    false, false, true,  false
};

bool isStrange(long n) {
    if (n < 10) {
        return false;
    }
    for (; n >= 10; n /= 10) {
        if (!p[n % 10 + (n / 10) % 10]) {
            return false;
        }
    }
    return true;
}

void test(int nMin, int nMax) {
    int k = 0;

    for (long n = nMin; n <= nMax;n++) {
        if (isStrange(n)) {
            std::cout << n;
            if (++k % 10 != 0) {
                std::cout << ' ';
            } else {
                std::cout << '\n';
            }
        }
    }
}

int main() {
    test(101, 499);
    return 0;
}








COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. STRANGE-PLUS-NUMBERS.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 VARIABLES.
          03 CANDIDATE            PIC 999.
          03 DIGITS               REDEFINES CANDIDATE,
                                  PIC 9 OCCURS 3 TIMES.
          03 LEFT-PAIR            PIC 99.
             88 LEFT-PAIR-PRIME   VALUES 2, 3, 5, 7, 11, 13, 17.
          03 RIGHT-PAIR           PIC 99. 
             88 RIGHT-PAIR-PRIME  VALUES 2, 3, 5, 7, 11, 13, 17.
       01 OUT.
          03 ROW                  PIC X(40) VALUE SPACES.
          03 PTR                  PIC 99 VALUE 1.
       
       PROCEDURE DIVISION. 
       BEGIN. 
           PERFORM CHECK-STRANGE-NUMBER
           VARYING CANDIDATE FROM 100 BY 1
           UNTIL CANDIDATE IS GREATER THAN 500.
           DISPLAY ROW.
           STOP RUN.

       CHECK-STRANGE-NUMBER. 
           ADD DIGITS(1), DIGITS(2) GIVING LEFT-PAIR.
           ADD DIGITS(2), DIGITS(3) GIVING RIGHT-PAIR. 
           IF LEFT-PAIR-PRIME AND RIGHT-PAIR-PRIME,
               PERFORM WRITE-STRANGE-NUMBER.

       WRITE-STRANGE-NUMBER.
           STRING CANDIDATE DELIMITED BY SIZE INTO ROW
           WITH POINTER PTR.
           ADD 1 TO PTR.
           IF PTR IS GREATER THAN 40,
               DISPLAY ROW,
               MOVE SPACES TO ROW,
               MOVE 1 TO PTR.
Task: Minimum multiple of m where digital sum equals m


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

int digit_sum(int n) {
    int sum = 0;
    for (; n > 0; n /= 10)
        sum += n % 10;
    return sum;
}

int main() {
    for (int n = 1; n <= 70; ++n) {
        for (int m = 1;; ++m) {
            if (digit_sum(m * n) == n) {
                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' ');
                break;
            }
        }
    }
}








COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. A131382.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 VARIABLES.
          03 MAXIMUM      PIC 99 VALUE 40.
          03 N            PIC 999.
          03 M            PIC 9(9).
          03 N-TIMES-M    PIC 9(9).
          03 DIGITS       PIC 9 OCCURS 9 TIMES,
                          REDEFINES N-TIMES-M,
                          INDEXED BY D.
          03 DIGITSUM     PIC 999 VALUE ZERO.
       01 OUTFMT.
          03 FILLER       PIC XX VALUE "A(".
          03 N-OUT        PIC Z9.
          03 FILLER       PIC X(4) VALUE ") = ".
          03 M-OUT        PIC Z(8)9.
       
       PROCEDURE DIVISION.
       BEGIN.
           PERFORM CALC-A131382 VARYING N FROM 1 BY 1
           UNTIL N IS GREATER THAN MAXIMUM.
           STOP RUN.
       
       CALC-A131382.
           PERFORM FIND-LEAST-M VARYING M FROM 1 BY 1
           UNTIL DIGITSUM IS EQUAL TO N.
           SUBTRACT 1 FROM M.
           MOVE N TO N-OUT.
           MOVE M TO M-OUT.
           DISPLAY OUTFMT.
           
       FIND-LEAST-M.
           MOVE ZERO TO DIGITSUM.
           MULTIPLY N BY M GIVING N-TIMES-M.
           PERFORM ADD-DIGIT VARYING D FROM 1 BY 1
           UNTIL D IS GREATER THAN 9.
       
       ADD-DIGIT.
           ADD DIGITS(D) TO DIGITSUM.
Task: Print debugging statement


C++: #include <iostream>


#define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__)



int main() {
    DEBUG("Hello world");
    DEBUG("Some %d Things", 42);

    return 0;
}








COBOL: gcobol
      
      
      
      
       identification division.
       program-id. steptrace.

       data division.
       working-storage section.

       procedure division.
       steptrace-main.

       display "explicit line" upon syserr

    >>Ddisplay "debug line" upon syserr

       display "from " FUNCTION MODULE-ID " in " FUNCTION MODULE-SOURCE
       goback.
       end program steptrace.
Task: Special divisors


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

using uint = unsigned int;

std::vector<uint> divisors(uint n) {
    std::vector<uint> divs;
    for (uint d=1; d<=n/2; d++) {
        if (n % d == 0) divs.push_back(d);
    }
    return divs;
}

uint reverse(uint n) {
    uint r;
    for (r = 0; n; n /= 10) r = (r*10) + (n%10);
    return r;
}

bool special(uint n) {
    for (uint d : divisors(n))
        if (reverse(n) % reverse(d) != 0) return false;
    return true;
}

int main() {
    for (uint n=1, c=0; n < 200; n++) {
        if (special(n)) {
            std::cout << std::setw(4) << n;
            if (++c == 10) {
                c = 0;
                std::cout << std::endl;
            }
        }
    }
    std::cout << std::endl;
    return 0;
}








COBOL:         IDENTIFICATION DIVISION.
        PROGRAM-ID. SPECIAL-DIVISORS.
        
        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 VARIABLES.
           02 CANDIDATE         PIC 999.
           02 CAND-REV          PIC 999.
           02 REVERSE           PIC 999.
           02 REV-DIGITS        REDEFINES REVERSE PIC 9 OCCURS 3 TIMES.
           02 DIVMAX            PIC 999.
           02 DIVISOR           PIC 999.
           02 DIVRSLT           PIC 999V999.
           02 FILLER            REDEFINES DIVRSLT.
              03 FILLER         PIC 999.
              03 FILLER         PIC 999.
                 88 DIVISIBLE   VALUE 0.
           02 TEMP              PIC 9.
           02 RD                PIC 9 COMP.
           02 STATUS-FLAG       PIC X.
              88 OK             VALUE 'Y'.    
           02 SPECIAL-N         PIC ZZ9.           

        PROCEDURE DIVISION.
        BEGIN.
            PERFORM CHECK-SPECIAL-DIVISOR
                VARYING CANDIDATE FROM 1 BY 1
                UNTIL CANDIDATE IS EQUAL TO 200.
            STOP RUN.
        
        CHECK-SPECIAL-DIVISOR.
            MOVE CANDIDATE TO REVERSE.
            PERFORM REVERSE-NUMBER.
            MOVE REVERSE TO CAND-REV.
            DIVIDE CANDIDATE BY 2 GIVING DIVMAX.
            MOVE 'Y' TO STATUS-FLAG.
            PERFORM TRY-DIVISOR
                VARYING DIVISOR FROM 1 BY 1
                UNTIL DIVISOR IS GREATER THAN DIVMAX.
            IF OK
                MOVE CANDIDATE TO SPECIAL-N
                DISPLAY SPECIAL-N.
        
        TRY-DIVISOR.
            IF OK
                DIVIDE CANDIDATE BY DIVISOR GIVING DIVRSLT
                IF DIVISIBLE
                    MOVE DIVISOR TO REVERSE
                    PERFORM REVERSE-NUMBER
                    DIVIDE CAND-REV BY REVERSE GIVING DIVRSLT
                    IF NOT DIVISIBLE MOVE 'N' TO STATUS-FLAG.
        
        REVERSE-NUMBER.
            SET RD TO 1.
            INSPECT REVERSE TALLYING RD FOR LEADING '0'.
            MOVE REV-DIGITS(RD) TO TEMP.
            MOVE REV-DIGITS(3) TO REV-DIGITS(RD).
            MOVE TEMP TO REV-DIGITS(3).
Task: Pythagoras tree







Python: def setup():
    size(800, 400)
    background(255)
    stroke(0, 255, 0)
    tree(width / 2.3, height, width / 1.8, height, 10)


def tree(x1, y1, x2, y2, depth):
    if depth <= 0: return
    dx = (x2 - x1)
    dy = (y1 - y2)

    x3 = (x2 - dy)
    y3 = (y2 - dx)
    x4 = (x1 - dy)
    y4 = (y1 - dx)
    x5 = (x4 + 0.5 * (dx - dy))
    y5 = (y4 - 0.5 * (dx + dy))

    
    beginShape()
    fill(0.0, 255.0 / depth, 0.0)
    vertex(x1, y1)
    vertex(x2, y2)
    vertex(x3, y3)
    vertex(x4, y4)
    vertex(x1, y1)
    endShape()

    
    beginShape()
    fill(0.0, 255.0 / depth, 0.0)
    vertex(x3, y3)
    vertex(x4, y4)
    vertex(x5, y5)
    vertex(x3, y3)
    endShape()

    tree(x4, y4, x5, y5, depth - 1)
    tree(x5, y5, x3, y3, depth - 1)
Task: Sequence_ smallest number greater than previous term with exactly n divisors







Python: def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))


def sequence(max_n=None):
    previous = 0
    n = 0
    while True:
        n += 1
        ii = previous
        if max_n is not None:
            if n > max_n:
                break
        while True:
            ii += 1
            if len(divisors(ii)) == n:
                yield ii
                previous = ii
                break


if __name__ == '__main__':
    for item in sequence(15):
        print(item)
Task: Superellipse







Python: 


import matplotlib.pyplot as plt
from math import sin, cos, pi

def sgn(x):
	return ((x>0)-(x<0))*1

a,b,n=200,200,2.5 
na=2/n
step=100 
piece=(pi*2)/step
xp=[];yp=[]

t=0
for t1 in range(step+1):
	
	x=(abs((cos(t)))**na)*a*sgn(cos(t))
	y=(abs((sin(t)))**na)*b*sgn(sin(t))
	xp.append(x);yp.append(y)
	t+=piece

plt.plot(xp,yp) 
plt.title("Superellipse with parameter "+str(n))
plt.show()
Task: Koch curve







Python: l = 300

def setup():
    size(400, 400)
    background(0, 0, 255)
    stroke(255)
    
    translate(width / 2.0, height / 2.0)
    
    translate(-l / 2.0, l * sqrt(3) / 6.0)
    for i in range(4):
        kcurve(0, l)
        rotate(radians(120))
        translate(-l, 0)


def kcurve(x1, x2):
    s = (x2 - x1) / 3.0
    if s < 5:
        pushMatrix()
        translate(x1, 0)
        line(0, 0, s, 0)
        line(2 * s, 0, 3 * s, 0)
        translate(s, 0)
        rotate(radians(60))
        line(0, 0, s, 0)
        translate(s, 0)
        rotate(radians(-120))
        line(0, 0, s, 0)
        popMatrix()
        return

    pushMatrix()
    translate(x1, 0)
    kcurve(0, s)
    kcurve(2 * s, 3 * s)
    translate(s, 0)
    rotate(radians(60))
    kcurve(0, s)
    translate(s, 0)
    rotate(radians(-120))
    kcurve(0, s)
    popMatrix()
Task: Minimum numbers of three lists







Python: numbers1 = [5,45,23,21,67]
numbers2 = [43,22,78,46,38]
numbers3 = [9,98,12,98,53]

numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]

print(numbers)
Task: Mosaic matrix







Python: size = 9
for Row in range(size):
    for Col in range(size):
        if (Row % 2 == 1 and Col % 2 == 1) or (Row % 2 == 0 and Col % 2 == 0):
            print("1", end=" ")
        else:
            print("0", end=" ")
    print()
Task: Longest substrings without repeating characters







Python: def longest_substring(s = "xyzyab"):
    substr = [s[x:y] for x in range(len(s)) for y in range(x+1, len(s) + 1)]
    no_reps = []
    for sub in substr:
        if len(sub) == len(set(sub)) and sub not in no_reps:
            no_reps.append(sub)
    max_len = max(len(sub) for sub in no_reps) if no_reps else 0
    max_subs = [sub for sub in no_reps if len(sub) == max_len]
    return max_subs

if __name__ == '__main__':
    for s in ["xyzyabcybdfd", "xyzyab", "zzzzz", "a", "α⊆϶α϶", "",
              [1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 0]]:
        print(f"{s} => {longest_substring(s)}")
Task: Largest five adjacent number







Python: 

from random import seed,randint
from datetime import datetime

seed(str(datetime.now()))

largeNum = [randint(1,9)]

for i in range(1,1000):
    largeNum.append(randint(0,9))

maxNum,minNum = 0,99999

for i in range(0,994):
    num = int("".join(map(str,largeNum[i:i+5])))
    if num > maxNum:
        maxNum = num
    elif num < minNum:
        minNum = num

print("Largest 5-adjacent number found ", maxNum)
print("Smallest 5-adjacent number found ", minNum)
Task: Last list item







Python: 

def add_least_reduce(lis):
    
    while len(lis) > 1:
        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))
        print('Interim list:', lis)
    return lis

LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]

print(LIST, ' ==> ', add_least_reduce(LIST.copy()))
Task: Mastermind







Python: import random


def encode(correct, guess):
    output_arr = [''] * len(correct)

    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):
        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'

    return ''.join(output_arr)


def safe_int_input(prompt, min_val, max_val):
    while True:
        user_input = input(prompt)

        try:
            user_input = int(user_input)
        except ValueError:
            continue

        if min_val <= user_input <= max_val:
            return user_input


def play_game():
    print("Welcome to Mastermind.")
    print("You will need to guess a random code.")
    print("For each guess, you will receive a hint.")
    print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.")
    print()

    number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20)
    code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10)

    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]
    code = ''.join(random.choices(letters, k=code_length))
    guesses = []

    while True:
        print()
        guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip()

        if len(guess) != code_length or any([char not in letters for char in guess]):
            continue
        elif guess == code:
            print(f"\nYour guess {guess} was correct!")
            break
        else:
            guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}")

        for i_guess in guesses:
            print("------------------------------------")
            print(i_guess)
        print("------------------------------------")


if __name__ == '__main__':
    play_game()
Task: Overloaded operators


C++: 

#include <iostream>
using namespace std;

class Cuboid {
   
   private:
      double length;    
      double breadth;    
      double height;    
   
   public:
      double getVolume(void) {
         return length * breadth * height;
      }
      void setLength( double l ) {
         length = l;
      }
      void setBreadth( double b ) {
         breadth = b;
      }
      void setHeight( double h ) {
         height = h;
      }
      

      Cuboid operator +(const Cuboid& c) {
         Cuboid biggerCuboid;
         biggerCuboid.length = this->length + c.length;
         biggerCuboid.breadth = this->breadth + c.breadth;
         biggerCuboid.height = this->height + c.height;
         return biggerCuboid;
      }
      
      Cuboid operator -(const Cuboid& c) {
         Cuboid smallerCuboid;
         smallerCuboid.length = this->length - c.length;
         smallerCuboid.breadth = this->breadth - c.breadth;
         smallerCuboid.height = this->height - c.height;
         return smallerCuboid;
      }
};

int main() {
   Cuboid c1;               
   Cuboid c2;               
   Cuboid c3;               
   double volume = 0.0;    

   c1.setLength(6.0); 
   c1.setBreadth(7.0); 
   c1.setHeight(5.0);
 
   c2.setLength(12.0); 
   c2.setBreadth(13.0); 
   c2.setHeight(10.0);
 
   volume = c1.getVolume();
   std::cout << "Volume of 1st cuboid : " << volume <<endl;
 
   volume = c2.getVolume();
   std::cout << "Volume of 2nd cuboid : " << volume <<endl;

   
   c3 = c1 + c2;

   volume = c3.getVolume();
   std::cout << "Volume of 3rd cuboid after adding : " << volume <<endl;
   
   
   c3 = c1 - c2;

   volume = c3.getVolume();
   std::cout << "Volume of 3rd cuboid after subtracting : " << volume <<endl;

   return 0;
}
Task: Sieve of Pritchard



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

class Program {

    
    static List<int> PrimesUpTo(int limit, bool verbose = false) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        var members = new SortedSet<int>{ 1 };
        int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1;
        List<int> primes = new List<int>(), tl = new List<int>();
        while (prime < rtlim) {
            nl = Math.Min(prime * stp, limit);
            if (stp < limit) {
                tl.Clear(); 
                foreach (var w in members)
                    for (n = w + stp; n <= nl; n += stp) tl.Add(n);
                members.UnionWith(tl); ac += tl.Count;
            }
            stp = nl; 
            nxtpr = 5; 
            tl.Clear();
            foreach (var w in members) {
                if (nxtpr == 5 && w > prime) nxtpr = w;
                if ((n = prime * w) > nl) break; else tl.Add(n);
            }
            foreach (var itm in tl) members.Remove(itm); rc += tl.Count;
            primes.Add(prime);
            prime = prime == 2 ? 3 : nxtpr;
        }
        members.Remove(1); primes.AddRange(members); sw.Stop();
        if (verbose) Console.WriteLine("Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds);
        return primes;
    }

    static void Main(string[] args) {
        Console.WriteLine("[{0}]", string.Join(", ", PrimesUpTo(150, true)));
        PrimesUpTo(1000000, true);
    }
}
Task: Dining philosophers

C: #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>

#define N 5
const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" };
pthread_mutex_t forks[N];

#define M 5 
const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" };

#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
#define xy(x, y) printf("\033[%d;%dH", x, y)
#define clear_eol(x) print(x, 12, "\033[K")
void print(int y, int x, const char *fmt, ...)
{
	static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;
	va_list ap;
	va_start(ap, fmt);

	lock(&screen);
	xy(y + 1, x), vprintf(fmt, ap);
	xy(N + 1, 1), fflush(stdout);
	unlock(&screen);
}

void eat(int id)
{
	int f[2], ration, i; 
	f[0] = f[1] = id;

	
	f[id & 1] = (id + 1) % N;

	clear_eol(id);
	print(id, 12, "..oO (forks, need forks)");

	for (i = 0; i < 2; i++) {
		lock(forks + f[i]);
		if (!i) clear_eol(id);

		print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]);
		
		sleep(1);
	}

	for (i = 0, ration = 3 + rand() % 8; i < ration; i++)
		print(id, 24 + i * 4, "nom"), sleep(1);

	
	for (i = 0; i < 2; i++) unlock(forks + f[i]);
}

void think(int id)
{
	int i, t;
	char buf[64] = {0};

	do {
		clear_eol(id);
		sprintf(buf, "..oO (%s)", topic[t = rand() % M]);

		for (i = 0; buf[i]; i++) {
			print(id, i+12, "%c", buf[i]);
			if (i < 5) usleep(200000);
		}
		usleep(500000 + rand() % 1000000);
	} while (t);
}

void* philosophize(void *a)
{
	int id = *(int*)a;
	print(id, 1, "%10s", names[id]);
	while(1) think(id), eat(id);
}

int main()
{
	int i, id[N];
	pthread_t tid[N];

	for (i = 0; i < N; i++)
		pthread_mutex_init(forks + (id[i] = i), 0);

	for (i = 0; i < N; i++)
		pthread_create(tid + i, 0, philosophize, id + i);

	
	return pthread_join(tid[0], 0);
}
Task: Pascal's triangle_Puzzle

C: 

#include <stdio.h>
#include <math.h>

void pascal(int a, int b, int mid, int top, int* x, int* y, int* z)
{
    double ytemp = (top - 4 * (a + b)) / 7.; 
    if(fmod(ytemp, 1.) >= 0.0001)
    { 
        x = 0;
        return;
    } 
    *y = ytemp;
    *x = mid - 2 * a - *y;
    *z = *y - *x;
}
int main()
{
    int a = 11, b = 4, mid = 40, top = 151;
    int x, y, z;
    pascal(a, b, mid, top, &x, &y, &z);
    if(x != 0)
        printf("x: %d, y: %d, z: %d\n", x, y, z);
    else printf("No solution\n");

    return 0;
}
Task: Strange numbers




Go: package main

import "fmt"

func isPrime(n int) bool {
    if n < 0 {
        n = -n
    }
    return n == 2 || n == 3 || n == 5 || n == 7
}

func main() {
    count := 0
    var d []int
    fmt.Println("Strange numbers in the open interval (100, 500) are:\n")
    for i := 101; i < 500; i++ {
        d = d[:0]
        j := i
        for j > 0 {
            d = append(d, j%10)
            j /= 10
        }
        if isPrime(d[0]-d[1]) && isPrime(d[1]-d[2]) {
            fmt.Printf("%d ", i)
            count++
            if count%10 == 0 {
                fmt.Println()
            }
        }
    }
    if count%10 != 0 {
        fmt.Println()
    }
    fmt.Printf("\n%d strange numbers in all.\n", count)
}