Sexy primes

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

#define TRUE 1
#define FALSE 0

typedef unsigned char bool;

void sieve(bool *c, int limit) {
    int i, p = 3, p2;

    c[0] = TRUE;
    c[1] = TRUE;

    for (;;) {
        p2 = p * p;
        if (p2 >= limit) {
            break;
        }
        for (i = p2; i < limit; i += 2*p) {
            c[i] = TRUE;
        }
        for (;;) {
            p += 2;
            if (!c[p]) {
                break;
            }
        }
    }
}

void printHelper(const char *cat, int len, int lim, int n) {
    const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : "";
    const char *verb = (len == 1) ? "is" : "are";
    printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len);
    printf("The last %d %s:\n", n, verb);
}

void printArray(int *a, int len) {
    int i;
    printf("[");
    for (i = 0; i < len; ++i) printf("%d ", a[i]);
    printf("\b]");
}

int main() {
    int i, ix, n, lim = 1000035;
    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;
    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;
    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;
    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];
    int last_un[10];
    bool *sv = calloc(lim - 1, sizeof(bool));
    setlocale(LC_NUMERIC, "");
    sieve(sv, lim);

    for (i = 3; i < lim; i += 2) {
        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
            unsexy++;
            continue;
        }
        if (i < lim-6 && !sv[i] && !sv[i+6]) {
            pairs++;
        } else continue;

        if (i < lim-12 && !sv[i+12]) {
            trips++;
        } else continue;

        if (i < lim-18 && !sv[i+18]) {
            quads++;
        } else continue;

        if (i < lim-24 && !sv[i+24]) {
            quins++;
        }
    }
    if (pairs < lpr) lpr = pairs;
    if (trips < ltr) ltr = trips;
    if (quads < lqd) lqd = quads;
    if (quins < lqn) lqn = quins;
    if (unsexy < lun) lun = unsexy;

    for (i = 3; i < lim; i += 2) {
        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
            un++;
            if (un > unsexy - lun) {
                last_un[un + lun - 1 - unsexy] = i;
            }
            continue;
        }
        if (i < lim-6 && !sv[i] && !sv[i+6]) {
            pr++;
            if (pr > pairs - lpr) {
                ix = pr + lpr - 1 - pairs;
                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;
            }
        } else continue;

        if (i < lim-12 && !sv[i+12]) {
            tr++;
            if (tr > trips - ltr) {
                ix = tr + ltr - 1 - trips;
                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;
                last_tr[ix][2] = i + 12;
            }
        } else continue;

        if (i < lim-18 && !sv[i+18]) {
            qd++;
            if (qd > quads - lqd) {
                ix = qd + lqd - 1 - quads;
                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;
                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;
            }
        } else continue;

        if (i < lim-24 && !sv[i+24]) {
            qn++;
            if (qn > quins - lqn) {
                ix = qn + lqn - 1 - quins;
                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;
                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;
                last_qn[ix][4] = i + 24;
            }
        }
    }

    printHelper("pairs", pairs, lim, lpr);
    printf("  [");
    for (i = 0; i < lpr; ++i) {
        printArray(last_pr[i], 2);
        printf("\b] ");
    }
    printf("\b]\n\n");

    printHelper("triplets", trips, lim, ltr);
    printf("  [");
    for (i = 0; i < ltr; ++i) {
        printArray(last_tr[i], 3);
        printf("\b] ");
    }
    printf("\b]\n\n");

    printHelper("quadruplets", quads, lim, lqd);
    printf("  [");
    for (i = 0; i < lqd; ++i) {
        printArray(last_qd[i], 4);
        printf("\b] ");
    }
    printf("\b]\n\n");

    printHelper("quintuplets", quins, lim, lqn);
    printf("  [");
    for (i = 0; i < lqn; ++i) {
        printArray(last_qn[i], 5);
        printf("\b] ");
    }
    printf("\b]\n\n");

    printHelper("unsexy primes", unsexy, lim, lun);
    printf("  [");
    printArray(last_un, lun);
    printf("\b]\n");
    free(sv);
    return 0;
}

use circular_queue::CircularQueue;

fn main() {
    let max = 1000035;
    let max_group_size = 5;
    let diff = 6;
    let max_groups = 5;
    let max_unsexy = 10;

    let sieve = primal::Sieve::new(max + diff);
    let mut group_count = vec![0; max_group_size];
    let mut unsexy_count = 0;
    let mut groups = Vec::new();
    let mut unsexy_primes = CircularQueue::with_capacity(max_unsexy);

    for _ in 0..max_group_size {
        groups.push(CircularQueue::with_capacity(max_groups));
    }

    for p in sieve.primes_from(2).take_while(|x| *x < max) {
        if !sieve.is_prime(p + diff) && (p < diff + 2 || !sieve.is_prime(p - diff)) {
            unsexy_count += 1;
            unsexy_primes.push(p);
        } else {
            let mut group = Vec::new();
            group.push(p);
            for group_size in 1..max_group_size {
                let next = p + group_size * diff;
                if next >= max || !sieve.is_prime(next) {
                    break;
                }
                group.push(next);
                group_count[group_size] += 1;
                groups[group_size].push(group.clone());
            }
        }
    }

    for size in 1..max_group_size {
        println!(
            "Number of groups of size {} is {}",
            size + 1,
            group_count[size]
        );
        println!("Last {} groups of size {}:", groups[size].len(), size + 1);
        println!(
            "{}\n",
            groups[size]
                .asc_iter()
                .map(|g| format!("({})", to_string(&mut g.iter())))
                .collect::<Vec<String>>()
                .join(", ")
        );
    }
    println!("Number of unsexy primes is {}", unsexy_count);
    println!("Last {} unsexy primes:", unsexy_primes.len());
    println!("{}", to_string(&mut unsexy_primes.asc_iter()));
}

fn to_string<T: ToString>(iter: &mut dyn std::iter::Iterator<Item = T>) -> String {
    iter.map(|n| n.to_string())
        .collect::<Vec<String>>()
        .join(", ")
}


Shift list elements to left by 3

#include <stdio.h>

void lshift(int *l, size_t n) {
    int i, f;
    if (n < 2) return;
    f = l[0];
    for (i = 0; i < n-1; ++i) l[i] = l[i+1];
    l[n-1] = f;
}

int main() {
    int l[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int i;
    size_t n = 9;
    printf("Original list     : ");
    for (i = 0; i < n; ++i) printf("%d ", l[i]);
    printf("\nShifted left by 3 : ");
    for (i = 0; i < 3; ++i) lshift(l, n);
    for (i = 0; i < n; ++i) printf("%d ", l[i]);
    printf("\n");
    return 0;
}


Sierpinski pentagon

#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>

#define pi M_PI

int main(){

	time_t t;
	double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
	int i,iter,choice,numSides;

	printf("Enter number of sides : ");
	scanf("%d",&numSides);

	printf("Enter polygon side length : ");
	scanf("%lf",&side);

	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	initwindow(windowSide,windowSide,"Polygon Chaos");

	vertices = (double**)malloc(numSides*sizeof(double*));

	for(i=0;i<numSides;i++){
		vertices[i] = (double*)malloc(2 * sizeof(double));

		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
		sumX+= vertices[i][0];
		sumY+= vertices[i][1];
		putpixel(vertices[i][0],vertices[i][1],15);
	}

	srand((unsigned)time(&t));

	seedX = sumX/numSides;
	seedY = sumY/numSides;

	putpixel(seedX,seedY,15);

	for(i=0;i<iter;i++){
		choice = rand()%numSides;

		seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
		seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);

		putpixel(seedX,seedY,15);
	}

	free(vertices);

	getch();

	closegraph();

	return 0;
}

fn sierpinski_pentagon(
    mut document: svg::Document,
    mut x: f64,
    mut y: f64,
    mut side: f64,
    order: usize,
) -> svg::Document {
    use std::f64::consts::PI;
    use svg::node::element::Polygon;

    let degrees72 = 0.4 * PI;
    let mut angle = 3.0 * degrees72;
    let scale_factor = 1.0 / (2.0 + degrees72.cos() * 2.0);

    if order == 1 {
        let mut points = Vec::new();
        points.push((x, y));
        for _ in 0..5 {
            x += angle.cos() * side;
            y -= angle.sin() * side;
            angle += degrees72;
            points.push((x, y));
        }
        let polygon = Polygon::new()
            .set("fill", "blue")
            .set("stroke", "black")
            .set("stroke-width", "1")
            .set("points", points);
        document = document.add(polygon);
    } else {
        side *= scale_factor;
        let distance = side + side * degrees72.cos() * 2.0;
        for _ in 0..5 {
            x += angle.cos() * distance;
            y -= angle.sin() * distance;
            angle += degrees72;
            document = sierpinski_pentagon(document, x, y, side, order - 1);
        }
    }
    document
}

fn write_sierpinski_pentagon(file: &str, size: usize, order: usize) -> std::io::Result<()> {
    use std::f64::consts::PI;
    use svg::node::element::Rectangle;

    let margin = 5.0;
    let radius = (size as f64) / 2.0 - 2.0 * margin;
    let side = radius * (0.2 * PI).sin() * 2.0;
    let height = side * ((0.2 * PI).sin() + (0.4 * PI).sin());
    let x = (size as f64) / 2.0;
    let y = (size as f64 - height) / 2.0;

    let rect = Rectangle::new()
        .set("width", "100%")
        .set("height", "100%")
        .set("fill", "white");

    let mut document = svg::Document::new()
        .set("width", size)
        .set("height", size)
        .add(rect);

    document = sierpinski_pentagon(document, x, y, side, order);
    svg::save(file, &document)
}

fn main() {
    write_sierpinski_pentagon("sierpinski_pentagon.svg", 600, 5).unwrap();
}


Sierpinski triangle_Graphical

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

long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;

void sc_up()
{
	scale *= 2; x *= 2; y *= 2;
	cscale *= 3;
}

void h_rgb(long long x, long long y)
{
	rgb *p = &pix[y][x];

#	define SAT 1
	double h = 6.0 * clen / cscale;
	double VAL = 1;
	double c = SAT * VAL;
	double X = c * (1 - fabs(fmod(h, 2) - 1));

	switch((int)h) {
	case 0: p->r += c; p->g += X; return;
	case 1:	p->r += X; p->g += c; return;
	case 2: p->g += c; p->b += X; return;
	case 3: p->g += X; p->b += c; return;
	case 4: p->r += X; p->b += c; return;
	default:
		p->r += c; p->b += X;
	}
}

void iter_string(const char * str, int d)
{
	long long len;
	while (*str != '\0') {
		switch(*(str++)) {
		case 'X':
			if (d)	iter_string("XHXVX", d - 1);
			else{
				clen ++;
				h_rgb(x/scale, y/scale);
				x += dx;
				y -= dy;
			}
			continue;
		case 'V':
			len = 1LLU << d;
			while (len--) {
				clen ++;
				h_rgb(x/scale, y/scale);
				y += dy;
			}
			continue;
		case 'H':
			len = 1LLU << d;
			while(len --) {
				clen ++;
				h_rgb(x/scale, y/scale);
				x -= dx;
			}
			continue;
		}
	}
}

void sierp(long leng, int depth)
{
	long i;
	long h = leng + 20, w = leng + 20;

	rgb *buf = malloc(sizeof(rgb) * w * h);
	pix = malloc(sizeof(rgb *) * h);
	for (i = 0; i < h; i++)
		pix[i] = buf + w * i;
	memset(buf, 0, sizeof(rgb) * w * h);

	x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;
	for (i = 0; i < depth; i++) sc_up();
	iter_string("VXH", depth);

	unsigned char *fpix = malloc(w * h * 3);
	double maxv = 0, *dbuf = (double*)buf;

	for (i = 3 * w * h - 1; i >= 0; i--)
		if (dbuf[i] > maxv) maxv = dbuf[i];
	for (i = 3 * h * w - 1; i >= 0; i--)
		fpix[i] = 255 * dbuf[i] / maxv;

	printf("P6\n%ld %ld\n255\n", w, h);
	fflush(stdout);
	fwrite(fpix, h * w * 3, 1, stdout);
}

int main(int c, char ** v)
{
	int size, depth;

	depth  = (c > 1) ? atoi(v[1]) : 10;
	size = 1 << depth;

	fprintf(stderr, "size: %d depth: %d\n", size, depth);
	sierp(size, depth + 2);

	return 0;
}

const SQRT3_2: f64 = 0.86602540378444;

fn sierpinski_triangle(
    mut document: svg::Document,
    mut x: f64,
    mut y: f64,
    mut side: f64,
    order: usize,
) -> svg::Document {
    use svg::node::element::Polygon;

    if order == 1 {
        let mut points = Vec::new();
        points.push((x, y));
        y += side * SQRT3_2;
        x -= side * 0.5;
        points.push((x, y));
        x += side;
        points.push((x, y));
        let polygon = Polygon::new()
            .set("fill", "black")
            .set("stroke", "none")
            .set("points", points);
        document = document.add(polygon);
    } else {
        side *= 0.5;
        document = sierpinski_triangle(document, x, y, side, order - 1);
        y += side * SQRT3_2;
        x -= side * 0.5;
        document = sierpinski_triangle(document, x, y, side, order - 1);
        x += side;
        document = sierpinski_triangle(document, x, y, side, order - 1);
    }
    document
}

