WeixiangYan/CodeTransOcean huggingface dataset:
Task: Successive prime differences







Python: 
from sympy import Sieve

def nsuccprimes(count, mx):
    "return tuple of <count> successive primes <= mx (generator)"
    sieve = Sieve()
    sieve.extend(mx)
    primes = sieve._list
    return zip(*(primes[n:] for n in range(count)))

def check_value_diffs(diffs, values):
    "Differences between successive values given by successive items in diffs?"
    return all(v[1] - v[0] == d 
               for d, v in zip(diffs, zip(values, values[1:])))

def successive_primes(offsets=(2, ), primes_max=1_000_000):
    return (sp for sp in nsuccprimes(len(offsets) + 1, primes_max) 
            if check_value_diffs(offsets, sp))

if __name__ == '__main__':
    for offsets, mx in [((2,),      1_000_000), 
                        ((1,),      1_000_000),
                        ((2, 2),    1_000_000),
                        ((2, 4),    1_000_000),
                        ((4, 2),    1_000_000),
                        ((6, 4, 2), 1_000_000),
                       ]:
        print(f"
              f"SUCCESSIVE DIFFERENCES OF {str(list(offsets))[1:-1]}")
        for count, last in enumerate(successive_primes(offsets, mx), 1):
            if count == 1:
                first = last
        print("  First group:", str(first)[1:-1])
        print("   Last group:", str(last)[1:-1])
        print("        Count:", count)
Task: Numbers whose binary and ternary digit sums are prime







Python: 



def digitSumsPrime(n):
    
    def go(bases):
        return all(
            isPrime(digitSum(b)(n))
            for b in bases
        )
    return go



def digitSum(base):
    
    def go(n):
        q, r = divmod(n, base)
        return go(q) + r if n else 0
    return go




def main():
    
    xs = [
        str(n) for n in range(1, 200)
        if digitSumsPrime(n)([2, 3])
    ]
    print(f'{len(xs)} matches in [1..199]\n')
    print(table(10)(xs))





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def isPrime(n):
    
    if n in (2, 3):
        return True
    if 2 > n or 0 == n % 2:
        return False
    if 9 > n:
        return True
    if 0 == n % 3:
        return False

    def p(x):
        return 0 == n % x or 0 == n % (2 + x)

    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))



def table(n):
    
    def go(xs):
        w = len(xs[-1])
        return '\n'.join(
            ' '.join(row) for row in chunksOf(n)([
                s.rjust(w, ' ') for s in xs
            ])
        )
    return go



if __name__ == '__main__':
    main()
Task: 10001th prime







Python: 

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

def prime(n: int) -> int:
    if n == 1:
        return 2
    p = 3
    pn = 1
    while pn < n:
        if isPrime(p):
            pn += 1
        p += 2
    return p-2

if __name__ == '__main__':
    print(prime(10001))
Task: Summarize primes







Python: 


from itertools import accumulate, chain, takewhile



def primeSums():
    
    return (
        x for x in enumerate(
            accumulate(
                chain([(0, 0)], primes()),
                lambda a, p: (p, p + a[1])
            )
        ) if isPrime(x[1][1])
    )




def main():
    
    for x in takewhile(
            lambda t: 1000 > t[1][0],
            primeSums()
    ):
        print(f'{x[0]} -> {x[1][1]}')





def isPrime(n):
    
    if n in (2, 3):
        return True
    if 2 > n or 0 == n % 2:
        return False
    if 9 > n:
        return True
    if 0 == n % 3:
        return False

    def p(x):
        return 0 == n % x or 0 == n % (2 + x)

    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))



def primes():
    
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n



if __name__ == '__main__':
    main()
Task: Largest number divisible by its digits







Python: 

from itertools import (chain, permutations)
from functools import (reduce)
from math import (gcd)



def main():
    

    
    digits = [1, 2, 3, 4, 6, 7, 8, 9]

    
    lcmDigits = reduce(lcm, digits)

    
    
    sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])

    print(
        max(
            (
                intFromDigits(x) for x
                in concatMap(permutations)(sevenDigits)
            ),
            key=lambda n: n if 0 == n % lcmDigits else 0
        )
    )



