WeixiangYan/CodeTransOcean huggingface dataset:
Task: Montgomery reduction

C: #include <stdio.h>
#include <stdlib.h>

typedef unsigned long long ulong;

const int BASE = 2;

struct Montgomery {
    ulong m;
    ulong rrm;
    int n;
};

int bitLength(ulong v) {
    int result = 0;
    while (v > 0) {
        v >>= 1;
        result++;
    }
    return result;
}

ulong modPow(ulong b, ulong e, ulong n) {
    ulong result = 1;

    if (n == 1) {
        return 0;
    }

    b = b % n;
    while (e > 0) {
        if (e % 2 == 1) {
            result = (result * b) % n;
        }
        e >>= 1;
        b = (b * b) % n;
    }

    return result;
}

struct Montgomery makeMontgomery(ulong m) {
    struct Montgomery result;

    if (m == 0 || (m & 1) == 0) {
        fprintf(stderr, "m must be greater than zero and odd");
        exit(1);
    }

    result.m = m;
    result.n = bitLength(m);
    result.rrm = (1ULL << (result.n * 2)) % m;

    return result;
}

ulong reduce(struct Montgomery mont, ulong t) {
    ulong a = t;
    int i;

    for (i = 0; i < mont.n; i++) {
        if ((a & 1) == 1) {
            a += mont.m;
        }
        a = a >> 1;
    }

    if (a >= mont.m) {
        a -= mont.m;
    }
    return a;
}

void check(ulong x1, ulong x2, ulong m) {
    struct Montgomery mont = makeMontgomery(m);
    ulong t1 = x1 * mont.rrm;
    ulong t2 = x2 * mont.rrm;

    ulong r1 = reduce(mont, t1);
    ulong r2 = reduce(mont, t2);
    ulong r = 1ULL << mont.n;

    printf("b :  %d\n", BASE);
    printf("n :  %d\n", mont.n);
    printf("r :  %llu\n", r);
    printf("m :  %llu\n", mont.m);
    printf("t1:  %llu\n", t1);
    printf("t2:  %llu\n", t2);
    printf("r1:  %llu\n", r1);
    printf("r2:  %llu\n", r2);
    printf("\n");
    printf("Original x1       : %llu\n", x1);
    printf("Recovered from r1 : %llu\n", reduce(mont, r1));
    printf("Original x2       : %llu\n", x2);
    printf("Recovered from r2 : %llu\n", reduce(mont, r2));

    printf("\nMontgomery computation of x1 ^ x2 mod m :\n");
    ulong prod = reduce(mont, mont.rrm);
    ulong base = reduce(mont, x1 * mont.rrm);
    ulong exp = x2;
    while (bitLength(exp) > 0) {
        if ((exp & 1) == 1) {
            prod = reduce(mont, prod * base);
        }
        exp >>= 1;
        base = reduce(mont, base * base);
    }
    printf("%llu\n", reduce(mont, prod));
    printf("\nAlternate computation of x1 ^ x2 mod m :\n");
    printf("%llu\n", modPow(x1, x2, m));
}

int main() {
    check(41, 11, 1549);

    return 0;
}
Task: Play recorded sounds



C#: using System;
using System.Threading;
using System.Media;

class Program
{
    static void Main(string[] args)
    {
        
        SoundPlayer s1 = new SoundPlayer(); 
        s1.SoundLocation = file; 

        
        s1.Play();     

        
        s1.Play();
        Thread.Sleep(100);
        s1.Stop();

        
        s1.PlayLooping();
    }
}
Task: Send an unknown method call



C#: using System;

class Example
{
    public int foo(int x)
    {
        return 42 + x;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var example = new Example();
        var method = "foo";
        
        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });
        Console.WriteLine("{0}(5) = {1}", method, result);
    }
}
Task: Pandigital prime



C#: using System;
 
class Program {
  
 
  
  
 