fn write_sierpinski_triangle(file: &str, size: usize, order: usize) -> std::io::Result<()> {
    use svg::node::element::Rectangle;

    let margin = 20.0;
    let side = (size as f64) - 2.0 * margin;
    let y = 0.5 * ((size as f64) - SQRT3_2 * side);
    let x = margin + side * 0.5;

    let rect = Rectangle::new()
        .set("width", "100%")
        .set("height", "100%")
        .set("fill", "white");

    let mut document = svg::Document::new()
        .set("width", size)
        .set("height", size)
        .add(rect);

    document = sierpinski_triangle(document, x, y, side, order);
    svg::save(file, &document)
}

fn main() {
    write_sierpinski_triangle("sierpinski_triangle.svg", 600, 8).unwrap();
}


Simulate input_Keyboard

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

int main(int argc, char *argv[])
{
  Display *dpy;
  Window win;
  GC gc;
  int scr;
  Atom WM_DELETE_WINDOW;
  XEvent ev;
  XEvent ev2;
  KeySym keysym;
  int loop;

  dpy = XOpenDisplay(NULL);
  if (dpy == NULL) {
    fputs("Cannot open display", stderr);
    exit(1);
  }
  scr = XDefaultScreen(dpy);

  win = XCreateSimpleWindow(dpy,
          XRootWindow(dpy, scr),

          10, 10, 300, 200, 1,

          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));

  XStoreName(dpy, win, argv[0]);

  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);

  XMapWindow(dpy, win);
  XFlush(dpy);

  gc = XDefaultGC(dpy, scr);

  WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True);
  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);

  loop = 1;
  while (loop) {
    XNextEvent(dpy, &ev);
    switch (ev.type)
    {
      case Expose:

        {
          char msg1[] = "Clic in the window to generate";
          char msg2[] = "a key press event";
          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);
          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);
        }
        break;

      case ButtonPress:
        puts("ButtonPress event received");

        ev2.type = KeyPress;
        ev2.xkey.state = ShiftMask;
        ev2.xkey.keycode = 24 + (rand() % 33);
        ev2.xkey.same_screen = True;
        XSendEvent(dpy, win, True, KeyPressMask, &ev2);
        break;

      case ClientMessage:

        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)
          loop = 0;
        break;

      case KeyPress:

        puts("KeyPress event received");
        printf("> keycode: %d\n", ev.xkey.keycode);

        keysym = XLookupKeysym(&(ev.xkey), 0);
        if (keysym == XK_q ||
            keysym == XK_Escape) {
          loop = 0;
        } else {
          char buffer[] = "  ";
          int nchars = XLookupString(
                &(ev.xkey),
                buffer,
                2,
                &keysym,
                NULL );
          if (nchars == 1)
            printf("> Key '%c' pressed\n", buffer[0]);
        }
        break;
    }
  }
  XDestroyWindow(dpy, win);

  XCloseDisplay(dpy);
  return 1;
}

extern crate autopilot;
fn main() {
    autopilot::key::type_string("Hello, world!", None, None, &[]);
}


Simulate input_Mouse

#define WINVER 0x500
#include<windows.h>

int main()
{
	int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
	int x = maxX/2, y = maxY/2;
	double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;

	INPUT ip;

	ZeroMemory(&ip,sizeof(ip));

	ip.type = INPUT_MOUSE;

	while(x > 5 || y < maxY-5){

	ip.mi.mouseData = 0;
	ip.mi.dx = x * factorX;
	ip.mi.dy = y * factorY;
	ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;

	SendInput(1,&ip,sizeof(ip));
	Sleep(1);
	if(x>3)
		x-=1;
	if(y<maxY-3)
		y+=1;
	}

	ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;

	SendInput(1,&ip,sizeof(ip));

	return 0;
}

extern crate autopilot;
extern crate rand;
use rand::Rng;

const TWO_PI: f64 = std::f64::consts::PI * 2.0;
fn sine_mouse_wave() -> Result<(), autopilot::mouse::MouseError> {
    let screen_size = autopilot::screen::size();
    let scoped_height = screen_size.height / 2.0 - 10.0;
    for x in 0..screen_size.width as u64 {
        let y = (scoped_height * ((TWO_PI * x as f64) / screen_size.width).sin() + scoped_height)
            .round();
        let duration: u64 = rand::thread_rng().gen_range(1, 3);
        try!(autopilot::mouse::move_to(autopilot::geometry::Point::new(
            x as f64,
            y as f64
        )));
        std::thread::sleep(std::time::Duration::from_millis(duration));
    }
    Ok(())
}

fn main() {
    sine_mouse_wave().expect("Unable to move mouse");
}


Smarandache prime-digital sequence

#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

typedef uint32_t integer;

integer next_prime_digit_number(integer n) {
    if (n == 0)
        return 2;
    switch (n % 10) {
    case 2:
        return n + 1;
    case 3:
    case 5:
        return n + 2;
    default:
        return 2 + next_prime_digit_number(n/10) * 10;
    }
}

bool is_prime(integer n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    if (n % 5 == 0)
        return n == 5;
    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };
    integer p = 7;
    for (;;) {
        for (int i = 0; i < 8; ++i) {
            if (p * p > n)
                return true;
            if (n % p == 0)
                return false;
            p += wheel[i];
        }
    }
}

int main() {
    setlocale(LC_ALL, "");
    const integer limit = 1000000000;
    integer n = 0, max = 0;
    printf("First 25 SPDS primes:\n");
    for (int i = 0; n < limit; ) {
        n = next_prime_digit_number(n);
        if (!is_prime(n))
            continue;
        if (i < 25) {
            if (i > 0)
                printf(" ");
            printf("%'u", n);
        }
        else if (i == 25)
            printf("\n");
        ++i;
        if (i == 100)
            printf("Hundredth SPDS prime: %'u\n", n);
        else if (i == 1000)
            printf("Thousandth SPDS prime: %'u\n", n);
        else if (i == 10000)
            printf("Ten thousandth SPDS prime: %'u\n", n);
        max = n;
    }
    printf("Largest SPDS prime less than %'u: %'u\n", limit, max);
    return 0;
}

fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    if n % 5 == 0 {
        return n == 5;
    }
    let mut p = 7;
    const WHEEL: [u32; 8] = [4, 2, 4, 2, 4, 6, 2, 6];
    loop {
        for w in &WHEEL {
            if p * p > n {
                return true;
            }
            if n % p == 0 {
                return false;
            }
            p += w;
        }
    }
}

fn next_prime_digit_number(n: u32) -> u32 {
    if n == 0 {
        return 2;
    }
    match n % 10 {
        2 => n + 1,
        3 | 5 => n + 2,
        _ => 2 + next_prime_digit_number(n / 10) * 10,
    }
}

fn smarandache_prime_digital_sequence() -> impl std::iter::Iterator<Item = u32> {
    let mut n = 0;
    std::iter::from_fn(move || {
        loop {
            n = next_prime_digit_number(n);
            if is_prime(n) {
                break;
            }
        }
        Some(n)
    })
}

fn main() {
    let limit = 1000000000;
    let mut seq = smarandache_prime_digital_sequence().take_while(|x| *x < limit);
    println!("First 25 SPDS primes:");
    for i in seq.by_ref().take(25) {
        print!("{} ", i);
    }
    println!();
    if let Some(p) = seq.by_ref().nth(99 - 25) {
        println!("100th SPDS prime: {}", p);
    }
    if let Some(p) = seq.by_ref().nth(999 - 100) {
        println!("1000th SPDS prime: {}", p);
    }
    if let Some(p) = seq.by_ref().nth(9999 - 1000) {
        println!("10,000th SPDS prime: {}", p);
    }
    if let Some(p) = seq.last() {
        println!("Largest SPDS prime less than {}: {}", limit, p);
    }
}


Solve a Hidato puzzle

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int *board, *flood, *known, top = 0, w, h;

static inline int idx(int y, int x) { return y * w + x; }

int neighbors(int c, int *p)

{
	int i, j, n = 0;
	int y = c / w, x = c % w;

	for (i = y - 1; i <= y + 1; i++) {
		if (i < 0 || i >= h) continue;
		for (j = x - 1; j <= x + 1; j++)
			if (!(j < 0 || j >= w
				|| (j == x && i == y)
				|| board[ p[n] = idx(i,j) ] == -1))
				n++;
	}

	return n;
}

void flood_fill(int c)

{
	int i, n[8], nei;

	nei = neighbors(c, n);
	for (i = 0; i < nei; i++) {
		if (board[n[i]] || flood[n[i]]) continue;

		flood[n[i]] = 1;
		flood_fill(n[i]);
	}
}

int check_connectity(int lowerbound)
{
	int c;
	memset(flood, 0, sizeof(flood[0]) * w * h);
	for (c = lowerbound + 1; c <= top; c++)
		if (known[c]) flood_fill(known[c]);

	for (c = 0; c < w * h; c++)
		if (!board[c] && !flood[c])
			return 0;

	return 1;
}

void make_board(int x, int y, const char *s)
{
	int i;

	w = x, h = y;
        top = 0;
	x = w * h;

        known = calloc(x + 1, sizeof(int));
        board = calloc(x,     sizeof(int));
        flood = calloc(x,     sizeof(int));

	while (x--) board[x] = -1;

	for (y = 0; y < h; y++)
	for (x = 0; x < w; x++) {
		i = idx(y, x);

		while (isspace(*s)) s++;

		switch (*s) {
		case '_':	board[i] = 0;
		case '.':	break;
		default:
			known[ board[i] = strtol(s, 0, 10) ] = i;
			if (board[i] > top) top = board[i];
		}

		while (*s && !isspace(*s)) s++;
	}
}

void show_board(const char *s)
{
	int i, j, c;

	printf("\n%s:\n", s);

	for (i = 0; i < h; i++, putchar('\n'))
	for (j = 0; j < w; j++) {
		c = board[ idx(i, j) ];
		printf(!c ? " __" : c == -1 ? "   " : " %2d", c);
	}
}

int fill(int c, int n)
{
	int i, nei, p[8], ko, bo;

	if ((board[c] && board[c] != n) || (known[n] && known[n] != c))
		return 0;

	if (n == top) return 1;

	ko = known[n];
	bo = board[c];
	board[c] = n;

	if (check_connectity(n)) {
		nei = neighbors(c, p);
		for (i = 0; i < nei; i++)
			if (fill(p[i], n + 1))
				return 1;
	}

	board[c] = bo;
	known[n] = ko;
	return 0;
}

int main()
{
	make_board(
#define USE_E 0
#if (USE_E == 0)
		8,8,	" __ 33 35 __ __ .. .. .."
			" __ __ 24 22 __ .. .. .."
			" __ __ __ 21 __ __ .. .."
			" __ 26 __ 13 40 11 .. .."
			" 27 __ __ __  9 __  1 .."
			" .   . __ __ 18 __ __ .."
			" .  ..  .  . __  7 __ __"
			" .  .. .. ..  .  .  5 __"
#elif (USE_E == 1)
	3, 3,	" . 4 ."
		" _ 7 _"
		" 1 _ _"
#else
	50, 3,
	" 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74"
	" . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ ."
	" . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ."
#endif
	);

	show_board("Before");
	fill(known[1], 1);
	show_board("After");

	return 0;
}

use std::cmp::{max, min};
use std::fmt;
use std::ops;

#[derive(Debug, Clone, PartialEq)]
struct Board {
    cells: Vec<Vec<Option<u32>>>,
}

impl Board {
    fn new(initial_board: Vec<Vec<u32>>) -> Self {
        let b = initial_board
            .iter()
            .map(|r| {
                r.iter()
                    .map(|c| if *c == u32::MAX { None } else { Some(*c) })
                    .collect()
            })
            .collect();

        Board { cells: b }
    }

    fn height(&self) -> usize {
        self.cells.len()
    }

    fn width(&self) -> usize {
        self.cells[0].len()
    }
}
impl ops::Index<(usize, usize)> for Board {
    type Output = Option<u32>;

    fn index(&self, (y, x): (usize, usize)) -> &Self::Output {
        &self.cells[y][x]
    }
}
impl ops::IndexMut<(usize, usize)> for Board {

    fn index_mut(&mut self, (y, x): (usize, usize)) -> &mut Option<u32> {
        &mut self.cells[y][x]
    }
}

impl fmt::Display for Board {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let output: Vec<String> = self
            .cells
            .iter()
            .map(|r| {
                let mut row = String::default();

                r.iter().for_each(|c| match c {
                    None => row.push_str(format!("{:>2} ", " ").as_ref()),
                    Some(c) if c == &0 => row.push_str(format!("{:>2} ", ".").as_ref()),
                    Some(c) => row.push_str(format!("{:>2} ", c).as_ref()),
                });
                row
            })
            .collect();