def intFromDigits(xs):
    
    return reduce(lambda a, x: a * 10 + x, xs, 0)





def concatMap(f):
    
    def go(xs):
        return chain.from_iterable(map(f, xs))
    return go



def delete(xs):
    
    def go(x):
        ys = xs.copy()
        ys.remove(x)
        return ys
    return go



def lcm(x, y):
    
    return 0 if (0 == x or 0 == y) else abs(
        y * (x // gcd(x, y))
    )



if __name__ == '__main__':
    main()
Task: Sum of the digits of n is substring of n







Python: Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)]
>>> len(x)
48
>>> for i in range(0, len(x), (stride:= 10)): print(str(x[i:i+stride])[1:-1])

0, 1, 2, 3, 4, 5, 6, 7, 8, 9
10, 20, 30, 40, 50, 60, 70, 80, 90, 100
109, 119, 129, 139, 149, 159, 169, 179, 189, 199
200, 300, 400, 500, 600, 700, 800, 900, 910, 911
912, 913, 914, 915, 916, 917, 918, 919
>>>
Task: Sattolo cycle







Python: >>> from random import randrange
>>> def sattoloCycle(items):
	for i in range(len(items) - 1, 0, -1):
		j = randrange(i)  
		items[j], items[i] = items[i], items[j]

		
>>> 
>>> for _ in range(10):
	lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
	sattoloCycle(lst)
	print(lst)

	
[5, 8, 1, 2, 6, 4, 3, 9, 10, 7]
[5, 9, 8, 10, 4, 3, 6, 2, 1, 7]
[10, 5, 8, 3, 9, 1, 4, 2, 6, 7]
[10, 5, 2, 6, 9, 7, 8, 3, 1, 4]
[7, 4, 8, 5, 10, 3, 2, 9, 1, 6]
[2, 3, 10, 9, 4, 5, 8, 1, 7, 6]
[5, 7, 4, 6, 2, 9, 3, 10, 8, 1]
[3, 10, 7, 2, 9, 5, 8, 4, 1, 6]
[2, 6, 5, 3, 9, 8, 10, 7, 1, 4]
[3, 6, 2, 5, 10, 4, 1, 9, 7, 8]
>>>
Task: Create a file on magnetic tape







Python: >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
... 
>>>
Task: Chemical calculator







Python: assert   1.008 == molar_mass('H')                  
assert   2.016 == molar_mass('H2')                 
assert  18.015 == molar_mass('H2O')                
assert  34.014 == molar_mass('H2O2')               
assert  34.014 == molar_mass('(HO)2')              
assert 142.036 == molar_mass('Na2SO4')             
assert  84.162 == molar_mass('C6H12')              
assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  
assert 176.124 == molar_mass('C6H4O2(OH)4')        
assert 386.664 == molar_mass('C27H46O')            
assert 315     == molar_mass('Uue')
Task: Sort primes from list to a list







Python: print("working...")
print("Primes are:")

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

Primes = [2,43,81,122,63,13,7,95,103]
Temp = []

for n in range(len(Primes)):
	if isprime(Primes[n]):
		Temp.append(Primes[n])

Temp.sort()
print(Temp)
print("done...")
Task: Magic squares of doubly even order







Python: def MagicSquareDoublyEven(order):
    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
    n1 = order/4
    for r in range(n1):
        r1 = sq[r][n1:-n1]
        r2 = sq[order -r - 1][n1:-n1]
        r1.reverse()
        r2.reverse()
        sq[r][n1:-n1] = r2
        sq[order -r - 1][n1:-n1] = r1
    for r in range(n1, order-n1):
        r1 = sq[r][:n1]
        r2 = sq[order -r - 1][order-n1:]
        r1.reverse()
        r2.reverse()
        sq[r][:n1] = r2
        sq[order -r - 1][order-n1:] = r1
    return sq