  static void fun(char sp) {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    
    
    
 
    for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {
 
      
      
      
      var s = x.ToString();
      for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;
 
      
      
      if (x % 3 == 0) continue;
      for (int i = 1; i * i < x; ) {
        if (x % (i += 4) == 0) goto nxt;
        if (x % (i += 2) == 0) goto nxt;
      }
      sw.Stop(); Console.WriteLine("{0}..7: {1,10:n0} {2} μs", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;
      nxt: ;
    }
  }

static void Main(string[] args) {
    fun('1');
    fun('0');
  }
}
Task: Draw pixel 2





Java: 

size(640,480);

stroke(#ffff00);

ellipse(random(640),random(480),1,1);
Task: Here document





Java: package rosettacode.heredoc;
public class MainApp {
	public static void main(String[] args) {
		String hereDoc = """
				This is a multiline string.
				It includes all of this text,
				but on separate lines in the code.
				 """;
		System.out.println(hereDoc);
	}
}
Task: Function definition







Python: def multiply(x, y):
    return x * y
Task: Terminal control_Dimensions







Python: import os

def get_windows_terminal():
    from ctypes import windll, create_string_buffer
    h = windll.kernel32.GetStdHandle(-12)
    csbi = create_string_buffer(22)
    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

    
    if not res: return 80, 25 

    import struct
    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
    = struct.unpack("hhhhHhhhhhh", csbi.raw)
    width = right - left + 1
    height = bottom - top + 1

    return width, height

def get_linux_terminal():
    width = os.popen('tput cols', 'r').readline()
    height = os.popen('tput lines', 'r').readline()

    return int(width), int(height)

print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
Task: Next special primes







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True


if __name__ == '__main__':
    p = 3
    i = 2

    print("2 3", end = " ");
    while True:
        if isPrime(p + i) == 1:
            p += i
            print(p, end = " ");
        i += 2
        if p + i >= 1050:
            break
Task: Jacobi symbol







Python: def jacobi(a, n):
    if n <= 0:
        raise ValueError("'n' must be a positive integer.")
    if n % 2 == 0:
        raise ValueError("'n' must be odd.")
    a %= n
    result = 1
    while a != 0:
        while a % 2 == 0:
            a /= 2
            n_mod_8 = n % 8
            if n_mod_8 in (3, 5):
                result = -result
        a, n = n, a
        if a % 4 == 3 and n % 4 == 3:
            result = -result
        a %= n
    if n == 1:
        return result
    else:
        return 0
Task: Klarner-Rado sequence







Python: def KlarnerRado(N):
    K = [1]
    for i in range(N):
        j = K[i]
        firstadd, secondadd = 2 * j + 1, 3 * j + 1
        if firstadd < K[-1]:
            for pos in range(len(K)-1, 1, -1):
                if K[pos] < firstadd < K[pos + 1]:
                    K.insert(pos + 1, firstadd)
                    break
        elif firstadd > K[-1]:
            K.append(firstadd)
        if secondadd < K[-1]:
            for pos in range(len(K)-1, 1, -1):
                if K[pos] < secondadd < K[pos + 1]:
                    K.insert(pos + 1, secondadd)
                    break
        elif secondadd > K[-1]:
            K.append(secondadd)

    return K

kr1m = KlarnerRado(100_000)

print('First 100 Klarner-Rado sequence numbers:')
for idx, v in enumerate(kr1m[:100]):
    print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '')
for n in [1000, 10_000, 100_000]:
    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
Task: Largest palindrome product







Python: 

T=[set([(0, 0)])]

def double(it):
    for a, b in it:
        yield a, b
        yield b, a

def tails(n):
    
    if len(T)<=n:
        l = set()
        for i in range(10):
            for j in range(i, 10):
                I = i*10**(n-1)
                J = j*10**(n-1)
                it = tails(n-1)
                if I!=J: it = double(it)
                for t1, t2 in it:
                    if ((I+t1)*(J+t2)+1)%10**n == 0:
                        l.add((I+t1, J+t2))
        T.append(l)
    return T[n]

def largestPalindrome(n):
    
    m, tail = 0, n // 2
    head = n - tail
    up = 10**head
    for L in range(1, 9*10**(head-1)+1):
        
        m = 0
        sol = None
        for i in range(1, L + 1):
            lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)
            hi = int(up - (up - L)**2 / (up - i))
            for j in range(lo, hi + 1):
                I = (up-i) * 10**tail
                J = (up-j) * 10**tail
                it = tails(tail)
                if I!=J: it = double(it)
                    for t1, t2 in it:
                        val = (I + t1)*(J + t2)
                        s = str(val)
                        if s == s[::-1] and val>m:
                            sol = (I + t1, J + t2)
                            m = val

        if m:
            print("{:2d}\t{:4d}".format(n, m % 1337), sol, sol[0] * sol[1])
            return m % 1337
    return 0

if __name__ == "__main__":
    for k in range(1, 14):
        largestPalindrome(k)
Task: Magic numbers







Python: from itertools import groupby

def magic_numbers(base):
    hist = []
    n = l = i = 0
    while True:
        l += 1
        hist.extend((n + digit, l) for digit in range(-n % l, base, l))
        i += 1
        if i == len(hist):
            return hist
        n, l = hist[i]
        n *= base