        write!(f, "{}", output.join("\n"))
    }
}

#[derive(Clone, Debug)]
struct Puzzle {

    board: Board,

    fixed: Vec<u32>,

    start: (usize, usize),
}

impl Puzzle {

    fn new(initial_board: Vec<Vec<u32>>) -> Self {
        let mut s: (usize, usize) = (0, 0);
        let mut f = initial_board
            .iter()
            .enumerate()
            .flat_map(|(y, r)| r.iter().enumerate().map(move |(x, c)| (y, x, *c)))
            .filter(|(_, _, c)| (1..u32::MAX).contains(c))
            .fold(Vec::new(), |mut fixed, (y, x, c)| {
                fixed.push(c);
                if c == 1 {

                    s = (y, x)
                };
                fixed
            });

        f.sort_unstable();

        Puzzle {
            board: Board::new(initial_board),
            fixed: f,
            start: s,
        }
    }

    pub fn print_board(&self) {
        println!("{}", self.board);
    }

    fn solver(&mut self, current: (usize, usize), n: &u32, mut next: usize) -> bool {

        if n > self.fixed.last().unwrap() {
            return true;
        }

        match self.board[current] {

            None => return false,

            Some(c) if c != 0 && c != *n => return false,

            Some(c) if c == 0 && self.fixed[next] == *n => return false,

            _ => (),
        }

        let mut backup: u32 = 0;
        if self.board[current] == Some(*n) {
            backup = *n;
            next += 1;
        }

        self.board[current] = Some(*n);

        for y in (max(current.0, 1) - 1)..=min(current.0 + 1, self.board.height() - 1) {
            for x in (max(current.1, 1) - 1)..=min(current.1 + 1, self.board.width() - 1) {
                if self.solver((y, x), &(n + 1), next) {
                    return true;
                }
            }
        }

        self.board[current] = Some(backup);
        false
    }

    pub fn solve(&mut self) {
        let start = self.start;
        self.solver(start, &1, 0);
    }
}

fn main() {
    let input = vec![
        vec![0, 33, 35, 0, 0, u32::MAX, u32::MAX, u32::MAX],
        vec![0, 0, 24, 22, 0, u32::MAX, u32::MAX, u32::MAX],
        vec![0, 0, 0, 21, 0, 0, u32::MAX, u32::MAX],
        vec![0, 26, 0, 13, 40, 11, u32::MAX, u32::MAX],
        vec![27, 0, 0, 0, 9, 0, 1, u32::MAX],
        vec![u32::MAX, u32::MAX, 0, 0, 18, 0, 0, u32::MAX],
        vec![u32::MAX, u32::MAX, u32::MAX, u32::MAX, 0, 7, 0, 0],
        vec![
            u32::MAX,
            u32::MAX,
            u32::MAX,
            u32::MAX,
            u32::MAX,
            u32::MAX,
            5,
            0,
        ],
    ];

    let mut p = Puzzle::new(input);
    p.print_board();
    p.solve();
    println!("\nSolution:");
    p.print_board();
}


Sorting Algorithms_Circle Sort

#include <stdio.h>

int circle_sort_inner(int *start, int *end)
{
	int *p, *q, t, swapped;

	if (start == end) return 0;

	for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)
		if (*p > *q)
			t = *p, *p = *q, *q = t, swapped = 1;

	return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);
}

void circle_sort(int *x, int n)
{
	do {
		int i;
		for (i = 0; i < n; i++) printf("%d ", x[i]);
		putchar('\n');
	} while (circle_sort_inner(x, x + (n - 1)));
}

int main(void)
{
	int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};
	circle_sort(x, sizeof(x) / sizeof(*x));

	return 0;
}

fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize {
    if low == high {
        return swaps;
    }
    let mut lo = low;
    let mut hi = high;
    let mid = (hi - lo) / 2;
    let mut s = swaps;
    while lo < hi {
        if a[lo] > a[hi] {
            a.swap(lo, hi);
            s += 1;
        }
        lo += 1;
        hi -= 1;
    }
    if lo == hi {
        if a[lo] > a[hi + 1] {
            a.swap(lo, hi + 1);
            s += 1;
        }
    }
    s = _circle_sort(a, low, low + mid, s);
    s = _circle_sort(a, low + mid + 1, high, s);
    return s;
}

fn circle_sort<T: PartialOrd>(a: &mut [T]) {
    let len = a.len();
    loop {
        if _circle_sort(a, 0, len - 1, 0) == 0 {
            break;
        }
    }
}

fn main() {
    let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
    println!("before: {:?}", v);
    circle_sort(&mut v);
    println!("after:  {:?}", v);
}


Sorting algorithms_Cocktail sort with shifting bounds

#include <stdio.h>
#include <string.h>

void swap(char* p1, char* p2, size_t size) {
    for (; size-- > 0; ++p1, ++p2) {
        char tmp = *p1;
        *p1 = *p2;
        *p2 = tmp;
    }
}

void cocktail_shaker_sort(void* base, size_t count, size_t size,
                          int (*cmp)(const void*, const void*)) {
    char* begin = base;
    char* end = base + size * count;
    if (end == begin)
        return;
    for (end -= size; begin < end; ) {
        char* new_begin = end;
        char* new_end = begin;
        for (char* p = begin; p < end; p += size) {
            char* q = p + size;
            if (cmp(p, q) > 0) {
                swap(p, q, size);
                new_end = p;
            }
        }
        end = new_end;
        for (char* p = end; p > begin; p -= size) {
            char* q = p - size;
            if (cmp(q, p) > 0) {
                swap(p, q, size);
                new_begin = p;
            }
        }
        begin = new_begin;
    }
}

int string_compare(const void* p1, const void* p2) {
    const char* const* s1 = p1;
    const char* const* s2 = p2;
    return strcmp(*s1, *s2);
}

void print(const char** a, size_t len) {
    for (size_t i = 0; i < len; ++i)
        printf("%s ", a[i]);
    printf("\n");
}

int main() {
    const char* a[] = { "one", "two", "three", "four", "five",
        "six", "seven", "eight" };
    const size_t len = sizeof(a)/sizeof(a[0]);
    printf("before: ");
    print(a, len);
    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);
    printf("after: ");
    print(a, len);
    return 0;
}

fn cocktail_shaker_sort<T: PartialOrd>(a: &mut [T]) {
    let mut begin = 0;
    let mut end = a.len();
    if end == 0 {
        return;
    }
    end -= 1;
    while begin < end {
        let mut new_begin = end;
        let mut new_end = begin;
        for i in begin..end {
            if a[i + 1] < a[i] {
                a.swap(i, i + 1);
                new_end = i;
            }
        }
        end = new_end;
        let mut i = end;
        while i > begin {
            if a[i] < a[i - 1] {
                a.swap(i, i - 1);
                new_begin = i;
            }
            i -= 1;
        }
        begin = new_begin;
    }
}

fn main() {
    let mut v = vec![5, 1, -6, 12, 3, 13, 2, 4, 0, 15];
    println!("before: {:?}", v);
    cocktail_shaker_sort(&mut v);
    println!("after:  {:?}", v);
}


Sorting algorithms_Shell sort

fn shell_sort<T: Ord + Copy>(v: &mut [T]) {
    let mut gap = v.len() / 2;
    let len = v.len();
    while gap > 0 {
        for i in gap..len {
            let temp = v[i];
            let mut j = i;
            while j >= gap && v[j - gap] > temp {
                v[j] = v[j - gap];
                j -= gap;
            }
            v[j] = temp;
        }
        gap /= 2;
    }
}

fn main() {
    let mut numbers = [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];
    println!("Before: {:?}", numbers);
    shell_sort(&mut numbers);
    println!("After: {:?}", numbers);
}


Sorting algorithms_Stooge sort

#include <stdio.h>

#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)

void StoogeSort(int a[], int i, int j)
{
   int t;

   if (a[j] < a[i]) SWAP(a[i], a[j]);
   if (j - i > 1)
   {
       t = (j - i + 1) / 3;
       StoogeSort(a, i, j - t);
       StoogeSort(a, i + t, j);
       StoogeSort(a, i, j - t);
   }
}

int main(int argc, char *argv[])
{
   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};
   int i, n;

   n = sizeof(nums)/sizeof(int);
   StoogeSort(nums, 0, n-1);

   for(i = 0; i <= n-1; i++)
      printf("%5d", nums[i]);

   return 0;
}

fn stoogesort<E>(a: &mut [E])
    where E: PartialOrd
{
    let len = a.len();

    if a.first().unwrap() > a.last().unwrap() {
        a.swap(0, len - 1);
    }
    if len - 1 > 1 {
        let t = len / 3;
        stoogesort(&mut a[..len - 1]);
        stoogesort(&mut a[t..]);
        stoogesort(&mut a[..len - 1]);
    }
}

fn main() {
    let mut numbers = vec![1_i32, 9, 4, 7, 6, 5, 3, 2, 8];
    println!("Before: {:?}", &numbers);
    stoogesort(&mut numbers);
    println!("After: {:?}", &numbers);
}


Sparkline in unicode

#include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>

int main(int argC,char* argV[])
{
	double* arr,min,max;
	char* str;
	int i,len;
	if(argC == 1)
		printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
	else{
		arr = (double*)malloc((argC-1)*sizeof(double));
		for(i=1;i<argC;i++){
			len = strlen(argV[i]);

			if(argV[i][len-1]==','){
				str = (char*)malloc(len*sizeof(char));
				strncpy(str,argV[i],len-1);
				arr[i-1] = atof(str);
				free(str);
			}
			else
				arr[i-1] = atof(argV[i]);
			if(i==1){
				min = arr[i-1];
				max = arr[i-1];
			}
			else{
				min=(min<arr[i-1]?min:arr[i-1]);
				max=(max>arr[i-1]?max:arr[i-1]);
			}
		}

		printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min);

		setlocale(LC_ALL, "");

		for(i=1;i<argC;i++){
			printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));
		}
	}
	return 0;
}

const BARS: &'static str = "▁▂▃▄▅▆▇█";

fn print_sparkline(s: &str){
    let v = BARS.chars().collect::<Vec<char>>();
    let line: String = s.replace(",", " ").split(" ")
                            .filter(|x| !x.is_empty())
                            .map(|x| v[x.parse::<f64>().unwrap().ceil() as usize - 1])
                            .collect();
    println!("{:?}", line);
}

fn main(){
    let s1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1";
    print_sparkline(s1);
    let s2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5";
    print_sparkline(s2);
}


Spelling of ordinal numbers

#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>

typedef uint64_t integer;

typedef struct number_names_tag {
    const char* cardinal;
    const char* ordinal;
} number_names;

const number_names small[] = {
    { "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
    { "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
    { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
    { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
    { "twelve", "twelfth" }, { "thirteen", "thirteenth" },
    { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
    { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
    { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};

const number_names tens[] = {
    { "twenty", "twentieth" }, { "thirty", "thirtieth" },
    { "forty", "fortieth" }, { "fifty", "fiftieth" },
    { "sixty", "sixtieth" }, { "seventy", "seventieth" },
    { "eighty", "eightieth" }, { "ninety", "ninetieth" }
};

typedef struct named_number_tag {
    const char* cardinal;
    const char* ordinal;
    integer number;
} named_number;

const named_number named_numbers[] = {
    { "hundred", "hundredth", 100 },
    { "thousand", "thousandth", 1000 },
    { "million", "millionth", 1000000 },
    { "billion", "billionth", 1000000000 },
    { "trillion", "trillionth", 1000000000000 },
    { "quadrillion", "quadrillionth", 1000000000000000ULL },
    { "quintillion", "quintillionth", 1000000000000000000ULL }
};

const char* get_small_name(const number_names* n, bool ordinal) {
    return ordinal ? n->ordinal : n->cardinal;
}

const char* get_big_name(const named_number* n, bool ordinal) {
    return ordinal ? n->ordinal : n->cardinal;
}

const named_number* get_named_number(integer n) {
    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
    for (size_t i = 0; i + 1 < names_len; ++i) {
        if (n < named_numbers[i + 1].number)
            return &named_numbers[i];
    }
    return &named_numbers[names_len - 1];
}

void append_number_name(GString* gstr, integer n, bool ordinal) {
    if (n < 20)
        g_string_append(gstr, get_small_name(&small[n], ordinal));
    else if (n < 100) {
        if (n % 10 == 0) {
            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));
        } else {
            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));
            g_string_append_c(gstr, '-');
            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));
        }
    } else {
        const named_number* num = get_named_number(n);
        integer p = num->number;
        append_number_name(gstr, n/p, false);
        g_string_append_c(gstr, ' ');
        if (n % p == 0) {
            g_string_append(gstr, get_big_name(num, ordinal));
        } else {
            g_string_append(gstr, get_big_name(num, false));
            g_string_append_c(gstr, ' ');
            append_number_name(gstr, n % p, ordinal);
        }
    }
}

GString* number_name(integer n, bool ordinal) {
    GString* result = g_string_sized_new(8);
    append_number_name(result, n, ordinal);
    return result;
}

void test_ordinal(integer n) {
    GString* name = number_name(n, true);
    printf("%llu: %s\n", n, name->str);
    g_string_free(name, TRUE);
}

int main() {
    test_ordinal(1);
    test_ordinal(2);
    test_ordinal(3);
    test_ordinal(4);
    test_ordinal(5);
    test_ordinal(11);
    test_ordinal(15);
    test_ordinal(21);
    test_ordinal(42);
    test_ordinal(65);
    test_ordinal(98);
    test_ordinal(100);
    test_ordinal(101);
    test_ordinal(272);
    test_ordinal(300);
    test_ordinal(750);
    test_ordinal(23456);
    test_ordinal(7891233);
    test_ordinal(8007006005004003LL);
    return 0;
}

struct NumberNames {
    cardinal: &'static str,
    ordinal: &'static str,
}

impl NumberNames {
    fn get_name(&self, ordinal: bool) -> &'static str {
        if ordinal {
            return self.ordinal;
        }
        self.cardinal
    }
}