def printsq(s):
    n = len(s)
    bl = len(str(n**2))+1
    for i in range(n):
        print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
    print "\nMagic constant = %d"%sum(s[0])

printsq(MagicSquareDoublyEven(8))
Task: Steady squares







Python: print("working...")
print("Steady squares under 10.000 are:")
limit = 10000

for n in range(1,limit):
    nstr = str(n)
    nlen = len(nstr)
    square = str(pow(n,2))
    rn = square[-nlen:]
    if nstr == rn:
       print(str(n) + " " + str(square))

print("done...")
Task: Penta-power prime seeds







Python: from sympy import isprime

def ispentapowerprime(n):
    return all(isprime(i) for i in [n + 2, n + n + 1, n**2 + n + 1, n**3 + n + 1, n**4 + n + 1])

ppprimes = [i for i in range(10_400_000) if ispentapowerprime(i)]

for i in range(50):
    print(f'{ppprimes[i]: 11,}', end='\n' if (i + 1) % 10 == 0 else '')

for n in range(1_000_000, 10_000_001, 1_000_000):
    proot = next(filter(lambda x: x > n, ppprimes))
    print(f'The first penta-power prime seed over {n:,} is {proot:,}')
Task: Quad-power prime seeds







Python: 

from sympy import isprime


def isquadpowerprime(cand):
    
    return all(isprime(i) for i in
               [cand + cand + 1, cand**2 + cand + 1, cand**3 + cand + 1, cand**4 + cand + 1])


qpprimes = [k for k in range(10_100_000) if isquadpowerprime(k)]

for i in range(50):
    print(f'{qpprimes[i]: 9,}', end='\n' if (i + 1) % 10 == 0 else '')


for j in range(1_000_000, 10_000_001, 1_000_000):
    for p in qpprimes:
        if p > j:
            print(f'The first quad-power prime seed over {j:,} is {p:,}')
            break
Task: Honaker primes







Python: 


from pyprimesieve import primes


def digitsum(num):
    
    return sum(int(c) for c in str(num))


def generate_honaker(limit=5_000_000):
    
    honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]
    for hcount, (ppi, pri) in enumerate(honaker):
        yield hcount + 1, ppi, pri


print('First 50 Honaker primes:')
for p in generate_honaker():
    if p[0] < 51:
        print(f'{str(p):16}', end='\n' if p[0] % 5 == 0 else '')
    elif p[0] == 10_000:
        print(f'\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.')
        break
Task: Ormiston pairs







Python: 

from sympy import primerange


PRIMES1M = list(primerange(1, 1_000_000))
ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M]
ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M))
             if ASBASE10SORT[i - 1] == ASBASE10SORT[i]]

print('First 30 Ormiston pairs:')
for (i, o) in enumerate(ORMISTONS):
    if i < 30:
        print(f'({o[0] : 6} {o[1] : 6} )',
              end='\n' if (i + 1) % 5 == 0 else '  ')
    else:
        break

print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
Task: Numbers which are the cube roots of the product of their proper divisors







Python: 

from functools import reduce
from sympy import divisors


FOUND = 0
for num in range(1, 1_000_000):
    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1
    if num * num * num == divprod:
        FOUND += 1
        if FOUND <= 50:
            print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '')
        if FOUND == 500:
            print(f'\nFive hundreth: {num:,}')
        if FOUND == 5000:
            print(f'\nFive thousandth: {num:,}')
        if FOUND == 50000:
            print(f'\nFifty thousandth: {num:,}')
            break
Task: Product of min and max prime factors







Python: 


from sympy import factorint

NUM_WANTED = 100

for num in range(1, NUM_WANTED + 1):
    fac = factorint(num, multiple=True)
    product = fac[0] * fac[-1] if len(fac) > 0 else 1
    print(f'{product:5}', end='\n' if num % 10 == 0 else '')
Task: Tropical algebra overloading







Python: from numpy import Inf