mn = magic_numbers(10)
print("found", len(mn), "magic numbers")
print("the largest one is", mn[-1][0])

print("count by number of digits:")
print(*(f"{l}:{sum(1 for _ in g)}" for l, g in groupby(l for _, l in mn)))

print(end="minimally pandigital in 1..9: ")
print(*(m for m, l in mn if l == 9 == len(set(str(m)) - {"0"})))
print(end="minimally pandigital in 0..9: ")
print(*(m for m, l in mn if l == 10 == len(set(str(m)))))
Task: Factorial primes







Python: from itertools import count
from itertools import islice
from typing import Iterable
from typing import Tuple

import gmpy2


def factorials() -> Iterable[int]:
    fact = 1
    for i in count(1):
        yield fact
        fact *= i


def factorial_primes() -> Iterable[Tuple[int, int, str]]:
    for n, fact in enumerate(factorials()):
        if gmpy2.is_prime(fact - 1):
            yield (n, fact - 1, "-")
        if gmpy2.is_prime(fact + 1):
            yield (n, fact + 1, "+")


def print_factorial_primes(limit=10) -> None:
    print(f"First {limit} factorial primes.")
    for n, fact_prime, op in islice(factorial_primes(), 1, limit + 1):
        s = str(fact_prime)
        if len(s) > 40:
            s = f"{s[:20]}...{s[-20:]} ({len(s)} digits)"
        print(f"{n}! {op} 1 = {s}")


if __name__ == "__main__":
    import sys
    print_factorial_primes(int(sys.argv[1]) if len(sys.argv) > 1 else 10)
Task: Wagstaff primes







Python: 

from sympy import isprime

def wagstaff(N):
    
    pri, wcount = 1, 0
    while wcount < N:
        pri += 2
        if isprime(pri):
            wag = (2**pri + 1) // 3
            if isprime(wag):
                wcount += 1
                print(f'{wcount: 3}: {pri: 5} => ', 
                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')


wagstaff(24)
Task: Sphenic numbers







Python: 


from sympy import factorint

sphenics1m, sphenic_triplets1m = [], []

for i in range(3, 1_000_000):
    d = factorint(i)
    if len(d) == 3 and sum(d.values()) == 3:
        sphenics1m.append(i)
        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:
            sphenic_triplets1m.append(i)

print('Sphenic numbers less than 1000:')
for i, n in enumerate(sphenics1m):
    if n < 1000:
        print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '')
    else:
        break

print('\n\nSphenic triplets less than 10_000:')
for i, n in enumerate(sphenic_triplets1m):
    if n < 10_000:
        print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else '  ')
    else:
        break

print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),
      'sphenic triplets less than 1 million.')

S2HK = sphenics1m[200_000 - 1]
T5K = sphenic_triplets1m[5000 - 1]
print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')
print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
Task: Ormiston triples







Python: import textwrap

from itertools import pairwise
from typing import Iterator
from typing import List

import primesieve


def primes() -> Iterator[int]:
    it = primesieve.Iterator()
    while True:
        yield it.next_prime()


def triplewise(iterable):
    for (a, _), (b, c) in pairwise(pairwise(iterable)):
        yield a, b, c


def is_anagram(a: int, b: int, c: int) -> bool:
    return sorted(str(a)) == sorted(str(b)) == sorted(str(c))


def up_to_one_billion() -> int:
    count = 0
    for triple in triplewise(primes()):
        if is_anagram(*triple):
            count += 1
        if triple[2] >= 1_000_000_000:
            break
    return count


def up_to_ten_billion() -> int:
    count = 0
    for triple in triplewise(primes()):
        if is_anagram(*triple):
            count += 1
        if triple[2] >= 10_000_000_000:
            break
    return count


def first_25() -> List[int]:
    rv: List[int] = []
    for triple in triplewise(primes()):
        if is_anagram(*triple):
            rv.append(triple[0])
            if len(rv) >= 25:
                break
    return rv


if __name__ == "__main__":
    print("Smallest members of first 25 Ormiston triples:")
    print(textwrap.fill(" ".join(str(i) for i in first_25())), "\n")
    print(up_to_one_billion(), "Ormiston triples before 1,000,000,000")
    print(up_to_ten_billion(), "Ormiston triples before 10,000,000,000")
Task: Singly-linked list_Element removal







Python: class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None