const SMALL_NAMES: [NumberNames; 20] = [
    NumberNames {
        cardinal: "zero",
        ordinal: "zeroth",
    },
    NumberNames {
        cardinal: "one",
        ordinal: "first",
    },
    NumberNames {
        cardinal: "two",
        ordinal: "second",
    },
    NumberNames {
        cardinal: "three",
        ordinal: "third",
    },
    NumberNames {
        cardinal: "four",
        ordinal: "fourth",
    },
    NumberNames {
        cardinal: "five",
        ordinal: "fifth",
    },
    NumberNames {
        cardinal: "six",
        ordinal: "sixth",
    },
    NumberNames {
        cardinal: "seven",
        ordinal: "seventh",
    },
    NumberNames {
        cardinal: "eight",
        ordinal: "eighth",
    },
    NumberNames {
        cardinal: "nine",
        ordinal: "ninth",
    },
    NumberNames {
        cardinal: "ten",
        ordinal: "tenth",
    },
    NumberNames {
        cardinal: "eleven",
        ordinal: "eleventh",
    },
    NumberNames {
        cardinal: "twelve",
        ordinal: "twelfth",
    },
    NumberNames {
        cardinal: "thirteen",
        ordinal: "thirteenth",
    },
    NumberNames {
        cardinal: "fourteen",
        ordinal: "fourteenth",
    },
    NumberNames {
        cardinal: "fifteen",
        ordinal: "fifteenth",
    },
    NumberNames {
        cardinal: "sixteen",
        ordinal: "sixteenth",
    },
    NumberNames {
        cardinal: "seventeen",
        ordinal: "seventeenth",
    },
    NumberNames {
        cardinal: "eighteen",
        ordinal: "eighteenth",
    },
    NumberNames {
        cardinal: "nineteen",
        ordinal: "nineteenth",
    },
];

const TENS: [NumberNames; 8] = [
    NumberNames {
        cardinal: "twenty",
        ordinal: "twentieth",
    },
    NumberNames {
        cardinal: "thirty",
        ordinal: "thirtieth",
    },
    NumberNames {
        cardinal: "forty",
        ordinal: "fortieth",
    },
    NumberNames {
        cardinal: "fifty",
        ordinal: "fiftieth",
    },
    NumberNames {
        cardinal: "sixty",
        ordinal: "sixtieth",
    },
    NumberNames {
        cardinal: "seventy",
        ordinal: "seventieth",
    },
    NumberNames {
        cardinal: "eighty",
        ordinal: "eightieth",
    },
    NumberNames {
        cardinal: "ninety",
        ordinal: "ninetieth",
    },
];

struct NamedNumber {
    cardinal: &'static str,
    ordinal: &'static str,
    number: usize,
}

impl NamedNumber {
    fn get_name(&self, ordinal: bool) -> &'static str {
        if ordinal {
            return self.ordinal;
        }
        self.cardinal
    }
}

const N: usize = 7;
const NAMED_NUMBERS: [NamedNumber; N] = [
    NamedNumber {
        cardinal: "hundred",
        ordinal: "hundredth",
        number: 100,
    },
    NamedNumber {
        cardinal: "thousand",
        ordinal: "thousandth",
        number: 1000,
    },
    NamedNumber {
        cardinal: "million",
        ordinal: "millionth",
        number: 1000000,
    },
    NamedNumber {
        cardinal: "billion",
        ordinal: "billionth",
        number: 1000000000,
    },
    NamedNumber {
        cardinal: "trillion",
        ordinal: "trillionth",
        number: 1000000000000,
    },
    NamedNumber {
        cardinal: "quadrillion",
        ordinal: "quadrillionth",
        number: 1000000000000000,
    },
    NamedNumber {
        cardinal: "quintillion",
        ordinal: "quintillionth",
        number: 1000000000000000000,
    },
];

fn big_name(n: usize) -> &'static NamedNumber {
    for i in 1..N {
        if n < NAMED_NUMBERS[i].number {
            return &NAMED_NUMBERS[i - 1];
        }
    }
    &NAMED_NUMBERS[N - 1]
}

fn number_name(n: usize, ordinal: bool) -> String {
    if n < 20 {
        return String::from(SMALL_NAMES[n].get_name(ordinal));
    } else if n < 100 {
        if n % 10 == 0 {
            return String::from(TENS[n / 10 - 2].get_name(ordinal));
        }
        let s1 = TENS[n / 10 - 2].get_name(false);
        let s2 = SMALL_NAMES[n % 10].get_name(ordinal);
        return format!("{}-{}", s1, s2);
    }
    let big = big_name(n);
    let mut result = number_name(n / big.number, false);
    result.push(' ');
    if n % big.number == 0 {
        result.push_str(big.get_name(ordinal));
    } else {
        result.push_str(big.get_name(false));
        result.push(' ');
        result.push_str(&number_name(n % big.number, ordinal));
    }
    result
}

fn test_ordinal(n: usize) {
    println!("{}: {}", n, number_name(n, true));
}

fn main() {
    test_ordinal(1);
    test_ordinal(2);
    test_ordinal(3);
    test_ordinal(4);
    test_ordinal(5);
    test_ordinal(11);
    test_ordinal(15);
    test_ordinal(21);
    test_ordinal(42);
    test_ordinal(65);
    test_ordinal(98);
    test_ordinal(100);
    test_ordinal(101);
    test_ordinal(272);
    test_ordinal(300);
    test_ordinal(750);
    test_ordinal(23456);
    test_ordinal(7891233);
    test_ordinal(8007006005004003);
}


Square-free integers

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

#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000

typedef unsigned char bool;
typedef unsigned long long uint64;

void sieve(uint64 limit, uint64 *primes, uint64 *length) {
    uint64 i, count, p, p2;
    bool *c = calloc(limit + 1, sizeof(bool));
    primes[0] = 2;
    count  = 1;

    p = 3;
    for (;;) {
        p2 = p * p;
        if (p2 > limit) break;
        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;
        for (;;) {
            p += 2;
            if (!c[p]) break;
        }
    }
    for (i = 3; i <= limit; i += 2) {
        if (!c[i]) primes[count++] = i;
    }
    *length = count;
    free(c);
}

void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
    uint64 *primes = malloc((limit + 1) * sizeof(uint64));
    bool add;
    sieve(limit, primes, &np);
    for (i = from; i <= to; ++i) {
        add = TRUE;
        for (j = 0; j < np; ++j) {
            p = primes[j];
            p2 = p * p;
            if (p2 > i) break;
            if (i % p2 == 0) {
                add = FALSE;
                break;
            }
        }
        if (add) results[count++] = i;
    }
    *len = count;
    free(primes);
}

int main() {
    uint64 i, *sf, len;

    sf = malloc(1000000 * sizeof(uint64));
    printf("Square-free integers from 1 to 145:\n");
    squareFree(1, 145, sf, &len);
    for (i = 0; i < len; ++i) {
        if (i > 0 && i % 20 == 0) {
            printf("\n");
        }
        printf("%4lld", sf[i]);
    }

    printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145);
    squareFree(TRILLION, TRILLION + 145, sf, &len);
    for (i = 0; i < len; ++i) {
        if (i > 0 && i % 5 == 0) {
            printf("\n");
        }
        printf("%14lld", sf[i]);
    }

    printf("\n\nNumber of square-free integers:\n");
    int a[5] = {100, 1000, 10000, 100000, 1000000};
    for (i = 0; i < 5; ++i) {
        squareFree(1, a[i], sf, &len);
        printf("  from %d to %d = %lld\n", 1, a[i], len);
    }
    free(sf);
    return 0;
}

fn square_free(mut n: usize) -> bool {
    if n & 3 == 0 {
        return false;
    }
    let mut p: usize = 3;
    while p * p <= n {
        let mut count = 0;
        while n % p == 0 {
            count += 1;
            if count > 1 {
                return false;
            }
            n /= p;
        }
        p += 2;
    }
    true
}

fn print_square_free_numbers(from: usize, to: usize) {
    println!("Square-free numbers between {} and {}:", from, to);
    let mut line = String::new();
    for i in from..=to {
        if square_free(i) {
            if !line.is_empty() {
                line.push_str(" ");
            }
            line.push_str(&i.to_string());
            if line.len() >= 80 {
                println!("{}", line);
                line.clear();
            }
        }
    }
    if !line.is_empty() {
        println!("{}", line);
    }
}

fn print_square_free_count(from: usize, to: usize) {
    let mut count = 0;
    for i in from..=to {
        if square_free(i) {
            count += 1;
        }
    }
    println!(
        "Number of square-free numbers between {} and {}: {}",
        from, to, count
    )
}

fn main() {
    print_square_free_numbers(1, 145);
    print_square_free_numbers(1000000000000, 1000000000145);
    let mut n: usize = 100;
    while n <= 1000000 {
        print_square_free_count(1, n);
        n *= 10;
    }
}


Statistics_Normal distribution

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>

#define NMAX 10000000

double mean(double* values, int n)
{
    int i;
    double s = 0;

    for ( i = 0; i < n; i++ )
        s += values[i];
    return s / n;
}

double stddev(double* values, int n)
{
    int i;
    double average = mean(values,n);
    double s = 0;

    for ( i = 0; i < n; i++ )
        s += (values[i] - average) * (values[i] - average);
    return sqrt(s / (n - 1));
}

double* generate(int n)
{
    int i;
    int m = n + n % 2;
    double* values = (double*)calloc(m,sizeof(double));
    double average, deviation;

    if ( values )
    {
        for ( i = 0; i < m; i += 2 )
        {
            double x,y,rsq,f;
            do {
                x = 2.0 * rand() / (double)RAND_MAX - 1.0;
                y = 2.0 * rand() / (double)RAND_MAX - 1.0;
                rsq = x * x + y * y;
            }while( rsq >= 1. || rsq == 0. );
            f = sqrt( -2.0 * log(rsq) / rsq );
            values[i]   = x * f;
            values[i+1] = y * f;
        }
    }
    return values;
}

void printHistogram(double* values, int n)
{
    const int width = 50;
    int max = 0;

    const double low   = -3.05;
    const double high  =  3.05;
    const double delta =  0.1;

    int i,j,k;
    int nbins = (int)((high - low) / delta);
    int* bins = (int*)calloc(nbins,sizeof(int));
    if ( bins != NULL )
    {
        for ( i = 0; i < n; i++ )
        {
            int j = (int)( (values[i] - low) / delta );
            if ( 0 <= j  &&  j < nbins )
                bins[j]++;
        }

        for ( j = 0; j < nbins; j++ )
            if ( max < bins[j] )
                max = bins[j];

        for ( j = 0; j < nbins; j++ )
        {
            printf("(%5.2f, %5.2f) |", low + j * delta, low + (j + 1) * delta );
            k = (int)( (double)width * (double)bins[j] / (double)max );
            while(k-- > 0) putchar('*');
            printf("  %-.1f%%", bins[j] * 100.0 / (double)n);
            putchar('\n');
        }

        free(bins);
    }
}

int main(void)
{
    double* seq;

    srand((unsigned int)time(NULL));

    if ( (seq = generate(NMAX)) != NULL )
    {
        printf("mean = %g, stddev = %g\n\n", mean(seq,NMAX), stddev(seq,NMAX));
        printHistogram(seq,NMAX);
        free(seq);

        printf("\n%s\n", "press enter");
        getchar();
        return EXIT_SUCCESS;
    }
    return EXIT_FAILURE;
}

use math::{histogram::Histogram, traits::ToIterator};
use rand;
use rand_distr::{Distribution, Normal};

fn mean(data: &[f32]) -> Option<f32> {
    let sum: f32 = data.iter().sum();
    Some(sum / data.len() as f32)
}

fn standard_deviation(data: &[f32]) -> Option<f32> {
    let mean = mean(data).expect("invalid mean");
    let sum = data.iter().fold(0.0, |acc, &x| acc + (x - mean).powi(2));
    Some((sum / data.len() as f32).sqrt())
}