class MaxTropical:
    
    def __init__(self, x=0):
        self.x = x

    def __str__(self):
        return str(self.x)

    def __add__(self, other):
        return MaxTropical(max(self.x, other.x))

    def __mul__(self, other):
        return MaxTropical(self.x + other.x)

    def __pow__(self, other):
        assert other.x // 1 == other.x and other.x > 0, "Invalid Operation" 
        return MaxTropical(self.x * other.x)

    def __eq__(self, other):
        return self.x == other.x


if __name__ == "__main__":
    a = MaxTropical(-2)
    b = MaxTropical(-1)
    c = MaxTropical(-0.5)
    d = MaxTropical(-0.001)
    e = MaxTropical(0)
    f = MaxTropical(0.5)
    g = MaxTropical(1)
    h = MaxTropical(1.5)
    i = MaxTropical(2)
    j = MaxTropical(5)
    k = MaxTropical(7)
    l = MaxTropical(8)
    m = MaxTropical(-Inf)

    print("2 * -2 == ", i * a)
    print("-0.001 + -Inf == ", d + m)
    print("0 * -Inf == ", e * m)
    print("1.5 + -1 == ", h + b)
    print("-0.5 * 0 == ", c * e)
    print("5**7 == ", j**k)
    print("5 * (8 + 7)) == ", j * (l + k))
    print("5 * 8 + 5 * 7 == ", j * l + j * k)
    print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
Task: Super-Poulet numbers







Python: from sympy import isprime, divisors
 
def is_super_Poulet(n):
    return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n))

spoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)]

print('The first 20 super-Poulet numbers are:', spoulets[:20])

idx1m, val1m = next((i, v) for i, v in enumerate(spoulets) if v > 1_000_000)
print(f'The first super-Poulet number over 1 million is the {idx1m}th one, which is {val1m}')
Task: Koch curve

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

#define pi M_PI

typedef struct{
	double x,y;
}point;

void kochCurve(point p1,point p2,int times){
	point p3,p4,p5;
	double theta = pi/3;
	
	if(times>0){
		p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
		p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
		
		p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
		
		kochCurve(p1,p3,times-1);
		kochCurve(p3,p4,times-1);
		kochCurve(p4,p5,times-1);
		kochCurve(p5,p2,times-1);
	}
	
	else{
		line(p1.x,p1.y,p2.x,p2.y);
	}
}

int main(int argC, char** argV)
{
	int w,h,r;
	point p1,p2;
	
	if(argC!=4){
		printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
	}
	
	else{
		w = atoi(argV[1]);
		h = atoi(argV[2]);
		r = atoi(argV[3]);
		
		initwindow(w,h,"Koch Curve");
		
		p1 = (point){10,h-10};
		p2 = (point){w-10,h-10};
		
		kochCurve(p1,p2,r);
		
		getch();
	
		closegraph();
	}
	
	return 0;
}
Task: Numbers with equal rises and falls

C: #include <stdio.h>


int riseEqFall(int num) {
    int rdigit = num % 10;
    int netHeight = 0;
    while (num /= 10) {
        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
        rdigit = num % 10;
    }
    return netHeight == 0;
}


int nextNum() {
    static int num = 0;
    do {num++;} while (!riseEqFall(num));
    return num;
}

int main(void) {
    int total, num;
    
    
    printf("The first 200 numbers are: \n");
    for (total = 0; total < 200; total++)
        printf("%d ", nextNum());
    
    
    printf("\n\nThe 10,000,000th number is: ");
    for (; total < 10000000; total++) num = nextNum();
    printf("%d\n", num);
    
    return 0;
}
Task: Changeable words

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

#define MAX_WORD_SIZE 32

typedef struct string_tag {
    size_t length;
    char str[MAX_WORD_SIZE];
} string_t;

void fatal(const char* message) {
    fprintf(stderr, "%s\n", message);
    exit(1);
}

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