class SLinkedList:
    def __init__(self):
        self.head = None

    def insert_first(self, insert_this):
        new_node = Node(insert_this)
        new_node.next = self.head
        self.head = new_node

    def remove_node(self, remove_this):

        
        head_val = self.head

        
        
        
        if head_val is not None:
            if head_val.data == remove_this:
                self.head = head_val.next
                return

        
        
        
        
        
        while head_val is not None:
            if head_val.data == remove_this:
                break
            prev = head_val
            head_val = head_val.next

        
        if head_val is None:
            return

        
        prev.next = head_val.next

    def print_llist(self):
        print_node = self.head
        while print_node:
            print(print_node.data),
            print_node = print_node.next

mylist = SLinkedList()
mylist.insert_first("red")
mylist.insert_first("orange")
mylist.insert_first("yellow")
mylist.insert_first("green")
print("Original list:")
mylist.print_llist()
mylist.remove_node("orange")
print("\nAfter orange is removed:")
mylist.print_llist()
Task: Riordan numbers







Python: def Riordan(N):
    a = [1, 0, 1]
    for n in range(3, N):
        a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))
    return a

rios = Riordan(10_000)

for i in range(32):
    print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '')

print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')
print(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')
Task: Iterators







Python: 
from collections import deque
from typing import Iterable
from typing import Iterator
from typing import Reversible


days = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
]


colors = deque(
    [
        "red",
        "yellow",
        "pink",
        "green",
        "purple",
        "orange",
        "blue",
    ]
)


class MyIterable:
    class MyIterator:
        def __init__(self) -> None:
            self._day = -1

        def __iter__(self):
            return self

        def __next__(self):
            if self._day >= 6:
                raise StopIteration

            self._day += 1
            return days[self._day]

    class MyReversedIterator:
        def __init__(self) -> None:
            self._day = 7

        def __iter__(self):
            return self

        def __next__(self):
            if self._day <= 0:
                raise StopIteration

            self._day -= 1
            return days[self._day]

    def __iter__(self):
        return self.MyIterator()

    def __reversed__(self):
        return self.MyReversedIterator()


def print_elements(container: Iterable[object]) -> None:
    for element in container:
        print(element, end=" ")
    print("")  


def _drop(it: Iterator[object], n: int) -> None:
    
    try:
        for _ in range(n):
            next(it)
    except StopIteration:
        pass


def print_first_fourth_fifth(container: Iterable[object]) -> None:
    
    it = iter(container)
    print(next(it), end=" ")
    _drop(it, 2)
    print(next(it), end=" ")
    print(next(it))


def print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:
    
    it = reversed(container)
    print(next(it), end=" ")
    _drop(it, 2)
    print(next(it), end=" ")
    print(next(it))


def main() -> None:
    my_iterable = MyIterable()

    print("All elements:")
    print_elements(days)
    print_elements(colors)
    print_elements(my_iterable)

    print("\nFirst, fourth, fifth:")
    print_first_fourth_fifth(days)
    print_first_fourth_fifth(colors)
    print_first_fourth_fifth(my_iterable)

    print("\nLast, fourth to last, fifth to last:")
    print_reversed_first_fourth_fifth(days)
    print_reversed_first_fourth_fifth(colors)
    print_reversed_first_fourth_fifth(my_iterable)


if __name__ == "__main__":
    main()
Task: Separate the house number from the street name