fn print_histogram(data: &[f32], maxwidth: usize, bincount: usize, ch: char) {
    let min_val = data.iter().cloned().fold(f32::NAN, f32::min);
    let max_val = data.iter().cloned().fold(f32::NAN, f32::max);
    let histogram = Histogram::new(Some(&data.to_vec()), bincount, min_val, max_val).unwrap();
    let max_bin_value = histogram.get_counters().iter().max().unwrap();
    println!();
    for x in histogram.to_iter() {
        let (bin_min, bin_max, freq) = x;
        let bar_width = (((freq as f64) / (*max_bin_value as f64)) * (maxwidth as f64)) as u32;
        let bar_as_string = (1..bar_width).fold(String::new(), |b, _| b + &ch.to_string());
        println!(
            "({:>6},{:>6}) |{} {:.2}%",
            format!("{:.2}", bin_min),
            format!("{:.2}", bin_max),
            bar_as_string,
            (freq as f64) * 100.0 / (data.len() as f64)
        );
    }
    println!();
}

fn main() {
    let expected_mean: f32 = 0.0;
    let expected_std_deviation: f32 = 4.0;
    let normal = Normal::new(expected_mean, expected_std_deviation).unwrap();

    let mut rng = rand::thread_rng();
    for &number_of_samples in &[1000, 10_000, 1_000_000] {
        let data: Vec<f32> = normal
            .sample_iter(&mut rng)
            .take(number_of_samples)
            .collect();
        println!("Statistics for sample size {}:", number_of_samples);
        println!("\tMean: {:?}", mean(&data).expect("invalid mean"));
        println!(
            "\tStandard deviation: {:?}",
            standard_deviation(&data).expect("invalid standard deviation")
        );
        print_histogram(&data, 80, 40, '-');
    }
}


Strange unique prime triplets

#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#define LIMIT 3000

void init_sieve(unsigned char sieve[], int limit) {
    int i, j;

    for (i = 0; i < limit; i++) {
        sieve[i] = 1;
    }
    sieve[0] = 0;
    sieve[1] = 0;

    for (i = 2; i < limit; i++) {
        if (sieve[i]) {
            for (j = i + i; j < limit; j += i) {
                sieve[j] = 0;
            }
        }
    }
}

void strange_unique_prime_triplets(unsigned char sieve[], int limit, bool verbose) {
    int count = 0, sum;
    int i, j, k, n, p;
    int pi, pj, pk;

    n = 0;
    for (i = 0; i < limit; i++) {
        if (sieve[i]) {
            n++;
        }
    }

    if (verbose) {
        printf("Strange unique prime triplets < %d:\n", limit);
    }

    for (i = 0; i + 2 < n; i++) {
        pi = 2;
        p = i;
        while (p > 0) {
            pi++;
            if (sieve[pi]) {
                p--;
            }
        }

        for (j = i + 1; j + 1 < n; j++) {
            pj = pi;
            p = j - i;
            while (p > 0) {
                pj++;
                if (sieve[pj]) {
                    p--;
                }
            }

            for (k = j + 1; k < n; k++) {
                pk = pj;
                p = k - j;
                while (p > 0) {
                    pk++;
                    if (sieve[pk]) {
                        p--;
                    }
                }

                sum = pi + pj + pk;
                if (sum < LIMIT && sieve[sum]) {
                    count++;
                    if (verbose) {
                        printf("%2d + %2d + %2d = %d\n", pi, pj, pk, sum);
                    }
                }
            }
        }
    }

    printf("Count of strange unique prime triplets < %d is %d.\n\n", limit, count);
}

int main() {
    unsigned char sieve[LIMIT];

    init_sieve(sieve, LIMIT);

    strange_unique_prime_triplets(sieve, 30, true);
    strange_unique_prime_triplets(sieve, 1000, false);

    return 0;
}

fn prime_sieve(limit: usize) -> Vec<bool> {
    let mut sieve = vec![true; limit];
    if limit > 0 {
        sieve[0] = false;
    }
    if limit > 1 {
        sieve[1] = false;
    }
    for i in (4..limit).step_by(2) {
        sieve[i] = false;
    }
    let mut p = 3;
    loop {
        let mut q = p * p;
        if q >= limit {
            break;
        }
        if sieve[p] {
            let inc = 2 * p;
            while q < limit {
                sieve[q] = false;
                q += inc;
            }
        }
        p += 2;
    }
    sieve
}

fn strange_unique_prime_triplets(limit: usize, verbose: bool) {
    if limit < 6 {
        return;
    }
    let mut primes = Vec::new();
    let sieve = prime_sieve(limit * 3);
    for p in (3..limit).step_by(2) {
        if sieve[p] {
            primes.push(p);
        }
    }
    if verbose {
        println!("Strange unique prime triplets < {}:", limit);
    }
    let mut count = 0;
    let n = primes.len();
    for i in 0..n - 2 {
        for j in i + 1..n - 1 {
            for k in j + 1..n {
                let sum = primes[i] + primes[j] + primes[k];
                if sieve[sum] {
                    count += 1;
                    if verbose {
                        println!(
                            "{:2} + {:2} + {:2} = {:2}",
                            primes[i], primes[j], primes[k], sum
                        );
                    }
                }
            }
        }
    }
    println!(
        "Count of strange unique prime triplets < {} is {}.",
        limit, count
    );
}

fn main() {
    strange_unique_prime_triplets(30, true);
    strange_unique_prime_triplets(1000, false);
}


Strong and weak primes

fn is_prime(n: i32) -> bool {
	for i in 2..n {
		if i * i > n {
			return true;
		}
		if n % i == 0 {
			return false;
		}
	}
	n > 1
}

fn next_prime(n: i32) -> i32 {
	for i in (n+1).. {
		if is_prime(i) {
			return i;
		}
	}
	0
}

fn main() {
	let mut n = 0;
	let mut prime_q = 5;
	let mut prime_p = 3;
	let mut prime_o = 2;

	print!("First 36 strong primes: ");
	while n < 36 {
		if prime_p > (prime_o + prime_q) / 2 {
			print!("{} ",prime_p);
			n += 1;
		}
		prime_o = prime_p;
		prime_p = prime_q;
		prime_q = next_prime(prime_q);
	}
	println!("");

	while prime_p < 1000000 {
		if prime_p > (prime_o + prime_q) / 2 {
			n += 1;
		}
		prime_o = prime_p;
		prime_p = prime_q;
		prime_q = next_prime(prime_q);
	}
	println!("strong primes below 1,000,000: {}", n);

	while prime_p < 10000000 {
		if prime_p > (prime_o + prime_q) / 2 {
			n += 1;
		}
		prime_o = prime_p;
		prime_p = prime_q;
		prime_q = next_prime(prime_q);
	}
	println!("strong primes below 10,000,000: {}", n);

	n = 0;
	prime_q = 5;
	prime_p = 3;
	prime_o = 2;

	print!("First 36 weak primes: ");
	while n < 36 {
		if prime_p < (prime_o + prime_q) / 2 {
			print!("{} ",prime_p);
			n += 1;
		}
		prime_o = prime_p;
		prime_p = prime_q;
		prime_q = next_prime(prime_q);
	}
	println!("");

	while prime_p < 1000000 {
		if prime_p < (prime_o + prime_q) / 2 {
			n += 1;
		}
		prime_o = prime_p;
		prime_p = prime_q;
		prime_q = next_prime(prime_q);
	}
	println!("weak primes below 1,000,000: {}", n);

	while prime_p < 10000000 {
		if prime_p < (prime_o + prime_q) / 2 {
			n += 1;
		}
		prime_o = prime_p;
		prime_p = prime_q;
		prime_q = next_prime(prime_q);
	}
	println!("weak primes below 10,000,000: {}", n);
}


Successive prime differences

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define PRIME_COUNT 100000
int64_t PRIMES[PRIME_COUNT];
size_t primeSize = 0;

bool isPrime(int n) {
    size_t i = 0;

    for (i = 0; i < primeSize; i++) {
        int64_t p = PRIMES[i];
        if (n == p) {
            return true;
        }
        if (n % p == 0) {
            return false;
        }
        if (p * p > n) {
            break;
        }
    }

    return true;
}

void initialize() {
    int i;

    PRIMES[primeSize++] = 2;
    PRIMES[primeSize++] = 3;
    PRIMES[primeSize++] = 5;
    PRIMES[primeSize++] = 7;
    PRIMES[primeSize++] = 11;
    PRIMES[primeSize++] = 13;
    PRIMES[primeSize++] = 17;
    PRIMES[primeSize++] = 19;

    for (i = 21; primeSize < PRIME_COUNT;) {
        if (isPrime(i)) {
            PRIMES[primeSize++] = i;
        }
        i += 2;

        if (primeSize < PRIME_COUNT && isPrime(i)) {
            PRIMES[primeSize++] = i;
        }
        i += 2;
    }
}

void diff1(size_t diff) {
    int64_t pm0, pm1;
    int64_t fg1 = 0, fg2 = 0, lg1 = 0, lg2 = 0;
    size_t pos, count = 0;

    if (diff == 0) {
        return;
    }

    pm0 = PRIMES[0];
    for (pos = 1; pos < PRIME_COUNT; pos++) {
        pm1 = pm0;
        pm0 = PRIMES[pos];
        if (pm0 > 1000000) {
            break;
        }
        if (pm0 - pm1 == diff) {
            count++;
            if (fg1 == 0) {
                fg1 = pm1;
                fg2 = pm0;
            }
            lg1 = pm1;
            lg2 = pm0;
        }
    }

    printf("%ld|%d|%lld %lld|%lld %lld|\n", diff, count, fg1, fg2, lg1, lg2);
}

void diff2(size_t d0, size_t d1) {
    int64_t pm0, pm1, pm2;
    int64_t fg1 = 0, fg2, fg3, lg1, lg2, lg3;
    size_t pos, count = 0;

    if (d0 == 0 || d1 == 0) {
        return;
    }

    pm1 = PRIMES[0];
    pm0 = PRIMES[1];
    for (pos = 2; pos < PRIME_COUNT; pos++) {
        pm2 = pm1;
        pm1 = pm0;
        pm0 = PRIMES[pos];
        if (pm0 > 1000000) {
            break;
        }
        if (pm1 - pm2 == d0 && pm0 - pm1 == d1) {
            count++;
            if (fg1 == 0) {
                fg1 = pm2;
                fg2 = pm1;
                fg3 = pm0;
            }
            lg1 = pm2;
            lg2 = pm1;
            lg3 = pm0;
        }
    }

    printf("%d %d|%d|%lld %lld %lld|%lld %lld %lld|\n", d0, d1, count, fg1, fg2, fg3, lg1, lg2, lg3);
}

void diff3(size_t d0, size_t d1, size_t d2) {
    int64_t pm0, pm1, pm2, pm3;
    int64_t fg1 = 0, fg2, fg3, fg4, lg1, lg2, lg3, lg4;
    size_t pos, count = 0;

    if (d0 == 0 || d1 == 0 || d2 == 0) {
        return;
    }

    pm2 = PRIMES[0];
    pm1 = PRIMES[1];
    pm0 = PRIMES[2];
    for (pos = 3; pos < PRIME_COUNT; pos++) {
        pm3 = pm2;
        pm2 = pm1;
        pm1 = pm0;
        pm0 = PRIMES[pos];
        if (pm0 > 1000000) {
            break;
        }
        if (pm2 - pm3 == d0 && pm1 - pm2 == d1 && pm0 - pm1 == d2) {
            count++;
            if (fg1 == 0) {
                fg1 = pm3;
                fg2 = pm2;
                fg3 = pm1;
                fg4 = pm0;
            }
            lg1 = pm3;
            lg2 = pm2;
            lg3 = pm1;
            lg4 = pm0;
        }
    }

    printf("%d %d %d|%d|%lld %lld %lld %lld|%lld %lld %lld %lld|\n", d0, d1, d2, count, fg1, fg2, fg3, fg4, lg1, lg2, lg3, lg4);
}

int main() {
    initialize();

    printf("differences|count|first group|last group\n");

    diff1(2);
    diff1(1);

    diff2(2, 2);
    diff2(2, 4);
    diff2(4, 2);

    diff3(6, 4, 2);

    return 0;
}

fn is_prime(num: u32) -> bool {
  match num {
      x if x < 4 => x > 1,
      x if x % 2 == 0 => false,
      x => { let limit = (x as f32).sqrt().ceil() as u32;
              (3..=limit).step_by(2).all(|a| x % a != 0)
            }
  }
}

fn primes_by_diffs(primes: &[u32], diffs: &[u32]) -> Vec<Vec<u32>> {

  fn select(diffs: &[u32], prime_win: &[u32], acc: bool) -> bool {
    if diffs.is_empty() || !acc {
      acc
    }
    else {
      let acc1 = prime_win[0] + diffs[0] == prime_win[1];
      select(&diffs[1..], &prime_win[1..], acc1)
    }
  }

  primes.windows(diffs.len() + 1)
        .filter(|&win| select(diffs, win, true))
        .map(|win| win.to_vec())
        .collect()
}