void* xrealloc(void* p, size_t n) {
    void* ptr = realloc(p, n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

int hamming_distance(const string_t* str1, const string_t* str2) {
    size_t len1 = str1->length;
    size_t len2 = str2->length;
    if (len1 != len2)
        return 0;
    int count = 0;
    const char* s1 = str1->str;
    const char* s2 = str2->str;
    for (size_t i = 0; i < len1; ++i) {
        if (s1[i] != s2[i])
            ++count;
        
        if (count == 2)
            break;
    }
    return count;
}

int main(int argc, char** argv) {
    const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
    FILE* in = fopen(filename, "r");
    if (!in) {
        perror(filename);
        return EXIT_FAILURE;
    }
    char line[MAX_WORD_SIZE];
    size_t size = 0, capacity = 1024;
    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
    while (fgets(line, sizeof(line), in)) {
        if (size == capacity) {
            capacity *= 2;
            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
        }
        size_t len = strlen(line) - 1;
        if (len > 11) {
            string_t* str = &dictionary[size];
            str->length = len;
            memcpy(str->str, line, len);
            str->str[len] = '\0';
            ++size;
        }
    }
    fclose(in);
    printf("Changeable words in %s:\n", filename);
    int n = 1;
    for (size_t i = 0; i < size; ++i) {
        const string_t* str1 = &dictionary[i];
        for (size_t j = 0; j < size; ++j) {
            const string_t* str2 = &dictionary[j];
            if (i != j && hamming_distance(str1, str2) == 1)
                printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
        }
    }
    free(dictionary);
    return EXIT_SUCCESS;
}
Task: Decision tables

C: #include <stdio.h>
 
#define N_COND 3
#define COND_LEN (1 << N_COND)

struct { const char *str, *truth;}
cond[N_COND] = {
	{"Printer does not print",		"1111...."},
	{"A red light is flashing",		"11..11.."},
	{"Printer is unrecognised",		"1.1.1.1."},
},
solu[] = {
	{"Check the power cable",		"..1....."},
	{"Check the printer-computer cable",	"1.1....."},
	{"Ensure printer software is installed","1.1.1.1."},
	{"Check/replace ink",			"11..11.."},
	{"Check for paper jam",			".1.1...."},
};

int main()
{
	int q, ans, c;

	for (q = ans = c = 0; q < N_COND; q++) {
		do {
			if (c != '\n') printf("%s? ", cond[q].str);
			c = getchar();
		} while (c != 'y' && c != 'n');
		ans = (ans << 1) | (c != 'y');
	}

	if (ans == COND_LEN - 1)
		printf("\nSo, you don't have a problem then?\n");
	else {
		printf("\nSolutions:\n");
		for (q = 0; q < sizeof(solu)/sizeof(solu[0]); q++)
			if (solu[q].truth[ans] == '1')
				printf("    %s\n", solu[q].str);
	}
	return 0;
}
Task: Find words which contains more than 3 e vowels

C: #include <stdio.h>
#define SIZE 256

int check(char *word) {
    int e = 0, ok = 1;
    for(; *word && ok; word++) {
        switch(*word) {
            case 'a':
            case 'i':
            case 'o':
            case 'u': ok = 0; break;
            case 'e': e++;
        }
    }
    
    return ok && e > 3;
}
    
int main() {
    FILE *f;
    char line[SIZE];
    
    if (!(f = fopen("unixdict.txt", "r"))) {
        fprintf(stderr, "Cannot open unixdict.txt\n");
        return 1;
    }
    
    while (!feof(f)) {
        fgets(line, SIZE, f);
        if (check(line)) printf("%s", line);
    }
    
    fclose(f);
    return 0;
}
Task: Mosaic matrix

C: #include <stdio.h>

void mosaicMatrix(unsigned int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            if ((i + j) % 2 == 0) {
                printf("%s ", "1");
            } else {
                printf("%s ", "0");
            }
        }
        printf("\n");
    }
}

int main() {
    mosaicMatrix(10);
    printf("\n");
    mosaicMatrix(11);
    return 0;
}
Task: Longest substrings without repeating characters

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

struct substr {
    const char *start;
    size_t length;
};

struct substr *lswrc(const char *str) {
    size_t length = strlen(str);
    struct substr *arr = malloc(sizeof(struct substr) * (length + 1));
    if (!arr) return NULL;
  