Python: Plataanstraat 5           split as (Plataanstraat, 5)
Straat 12                 split as (Straat, 12)
Straat 12 II              split as (Straat, 12 II)
Dr. J. Straat   12        split as (Dr. J. Straat  , 12)
Dr. J. Straat 12 a        split as (Dr. J. Straat, 12 a)
Dr. J. Straat 12-14       split as (Dr. J. Straat, 12-14)
Laan 1940 – 1945 37       split as (Laan 1940 – 1945, 37)
Plein 1940 2              split as (Plein 1940, 2)
1213-laan 11              split as (1213-laan, 11)
16 april 1944 Pad 1       split as (16 april 1944 Pad, 1)
1e Kruisweg 36            split as (1e Kruisweg, 36)
Laan 1940-’45 66          split as (Laan 1940-’45, 66)
Laan ’40-’45              split as (Laan ’40-’45,)
Langeloërduinen 3 46      split as (Langeloërduinen, 3 46)
Marienwaerdt 2e Dreef 2   split as (Marienwaerdt 2e Dreef, 2)
Provincialeweg N205 1     split as (Provincialeweg N205, 1)
Rivium 2e Straat 59.      split as (Rivium 2e Straat, 59.)
Nieuwe gracht 20rd        split as (Nieuwe gracht, 20rd)
Nieuwe gracht 20rd 2      split as (Nieuwe gracht, 20rd 2)
Nieuwe gracht 20zw /2     split as (Nieuwe gracht, 20zw /2)
Nieuwe gracht 20zw/3      split as (Nieuwe gracht, 20zw/3)
Nieuwe gracht 20 zw/4     split as (Nieuwe gracht, 20 zw/4)
Bahnhofstr. 4             split as (Bahnhofstr., 4)
Wertstr. 10               split as (Wertstr., 10)
Lindenhof 1               split as (Lindenhof, 1)
Nordesch 20               split as (Nordesch, 20)
Weilstr. 6                split as (Weilstr., 6)
Harthauer Weg 2           split as (Harthauer Weg, 2)
Mainaustr. 49             split as (Mainaustr., 49)
August-Horch-Str. 3       split as (August-Horch-Str., 3)
Marktplatz 31             split as (Marktplatz, 31)
Schmidener Weg 3          split as (Schmidener Weg, 3)
Karl-Weysser-Str. 6       split as (Karl-Weysser-Str., 6)''')
Task: Sum data type





Java: import java.util.Arrays;

public class SumDataType {

    public static void main(String[] args) {
        for ( ObjectStore<?> e : Arrays.asList(new ObjectStore<String>("String"), new ObjectStore<Integer>(23), new ObjectStore<Float>(new Float(3.14159))) ) {
            System.out.println("Object : " + e);
        }
    }
    
    public static class ObjectStore<T> {
        private T object;
        public ObjectStore(T object) {
            this.object = object;
        }
        @Override
        public String toString() {
            return "value [" + object.toString() + "], type = " + object.getClass();
        }
    }

}
Task: Dice game probabilities





Java: import java.util.Random;

public class Dice{
	private static int roll(int nDice, int nSides){
		int sum = 0;
		Random rand = new Random();
		for(int i = 0; i < nDice; i++){
			sum += rand.nextInt(nSides) + 1;
		}
		return sum;
	}
	
	private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){
		int p1Wins = 0;
		for(int i = 0; i < rolls; i++){
			int p1Roll = roll(p1Dice, p1Sides);
			int p2Roll = roll(p2Dice, p2Sides);
			if(p1Roll > p2Roll) p1Wins++;
		}
		return p1Wins;
	}
	
	public static void main(String[] args){
		int p1Dice = 9; int p1Sides = 4;
		int p2Dice = 6; int p2Sides = 6;
		int rolls = 10000;
		int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
		System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
		System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
		
		System.out.println();
		
		p1Dice = 5; p1Sides = 10;
		p2Dice = 6; p2Sides = 7;
		rolls = 10000;
		p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
		System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
		System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
		
		System.out.println();
		
		p1Dice = 9; p1Sides = 4;
		p2Dice = 6; p2Sides = 6;
		rolls = 1000000;
		p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
		System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
		System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
		
		System.out.println();
		
		p1Dice = 5; p1Sides = 10;
		p2Dice = 6; p2Sides = 7;
		rolls = 1000000;
		p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
		System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
		System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
	}
}
Task: Rep-string





Java: public class RepString {

    static final String[] input = {"1001110011", "1110111011", "0010010010",
        "1010101010", "1111111111", "0100101101", "0100100", "101", "11",
        "00", "1", "0100101"};

    public static void main(String[] args) {
        for (String s : input)
            System.out.printf("%s : %s%n", s, repString(s));
    }

    static String repString(String s) {
        int len = s.length();
        outer:
        for (int part = len / 2; part > 0; part--) {
            int tail = len % part;
            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))
                continue;
            for (int j = 0; j < len / part - 1; j++) {
                int a = j * part;
                int b = (j + 1) * part;
                int c = (j + 2) * part;
                if (!s.substring(a, b).equals(s.substring(b, c)))
                    continue outer;
            }
            return s.substring(0, part);
        }
        return "none";
    }
}
Task: Mutex





Java: import java.util.concurrent.Semaphore;

public class VolatileClass{
   public Semaphore mutex = new Semaphore(1); 
                                              
   public void needsToBeSynched(){
      
   }
   
}
Task: Koch curve





Java: int l = 300;

void 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 (int i = 1; i <= 3; i++) {
    kcurve(0, l);
    rotate(radians(120));
    translate(-l, 0);
  }
}

void kcurve(float x1, float x2) {
  float s = (x2-x1)/3;
  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: Comments





Java: 
Int i = 0;