fn main() {
  let limit = 1_000_000u32;
  let start = std::time::Instant::now();
  let primes = (2..).filter(|&i| is_prime(i));
  let prime_list: Vec<u32> = primes.take_while(|&p| p <= limit).collect();
  let duration = start.elapsed();
  println!("primes time: {:?}", duration);
  for diffs in vec!(vec!(1), vec!(2), vec!(2,2), vec!(2,4), vec!(4,2), vec!(6,4,2), vec!(2,4,6)) {
    let result_list = primes_by_diffs(&prime_list, &diffs);
    let len = result_list.len();
    println!("{:?} number: {}\n\tfirst: {:?}", diffs, len, result_list[0]);
    if len == 1 {
      println!()
    }
    if len > 1 {
      println!("\tlast: {:?}\n", result_list.last().unwrap())
    }
  }
}


Sum data type

#include<stdio.h>

typedef union data{
        int i;
        float f;
        char c;
}united;

int main()
{
        united udat;

        udat.i = 5;
        udat.f = 3.14159;
        udat.c = 'C';

        printf("Integer   i = %d , address of i = %p\n",udat.i,&udat.i);
        printf("Float     f = %f , address of f = %p\n",udat.f,&udat.f);
        printf("Character c = %c , address of c = %p\n",udat.c,&udat.c);

        return 0;
}

enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);

let loopback = IpAddr::V6(String::from("::1"));


Summarize primes

#include <stdbool.h>
#include <stdio.h>

bool is_prime(int n) {
    int i = 5;

    if (n < 2) {
        return false;
    }

    if (n % 2 == 0) {
        return n == 2;
    }
    if (n % 3 == 0) {
        return n == 3;
    }

    while (i * i <= n) {
        if (n % i == 0) {
            return false;
        }
        i += 2;

        if (n % i == 0) {
            return false;
        }
        i += 4;
    }

    return true;
}

int main() {
    const int start = 1;
    const int stop = 1000;

    int sum = 0;
    int count = 0;
    int sc = 0;
    int p;

    for (p = start; p < stop; p++) {
        if (is_prime(p)) {
            count++;
            sum += p;
            if (is_prime(sum)) {
                printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
                sc++;
            }
        }
    }
    printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);

    return 0;
}

fn main() {
    let limit = 1000;
    let mut sum = 0;
    println!("count  prime      sum");
    for (n, p) in primal::Sieve::new(limit)
        .primes_from(2)
        .take_while(|x| *x < limit)
        .enumerate()
    {
        sum += p;
        if primal::is_prime(sum as u64) {
            println!("  {:>3}    {:>3}    {:>5}", n + 1, p, sum);
        }
    }
}


Super-d numbers

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

int main() {
    for (unsigned int d = 2; d <= 9; ++d) {
        printf("First 10 super-%u numbers:\n", d);
        char digits[16] = { 0 };
        memset(digits, '0' + d, d);
        mpz_t bignum;
        mpz_init(bignum);
        for (unsigned int count = 0, n = 1; count < 10; ++n) {
            mpz_ui_pow_ui(bignum, n, d);
            mpz_mul_ui(bignum, bignum, d);
            char* str = mpz_get_str(NULL, 10, bignum);
            if (strstr(str, digits)) {
                printf("%u ", n);
                ++count;
            }
            free(str);
        }
        mpz_clear(bignum);
        printf("\n");
    }
    return 0;
}

fn print_super_d_numbers(d: u32, limit: u32) {
    use rug::Assign;
    use rug::Integer;

    println!("First {} super-{} numbers:", limit, d);
    let digits = d.to_string().repeat(d as usize);
    let mut count = 0;
    let mut n = 1;
    let mut s = Integer::new();
    while count < limit {
        s.assign(Integer::u_pow_u(n, d));
        s *= d;
        if s.to_string().contains(&digits) {
            print!("{} ", n);
            count += 1;
        }
        n += 1;
    }
    println!();
}

fn main() {
    for d in 2..=9 {
        print_super_d_numbers(d, 10);
    }
}


Tarjan

#include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>

#ifndef min
#define min(x, y) ((x)<(y) ? (x) : (y))
#endif

struct edge {
	void *from;
	void *to;
};

struct components {
	int nnodes;
	void **nodes;
	struct components *next;
};

struct node {
	int index;
	int lowlink;
	bool onStack;
	void *data;
};

struct tjstate {
	int index;
	int sp;
	int nedges;
	struct edge *edges;
	struct node **stack;
	struct components *head;
	struct components *tail;
};

static int nodecmp(const void *l, const void *r)
{
	return (ptrdiff_t)l -(ptrdiff_t)((struct node *)r)->data;
}

static int strongconnect(struct node *v, struct tjstate *tj)
{
	struct node *w;

	v->index = tj->index;
	v->lowlink = tj->index;
	tj->index++;
	tj->stack[tj->sp] = v;
	tj->sp++;
	v->onStack = true;

	for (int i = 0; i<tj->nedges; i++) {

		if (tj->edges[i].from != v) {
			continue;
		}
		w = tj->edges[i].to;

		if (w->index == -1) {
			int r = strongconnect(w, tj);
			if (r != 0)
				return r;
			v->lowlink = min(v->lowlink, w->lowlink);

		} else if (w->onStack) {
			v->lowlink = min(v->lowlink, w->index);
		}
	}

	if (v->lowlink == v->index) {
		struct components *ng = malloc(sizeof(struct components));
		if (ng == NULL) {
			return 2;
		}
		if (tj->tail == NULL) {
			tj->head = ng;
		} else {
			tj->tail->next = ng;
		}
		tj->tail = ng;
		ng->next = NULL;
		ng->nnodes = 0;
		do {
			tj->sp--;
			w = tj->stack[tj->sp];
			w->onStack = false;
			ng->nnodes++;
		} while (w != v);
		ng->nodes = malloc(ng->nnodes*sizeof(void *));
		if (ng == NULL) {
			return 2;
		}
		for (int i = 0; i<ng->nnodes; i++) {
			ng->nodes[i] = tj->stack[tj->sp+i]->data;
		}
	}
	return 0;
}

static int ptrcmp(const void *l, const void *r)
{
	return (ptrdiff_t)((struct node *)l)->data
		- (ptrdiff_t)((struct node *)r)->data;
}

struct components *tarjans(
		int nnodes, void *nodedata[],
		int nedges, struct edge *edgedata[],
		int *error)
{
	struct node nodes[nnodes];
	struct edge edges[nedges];
	struct node *stack[nnodes];
	struct node *from, *to;
	struct tjstate tj = {0, 0, nedges, edges, stack, NULL, .tail=NULL};

	for (int i = 0; i<nnodes; i++) {
		nodes[i] = (struct node){-1, -1, false, nodedata[i]};
	}
	qsort(nodes, nnodes, sizeof(struct node), ptrcmp);

	for (int i = 0; i<nedges; i++) {
		from = bsearch(edgedata[i]->from, nodes, nnodes,
			sizeof(struct node), nodecmp);
		if (from == NULL) {
			*error = 1;
			return NULL;
		}
		to = bsearch(edgedata[i]->to, nodes, nnodes,
			sizeof(struct node), nodecmp);
		if (to == NULL) {
			*error = 1;
			return NULL;
		}
		edges[i] = (struct edge){.from=from, .to=to};
	}

	for (int i = 0; i < nnodes; i++) {
		if (nodes[i].index == -1) {
			*error = strongconnect(&nodes[i], &tj);
			if (*error != 0)
				return NULL;
		}
	}
	return tj.head;
}

use std::collections::{BTreeMap, BTreeSet};

#[derive(Clone, Debug)]
pub struct Graph {
    neighbors: BTreeMap<usize, BTreeSet<usize>>,
}

impl Graph {
    pub fn new(size: usize) -> Self {
        Self {
            neighbors: (0..size).fold(BTreeMap::new(), |mut acc, x| {
                acc.insert(x, BTreeSet::new());
                acc
            }),
        }
    }

    pub fn edges<'a>(&'a self, vertex: usize) -> impl Iterator<Item = usize> + 'a {
        self.neighbors[&vertex].iter().cloned()
    }

    pub fn add_edge(&mut self, from: usize, to: usize) {
        assert!(to < self.len());
        self.neighbors.get_mut(&from).unwrap().insert(to);
    }

    pub fn add_edges(&mut self, from: usize, to: impl IntoIterator<Item = usize>) {
        let limit = self.len();

        self.neighbors
            .get_mut(&from)
            .unwrap()
            .extend(to.into_iter().filter(|x| {
                assert!(*x < limit);
                true
            }));
    }

    pub fn is_empty(&self) -> bool {
        self.neighbors.is_empty()
    }

    pub fn len(&self) -> usize {
        self.neighbors.len()
    }
}

#[derive(Clone)]
struct VertexState {
    index: usize,
    low_link: usize,
    on_stack: bool,
}

pub struct Tarjan<'a> {
    graph: &'a Graph,
    index: usize,
    stack: Vec<usize>,
    state: Vec<VertexState>,
    components: Vec<BTreeSet<usize>>,
}

impl<'a> Tarjan<'a> {

    const INVALID_INDEX: usize = usize::MAX;

    pub fn walk(graph: &'a Graph) -> Vec<BTreeSet<usize>> {
        Self {
            graph,
            index: 0,
            stack: Vec::new(),
            state: vec![
                VertexState {
                    index: Self::INVALID_INDEX,
                    low_link: Self::INVALID_INDEX,
                    on_stack: false
                };
                graph.len()
            ],
            components: Vec::new(),
        }
        .visit_all()
    }

    fn visit_all(mut self) -> Vec<BTreeSet<usize>> {
        for vertex in 0..self.graph.len() {
            if self.state[vertex].index == Self::INVALID_INDEX {
                self.visit(vertex);
            }
        }

        self.components
    }

    fn visit(&mut self, v: usize) {
        let v_ref = &mut self.state[v];
        v_ref.index = self.index;
        v_ref.low_link = self.index;
        self.index += 1;
        self.stack.push(v);
        v_ref.on_stack = true;

        for w in self.graph.edges(v) {
            let w_ref = &self.state[w];
            if w_ref.index == Self::INVALID_INDEX {
                self.visit(w);
                let w_low_link = self.state[w].low_link;
                let v_ref = &mut self.state[v];
                v_ref.low_link = v_ref.low_link.min(w_low_link);
            } else if w_ref.on_stack {
                let w_index = self.state[w].index;
                let v_ref = &mut self.state[v];
                v_ref.low_link = v_ref.low_link.min(w_index);
            }
        }

        let v_ref = &self.state[v];
        if v_ref.low_link == v_ref.index {
            let mut component = BTreeSet::new();

            loop {
                let w = self.stack.pop().unwrap();
                self.state[w].on_stack = false;
                component.insert(w);
                if w == v {
                    break;
                }
            }

            self.components.push(component);
        }
    }
}

fn main() {
    let graph = {
        let mut g = Graph::new(8);
        g.add_edge(0, 1);
        g.add_edge(2, 0);
        g.add_edges(5, vec![2, 6]);
        g.add_edge(6, 5);
        g.add_edge(1, 2);
        g.add_edges(3, vec![1, 2, 4]);
        g.add_edges(4, vec![5, 3]);
        g.add_edges(7, vec![4, 7, 6]);
        g
    };

    for component in Tarjan::walk(&graph) {
        println!("{:?}", component);
    }
}


Tau function

#include <stdio.h>

unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;

    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }

    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }

    if (n > 1) {
        total *= 2;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int n;

    printf("Count of divisors for the first %d positive integers:\n", limit);
    for (n = 1; n <= limit; ++n) {
        printf("%3d", divisor_count(n));
        if (n % 20 == 0) {
            printf("\n");
        }
    }

    return 0;
}

fn factor_exponent(n: i32, i: i32) -> (i32, i32) {
	if n % i == 0 {
		let (a, b) = factor_exponent(n / i, i);
		(a + 1, b)
	} else {
		(0, n)
	}
}

fn tau(n: i32) -> i32 {
	for i in 2..(n+1) {
		if n % i == 0 {
			let (count, next) = factor_exponent(n, i);
			return (count + 1) * tau(next);
		}
	}
	return 1;
}

fn main() {
	for i in 1..101 {
		print!("{} ", tau(i));
	}
}


Tau number

#include <stdio.h>

unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    unsigned int p;

    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }

    for (p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }

    if (n > 1) {
        total *= 2;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int count = 0;
    unsigned int n;

    printf("The first %d tau numbers are:\n", limit);
    for (n = 1; count < limit; ++n) {
        if (n % divisor_count(n) == 0) {
            printf("%6d", n);
            ++count;
            if (count % 10 == 0) {
                printf("\n");
            }
        }
    }

    return 0;
}