    size_t start=0, i=0, maxStart=0, maxEnd=0, n=0;
    bool used[256] = {false};
    
    for (i=0; i<length; i++) {
        while (used[(unsigned char) str[i]]) 
            used[(unsigned char) str[start++]] = false;
        used[(unsigned char) str[i]] = true;
        if (i-start >= maxEnd-maxStart) {
            maxStart = start;
            maxEnd = i;
            size_t len = maxEnd - maxStart + 1;
            while (n>0 && arr[n-1].length < len) n--;
            arr[n].start = &str[start];
            arr[n].length = len;
            n++;
        }
    }
    
    arr[n].start = NULL;
    arr[n].length = 0;
    return realloc(arr, sizeof(struct substr) * (n+1));
}

int main() {
    char *examples[] = {"xyzyabcybdfd", "xyzyab", "zzzzz", "a", "", NULL};
    
    for (size_t i=0; examples[i]; i++) {
        printf("Original string: \"%s\"\n", examples[i]);
        printf("Longest substrings: ");
        struct substr *ls = lswrc(examples[i]);
        for (size_t j=0; ls[j].start; j++)
            printf("\"%.*s\" ", (int)ls[j].length, ls[j].start);
        printf("\n");
        free(ls);
    }
    
    return 0;
}
Task: Find words with alternating vowels and consonants

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

#define MAX_WORD_SIZE 80

bool is_vowel(char ch) {
    switch (ch) {
    case 'a': case 'A':
    case 'e': case 'E':
    case 'i': case 'I':
    case 'o': case 'O':
    case 'u': case 'U':
        return true;
    }
    return false;
}

bool alternating_vowels_and_consonants(const char* str, size_t len) {
    for (size_t i = 1; i < len; ++i) {
        if (is_vowel(str[i]) == is_vowel(str[i - 1]))
            return false;
    }
    return true;
}

int main(int argc, char** argv) {
    const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
    FILE* fp = fopen(filename, "r");
    if (!fp) {
        perror(filename);
        return EXIT_FAILURE;
    }
    char line[MAX_WORD_SIZE];
    int n = 1;
    while (fgets(line, sizeof(line), fp)) {
        size_t len = strlen(line) - 1; 
        if (len > 9 && alternating_vowels_and_consonants(line, len))
            printf("%2d: %s", n++, line);
    }
    fclose(fp);
    return EXIT_SUCCESS;
}
Task: Input_Output for lines of text

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

#define LEN 100  

int main()
{
	char **list;
	int num, i;
	
	scanf("%d",&num);
	
	list = (char**)malloc(num*sizeof(char*));
	
	for(i=0;i<num;i++)
	{
	   list[i] = (char*)malloc(LEN*sizeof(char));  
	   fflush(stdin);
	   fgets(list[i],LEN,stdin);
	} 
	
	printf("\n");
	
	for(i=0;i<num;i++)
	{
		printf("%s",list[i]);
	}
	
	return 0;
}
Task: Largest five adjacent number

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

#define DIGITS 1000
#define NUMSIZE 5

uint8_t randomDigit() {
    uint8_t d;
    do {d = rand() & 0xF;} while (d >= 10);
    return d;
}

int numberAt(uint8_t *d, int size) {
    int acc = 0;
    while (size--) acc = 10*acc + *d++;
    return acc;
}

int main() {
    uint8_t digits[DIGITS];
    int i, largest = 0;
    
    srand(time(NULL));
    
    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();
    for (i=0; i<DIGITS-NUMSIZE; i++) {
        int here = numberAt(&digits[i], NUMSIZE);
        if (here > largest) largest = here;
    }

    printf("%d\n", largest);
    return 0;
}
Task: Length of an arc between two angles

C: #define PI 3.14159265358979323846
#define ABS(x)  (x<0?-x:x)

double arc_length(double radius, double angle1, double angle2) {
    return (360 - ABS(angle2 - angle1)) * PI / 180 * radius;
}

void main()
{
    printf("%.7f\n",arc_length(10, 10, 120));
}