fn get_divisors(n: u32) -> Vec<u32> {
    let mut results = Vec::new();

    for i in 1..(n / 2 + 1) {
        if n % i == 0 {
            results.push(i);
        }
    }
    results.push(n);
    results
}

fn is_tau_number(i: u32) -> bool {
    0 == i % get_divisors(i).len() as u32
}

fn main() {
    println!("\nFirst 100 Tau numbers:");
    let mut counter: u32 = 0;
    let mut i: u32 = 1;
    while counter < 100 {
        if is_tau_number(i) {
            print!("{:>4}", i);
            counter += 1;
            print!("{}", if counter % 20 == 0 { "\n" } else { "," });
        }
        i += 1;
    }
}


Taxicab numbers

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

typedef unsigned long long xint;
typedef unsigned uint;
typedef struct {
	uint x, y;
	xint value;
} sum_t;

xint *cube;
uint n_cubes;

sum_t *pq;
uint pq_len, pq_cap;

void add_cube(void)
{
	uint x = n_cubes++;
	cube = realloc(cube, sizeof(xint) * (n_cubes + 1));
	cube[n_cubes] = (xint) n_cubes*n_cubes*n_cubes;
	if (x < 2) return;

	if (++pq_len >= pq_cap) {
		if (!(pq_cap *= 2)) pq_cap = 2;
		pq = realloc(pq, sizeof(*pq) * pq_cap);
	}

	sum_t tmp = (sum_t) { x, 1, cube[x] + 1 };

	uint i, j;
	for (i = pq_len; i >= 1 && pq[j = i>>1].value > tmp.value; i = j)
		pq[i] = pq[j];

	pq[i] = tmp;
}

void next_sum(void)
{
redo:	while (!pq_len || pq[1].value >= cube[n_cubes]) add_cube();

	sum_t tmp = pq[0] = pq[1];
	if (++tmp.y >= tmp.x) {
		tmp = pq[pq_len--];
		if (!pq_len) goto redo;
	} else
		tmp.value += cube[tmp.y] - cube[tmp.y-1];

	uint i, j;

	for (i = 1; (j = i<<1) <= pq_len; pq[i] = pq[j], i = j) {
		if (j < pq_len && pq[j+1].value < pq[j].value) ++j;
		if (pq[j].value >= tmp.value) break;
	}
	pq[i] = tmp;
}

uint next_taxi(sum_t *hist)
{
	do next_sum(); while (pq[0].value != pq[1].value);

	uint len = 1;
	hist[0] = pq[0];
	do {
		hist[len++] = pq[1];
		next_sum();
	} while (pq[0].value == pq[1].value);

	return len;
}

int main(void)
{
	uint i, l;
	sum_t x[10];
	for (i = 1; i <= 2006; i++) {
		l = next_taxi(x);
		if (25 < i && i < 2000) continue;
		printf("%4u:%10llu", i, x[0].value);
		while (l--) printf(" = %4u^3 + %4u^3", x[l].x, x[l].y);
		putchar('\n');
	}
	return 0;
}

use std::collections::HashMap;
use itertools::Itertools;

fn cubes(n: u64) -> Vec<u64> {
	let mut cube_vector = Vec::new();
	for i in 1..=n {
		cube_vector.push(i.pow(3));
	}
	cube_vector
}

fn main() {
	let c = cubes(1201);
	let it = c.iter().combinations(2);
	let mut m = HashMap::new();
	for x in it {
		let sum = x[0] + x[1];
		m.entry(sum).or_insert(Vec::new()).push(x)
	}

	let mut result = Vec::new();

	for (k,v) in m.iter() {
		if v.len() > 1 {
			result.push((k,v));
		}
	}

	result.sort();
	for f in result {
		println!("{:?}", f);
	}
}


Teacup rim text

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

int string_compare(gconstpointer p1, gconstpointer p2) {
    const char* const* s1 = p1;
    const char* const* s2 = p2;
    return strcmp(*s1, *s2);
}

GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
    GError* error = NULL;
    GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
    if (channel == NULL) {
        g_propagate_error(error_ptr, error);
        return NULL;
    }
    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
    GString* line = g_string_sized_new(64);
    gsize term_pos;
    while (g_io_channel_read_line_string(channel, line, &term_pos,
                                         &error) == G_IO_STATUS_NORMAL) {
        char* word = g_strdup(line->str);
        word[term_pos] = '\0';
        g_ptr_array_add(dict, word);
    }
    g_string_free(line, TRUE);
    g_io_channel_unref(channel);
    if (error != NULL) {
        g_propagate_error(error_ptr, error);
        g_ptr_array_free(dict, TRUE);
        return NULL;
    }
    g_ptr_array_sort(dict, string_compare);
    return dict;
}

void rotate(char* str, size_t len) {
    char c = str[0];
    memmove(str, str + 1, len - 1);
    str[len - 1] = c;
}

char* dictionary_search(const GPtrArray* dictionary, const char* word) {
    char** result = bsearch(&word, dictionary->pdata, dictionary->len,
                            sizeof(char*), string_compare);
    return result != NULL ? *result : NULL;
}

void find_teacup_words(GPtrArray* dictionary) {
    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
    GPtrArray* teacup_words = g_ptr_array_new();
    GString* temp = g_string_sized_new(8);
    for (size_t i = 0, n = dictionary->len; i < n; ++i) {
        char* word = g_ptr_array_index(dictionary, i);
        size_t len = strlen(word);
        if (len < 3 || g_hash_table_contains(found, word))
            continue;
        g_ptr_array_set_size(teacup_words, 0);
        g_string_assign(temp, word);
        bool is_teacup_word = true;
        for (size_t i = 0; i < len - 1; ++i) {
            rotate(temp->str, len);
            char* w = dictionary_search(dictionary, temp->str);
            if (w == NULL) {
                is_teacup_word = false;
                break;
            }
            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
                g_ptr_array_add(teacup_words, w);
        }
        if (is_teacup_word && teacup_words->len > 0) {
            printf("%s", word);
            g_hash_table_add(found, word);
            for (size_t i = 0; i < teacup_words->len; ++i) {
                char* teacup_word = g_ptr_array_index(teacup_words, i);
                printf(" %s", teacup_word);
                g_hash_table_add(found, teacup_word);
            }
            printf("\n");
        }
    }
    g_string_free(temp, TRUE);
    g_ptr_array_free(teacup_words, TRUE);
    g_hash_table_destroy(found);
}

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s dictionary\n", argv[0]);
        return EXIT_FAILURE;
    }
    GError* error = NULL;
    GPtrArray* dictionary = load_dictionary(argv[1], &error);
    if (dictionary == NULL) {
        if (error != NULL) {
            fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
                    argv[1], error->message);
            g_error_free(error);
        }
        return EXIT_FAILURE;
    }
    find_teacup_words(dictionary);
    g_ptr_array_free(dictionary, TRUE);
    return EXIT_SUCCESS;
}

use std::collections::BTreeSet;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;

fn load_dictionary(filename: &str) -> std::io::Result<BTreeSet<String>> {
    let file = File::open(filename)?;
    let mut dict = BTreeSet::new();
    for line in io::BufReader::new(file).lines() {
        let word = line?;
        dict.insert(word);
    }
    Ok(dict)
}

fn find_teacup_words(dict: &BTreeSet<String>) {
    let mut teacup_words: Vec<&String> = Vec::new();
    let mut found: HashSet<&String> = HashSet::new();
    for word in dict {
        let len = word.len();
        if len < 3 || found.contains(word) {
            continue;
        }
        teacup_words.clear();
        let mut is_teacup_word = true;
        let mut chars: Vec<char> = word.chars().collect();
        for _ in 1..len {
            chars.rotate_left(1);
            if let Some(w) = dict.get(&String::from_iter(&chars)) {
                if !w.eq(word) && !teacup_words.contains(&w) {
                    teacup_words.push(w);
                }
            } else {
                is_teacup_word = false;
                break;
            }
        }
        if !is_teacup_word || teacup_words.is_empty() {
            continue;
        }
        print!("{}", word);
        found.insert(word);
        for w in &teacup_words {
            found.insert(w);
            print!(" {}", w);
        }
        println!();
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 2 {
        eprintln!("Usage: teacup dictionary");
        std::process::exit(1);
    }
    let dict = load_dictionary(&args[1]);
    match dict {
        Ok(dict) => find_teacup_words(&dict),
        Err(error) => eprintln!("Cannot open file {}: {}", &args[1], error),
    }
}


Terminal control_Preserve screen

#include <stdio.h>
#include <unistd.h>

int main()
{
	int i;
	printf("\033[?1049h\033[H");
	printf("Alternate screen buffer\n");
	for (i = 5; i; i--) {
		printf("\rgoing back in %d...", i);
		fflush(stdout);
		sleep(1);
	}
	printf("\033[?1049l");

	return 0;
}

use std::io::{stdout, Write};
use std::time::Duration;

fn main() {
    let mut output = stdout();

    print!("\x1b[?1049h\x1b[H");
    println!("Alternate screen buffer");

    for i in (1..=5).rev() {
        print!("\rgoing back in {}...", i);
        output.flush().unwrap();
        std::thread::sleep(Duration::from_secs(1));
    }

    print!("\x1b[?1049l");
}


Textonyms

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

char text_char(char c) {
    switch (c) {
    case 'a': case 'b': case 'c':
        return '2';
    case 'd': case 'e': case 'f':
        return '3';
    case 'g': case 'h': case 'i':
        return '4';
    case 'j': case 'k': case 'l':
        return '5';
    case 'm': case 'n': case 'o':
        return '6';
    case 'p': case 'q': case 'r': case 's':
        return '7';
    case 't': case 'u': case 'v':
        return '8';
    case 'w': case 'x': case 'y': case 'z':
        return '9';
    default:
        return 0;
    }
}

bool text_string(const GString* word, GString* text) {
    g_string_set_size(text, word->len);
    for (size_t i = 0; i < word->len; ++i) {
        char c = text_char(g_ascii_tolower(word->str[i]));
        if (c == 0)
            return false;
        text->str[i] = c;
    }
    return true;
}

typedef struct textonym_tag {
    const char* text;
    size_t length;
    GPtrArray* words;
} textonym_t;

int compare_by_text_length(const void* p1, const void* p2) {
    const textonym_t* t1 = p1;
    const textonym_t* t2 = p2;
    if (t1->length > t2->length)
        return -1;
    if (t1->length < t2->length)
        return 1;
    return strcmp(t1->text, t2->text);
}

int compare_by_word_count(const void* p1, const void* p2) {
    const textonym_t* t1 = p1;
    const textonym_t* t2 = p2;
    if (t1->words->len > t2->words->len)
        return -1;
    if (t1->words->len < t2->words->len)
        return 1;
    return strcmp(t1->text, t2->text);
}

void print_words(GPtrArray* words) {
    for (guint i = 0, n = words->len; i < n; ++i) {
        if (i > 0)
            printf(", ");
        printf("%s", g_ptr_array_index(words, i));
    }
    printf("\n");
}

void print_top_words(GArray* textonyms, guint top) {
    for (guint i = 0; i < top; ++i) {
        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
        printf("%s = ", t->text);
        print_words(t->words);
    }
}

void free_strings(gpointer ptr) {
    g_ptr_array_free(ptr, TRUE);
}

bool find_textonyms(const char* filename, GError** error_ptr) {
    GError* error = NULL;
    GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
    if (channel == NULL) {
        g_propagate_error(error_ptr, error);
        return false;
    }
    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
                                           g_free, free_strings);
    GString* word = g_string_sized_new(64);
    GString* text = g_string_sized_new(64);
    guint count = 0;
    gsize term_pos;
    while (g_io_channel_read_line_string(channel, word, &term_pos,
                                         &error) == G_IO_STATUS_NORMAL) {
        g_string_truncate(word, term_pos);
        if (!text_string(word, text))
            continue;
        GPtrArray* words = g_hash_table_lookup(ht, text->str);
        if (words == NULL) {
            words = g_ptr_array_new_full(1, g_free);
            g_hash_table_insert(ht, g_strdup(text->str), words);
        }
        g_ptr_array_add(words, g_strdup(word->str));
        ++count;
    }
    g_io_channel_unref(channel);
    g_string_free(word, TRUE);
    g_string_free(text, TRUE);
    if (error != NULL) {
        g_propagate_error(error_ptr, error);
        g_hash_table_destroy(ht);
        return false;
    }

    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
    GHashTableIter iter;
    gpointer key, value;
    g_hash_table_iter_init(&iter, ht);
    while (g_hash_table_iter_next(&iter, &key, &value)) {
        GPtrArray* v = value;
        if (v->len > 1) {
            textonym_t textonym;
            textonym.text = key;
            textonym.length = strlen(key);
            textonym.words = v;
            g_array_append_val(words, textonym);
        }
    }

    printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
           count, filename);
    guint size = g_hash_table_size(ht);
    printf("They require %u digit combinations to represent them.\n", size);
    guint textonyms = words->len;
    printf("%u digit combinations represent Textonyms.\n", textonyms);

    guint top = 5;
    if (textonyms < top)
        top = textonyms;

    printf("\nTop %u by number of words:\n", top);
    g_array_sort(words, compare_by_word_count);
    print_top_words(words, top);

    printf("\nTop %u by length:\n", top);
    g_array_sort(words, compare_by_text_length);
    print_top_words(words, top);

    g_array_free(words, TRUE);
    g_hash_table_destroy(ht);
    return true;
}

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s word-list\n", argv[0]);
        return EXIT_FAILURE;
    }
    GError* error = NULL;
    if (!find_textonyms(argv[1], &error)) {
        if (error != NULL) {
            fprintf(stderr, "%s: %s\n", argv[1], error->message);
            g_error_free(error);
        }
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead};

fn text_char(ch: char) -> Option<char> {
    match ch {
        'a' | 'b' | 'c' => Some('2'),
        'd' | 'e' | 'f' => Some('3'),
        'g' | 'h' | 'i' => Some('4'),
        'j' | 'k' | 'l' => Some('5'),
        'm' | 'n' | 'o' => Some('6'),
        'p' | 'q' | 'r' | 's' => Some('7'),
        't' | 'u' | 'v' => Some('8'),
        'w' | 'x' | 'y' | 'z' => Some('9'),
        _ => None,
    }
}

fn text_string(s: &str) -> Option<String> {
    let mut text = String::with_capacity(s.len());
    for c in s.chars() {
        if let Some(t) = text_char(c) {
            text.push(t);
        } else {
            return None;
        }
    }
    Some(text)
}

fn print_top_words(textonyms: &Vec<(&String, &Vec<String>)>, top: usize) {
    for (text, words) in textonyms.iter().take(top) {
        println!("{} = {}", text, words.join(", "));
    }
}

fn find_textonyms(filename: &str) -> std::io::Result<()> {
    let file = File::open(filename)?;
    let mut table = HashMap::new();
    let mut count = 0;

    for line in io::BufReader::new(file).lines() {
        let mut word = line?;
        word.make_ascii_lowercase();
        if let Some(text) = text_string(&word) {
            let words = table.entry(text).or_insert(Vec::new());
            words.push(word);
            count += 1;
        }
    }

    let mut textonyms: Vec<(&String, &Vec<String>)> =
        table.iter().filter(|x| x.1.len() > 1).collect();

    println!(
        "There are {} words in '{}' which can be represented by the digit key mapping.",
        count, filename
    );
    println!(
        "They require {} digit combinations to represent them.",
        table.len()
    );
    println!(
        "{} digit combinations represent Textonyms.",
        textonyms.len()
    );

    let top = std::cmp::min(5, textonyms.len());
    textonyms.sort_by_key(|x| (std::cmp::Reverse(x.1.len()), x.0));
    println!("\nTop {} by number of words:", top);
    print_top_words(&textonyms, top);

    textonyms.sort_by_key(|x| (std::cmp::Reverse(x.0.len()), x.0));
    println!("\nTop {} by length:", top);
    print_top_words(&textonyms, top);

    Ok(())
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 2 {
        eprintln!("usage: {} word-list", args[0]);
        std::process::exit(1);
    }
    match find_textonyms(&args[1]) {
        Ok(()) => {}
        Err(error) => eprintln!("{}: {}", args[1], error),
    }
}


The ISAAC cipher

#include <stdio.h>
#include <stddef.h>
#include <string.h>
#ifdef _MSC_VER
  typedef unsigned __int32 uint32_t;
#else
  #include <stdint.h>
#endif

typedef  uint32_t  ub4;

ub4 randrsl[256], randcnt;

static    ub4 mm[256];
static    ub4 aa=0, bb=0, cc=0;

void isaac()
{
   register ub4 i,x,y;

   cc = cc + 1;
   bb = bb + cc;

   for (i=0; i<256; ++i)
   {
     x = mm[i];
     switch (i%4)
     {
     case 0: aa = aa^(aa<<13); break;
     case 1: aa = aa^(aa>>6); break;
     case 2: aa = aa^(aa<<2); break;
     case 3: aa = aa^(aa>>16); break;
     }
     aa              = mm[(i+128)%256] + aa;
     mm[i]      = y  = mm[(x>>2)%256] + aa + bb;
     randrsl[i] = bb = mm[(y>>10)%256] + x;
   }

   randcnt = 0;
}

#define mix(a,b,c,d,e,f,g,h) \
{ \
   a^=b<<11; d+=a; b+=c; \
   b^=c>>2;  e+=b; c+=d; \
   c^=d<<8;  f+=c; d+=e; \
   d^=e>>16; g+=d; e+=f; \
   e^=f<<10; h+=e; f+=g; \
   f^=g>>4;  a+=f; g+=h; \
   g^=h<<8;  b+=g; h+=a; \
   h^=a>>9;  c+=h; a+=b; \
}

void randinit(int flag)
{
   register int i;
   ub4 a,b,c,d,e,f,g,h;
   aa=bb=cc=0;
   a=b=c=d=e=f=g=h=0x9e3779b9;

   for (i=0; i<4; ++i)
   {
     mix(a,b,c,d,e,f,g,h);
   }

   for (i=0; i<256; i+=8)
   {
     if (flag)
	 {
       a+=randrsl[i  ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3];
       e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7];
     }
     mix(a,b,c,d,e,f,g,h);
     mm[i  ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
     mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
   }

   if (flag)
   {
	 for (i=0; i<256; i+=8)
     {
       a+=mm[i  ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3];
       e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7];
       mix(a,b,c,d,e,f,g,h);
       mm[i  ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
       mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
     }
   }

   isaac();
   randcnt=0;
}

ub4 iRandom()
{
	ub4 r = randrsl[randcnt];
	++randcnt;
	if (randcnt >255) {
		isaac();
		randcnt = 0;
	}
	return r;
}

char iRandA()
{
	return iRandom() % 95 + 32;
}

void iSeed(char *seed, int flag)
{
	register ub4 i,m;
	for (i=0; i<256; i++) mm[i]=0;
	m = strlen(seed);
	for (i=0; i<256; i++)
	{

        if (i>m) randrsl[i]=0;  else randrsl[i] = seed[i];
	}

	randinit(flag);
}

#define MAXMSG 4096
#define MOD 95
#define START 32

enum ciphermode {
	mEncipher, mDecipher, mNone
};

char v[MAXMSG];
char* Vernam(char *msg)
	{
		register ub4 i,l;
		l = strlen(msg);

		memset(v,'\0',l+1);

		for (i=0; i<l; i++)
			v[i] = iRandA() ^ msg[i];
		return v;
	}

char Caesar(enum ciphermode m, char ch, char shift, char modulo, char start)
	{
		register int n;
		if (m == mDecipher) shift = -shift;
		n = (ch-start) + shift;
		n = n % modulo;
		if (n<0) n += modulo;
		return start+n;
	}

char c[MAXMSG];
char* CaesarStr(enum ciphermode m, char *msg, char modulo, char start)
	{
		register ub4 i,l;
		l = strlen(msg);

		memset(c,'\0',l+1);

		for (i=0; i<l; i++)
			c[i] = Caesar(m, msg[i], iRandA(), modulo, start);
		return c;
	}

int main()
{
	register ub4 n,l;

	char *msg = "a Top Secret secret";
	char *key = "this is my secret key";

	char vctx[MAXMSG], vptx[MAXMSG];

	char cctx[MAXMSG], cptx[MAXMSG];
	l = strlen(msg);

	iSeed(key,1);
	strcpy(vctx, Vernam(msg));

	strcpy(cctx, CaesarStr(mEncipher, msg, MOD, START));

	iSeed(key,1);
	strcpy(vptx, Vernam(vctx));

	strcpy(cptx, CaesarStr(mDecipher,cctx, MOD, START));

	printf("Message: %s\n",msg);
	printf("Key    : %s\n",key);
	printf("XOR    : ");

	for (n=0; n<l; n++) printf("%02X",vctx[n]);
	printf("\n");

	printf("XOR dcr: %s\n",vptx);

	printf("MOD    : ");

	for (n=0; n<l; n++) printf("%02X",cctx[n]);
	printf("\n");

	printf("MOD dcr: %s\n",cptx);
	return 0;
}


Topswops

#include <stdio.h>
#include <string.h>

typedef struct { char v[16]; } deck;
typedef unsigned int uint;

uint n, d, best[16];

void tryswaps(deck *a, uint f, uint s) {
#	define A a->v
#	define B b.v
	if (d > best[n]) best[n] = d;
	while (1) {
		if ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))
			&& (d + best[s] >= best[n] || A[s] == -1))
			break;

		if (d + best[s] <= best[n]) return;
		if (!--s) return;
	}

	d++;
	deck b = *a;
	for (uint i = 1, k = 2; i <= s; k <<= 1, i++) {
		if (A[i] != i && (A[i] != -1 || (f & k)))
			continue;

		for (uint j = B[0] = i; j--;) B[i - j] = A[j];
		tryswaps(&b, f | k, s);
	}
	d--;
}

int main(void) {
	deck x;
	memset(&x, -1, sizeof(x));
	x.v[0] = 0;

	for (n = 1; n < 13; n++) {
		tryswaps(&x, 1, n - 1);
		printf("%2d: %d\n", n, best[n]);
	}

	return 0;
}

use itertools::Itertools;

fn solve(deck: &[usize]) -> usize {
    let mut counter = 0_usize;
    let mut shuffle = deck.to_vec();
    loop {
        let p0 = shuffle[0];
        if p0 == 1 {
            break;
        }
        shuffle[..p0].reverse();
        counter += 1;
    }

    counter
}

fn topswops(number: usize) -> usize {
    (1..=number)
        .permutations(number)
        .fold(0_usize, |mut acc, p| {
            let steps = solve(&p);
            if steps > acc {
                acc = steps;
            }
            acc
        })
}
fn main() {
    (1_usize..=10).for_each(|x| println!("{}: {}", x, topswops(x)));
}


Trabb Pardo–Knuth algorithm

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

int
main ()
{
  double inputs[11], check = 400, result;
  int i;

  printf ("\nPlease enter 11 numbers :");

  for (i = 0; i < 11; i++)
    {
      scanf ("%lf", &inputs[i]);
    }

  printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");

  for (i = 10; i >= 0; i--)
    {
      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);

      printf ("\nf(%lf) = ");

      if (result > check)
        {
          printf ("Overflow!");
        }

      else
        {
          printf ("%lf", result);
        }
    }

  return 0;
}

use std::io::{self, BufRead};

fn op(x: f32) -> Option<f32> {
    let y = x.abs().sqrt() + 5.0 * x * x * x;
    if y < 400.0 {
        Some(y)
    } else {
        None
    }
}

fn main() {
    println!("Please enter 11 numbers (one number per line)");
    let stdin = io::stdin();

    let xs = stdin
        .lock()
        .lines()
        .map(|ox| ox.unwrap().trim().to_string())
        .flat_map(|s| str::parse::<f32>(&s))
        .take(11)
        .collect::<Vec<_>>();

    for x in xs.into_iter().rev() {
        match op(x) {
            Some(y) => println!("{}", y),
            None => println!("overflow"),
        };
    }
}


Truncate a file

#include <windows.h>
#include <stdio.h>
#include <wchar.h>

void
oops(const wchar_t *message)
{
	wchar_t *buf;
	DWORD error;

	buf = NULL;
	error = GetLastError();
	FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
	    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
	    NULL, error, 0, (wchar_t *)&buf, 0, NULL);

	if (buf) {
		fwprintf(stderr, L"%ls: %ls", message, buf);
		LocalFree(buf);
	} else {

		fwprintf(stderr, L"%ls: unknown error 0x%x\n",
		    message, error);
	}
}

int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
	HANDLE fh;

	fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (fh == INVALID_HANDLE_VALUE) {
		oops(fn);
		return 1;
	}

	if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
	    SetEndOfFile(fh) == 0) {
		oops(fn);
		CloseHandle(fh);
		return 1;
	}

	CloseHandle(fh);
	return 0;
}

int
main()
{
	LARGE_INTEGER fp;
	int argc;
	wchar_t **argv, *fn, junk[2];

	argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv == NULL) {
		oops(L"CommandLineToArgvW");
		return 1;
	}

	if (argc != 3) {
		fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
		return 1;
	}

	fn = argv[1];

	if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
		fwprintf(stderr, L"%ls: not a number\n", argv[2]);
		return 1;
	}

	return dotruncate(fn, fp);
}

use std::path::Path;
use std::fs;

fn truncate_file<P: AsRef<Path>>(filename: P, filesize: usize) -> Result<(), Error> {
    use Error::*;
    let file = fs::read(&filename).or(Err(NotFound))?;

    if filesize > file.len() {
        return Err(FilesizeTooSmall)
    }

    fs::write(&filename, &file[..filesize]).or(Err(UnableToWrite))?;
    Ok(())
}

#[derive(Debug)]
enum Error {

    NotFound,

    FilesizeTooSmall,

    UnableToWrite,
}