Skip to content

Instantly share code, notes, and snippets.

@gene-ressler
gene-ressler / dsu.c
Last active January 5, 2023 01:29
Disjoint set union/find
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
struct node_s *parent;
int size;
int value;
} DISJOINT_SET;
DISJOINT_SET *make_set(int value) {
@gene-ressler
gene-ressler / morse.ino
Last active December 5, 2022 05:45
Sketch to flash and beep International Morse for a console string
#include <ctype.h>
#define ACTIVE_BUZZER 12
char s[256];
int n = 0, p = 0;
void setup() {
delay(1000);
pinMode(LED_BUILTIN, OUTPUT);
@gene-ressler
gene-ressler / qsel.c
Last active November 5, 2022 22:43
Quickselect with some optimizations
#include <stdio.h>
#include <stdlib.h>
static int med3(int a, int b, int c) {
return a < b
? c < a ? a : (c < b ? c : b)
: c > a ? a : (c > b ? c : b);
}
static void swap(int *a, int i, int j) {
@gene-ressler
gene-ressler / pn.py
Last active October 19, 2022 15:37
Permutation numbering
# For any 0 <= k < fact(n), return a unique permutation of [0..n-1].
# Functional inverse of number_from_perm().
def perm_from_number(n, k):
a = list(range(n))
p = []
for d in range(2, n + 1):
p.append(k % d)
k //= d
t = n - 1
for i in reversed(p):
@gene-ressler
gene-ressler / qs.c
Last active November 5, 2022 22:22
Quicksort with standard optimizations
#include <stdio.h>
#include <stdlib.h>
static int med3(int a, int b, int c) {
return a < b
? c < a ? a : (c < b ? c : b)
: c > a ? a : (c > b ? c : b);
}
static void swap(int *a, int i, int j) {
@gene-ressler
gene-ressler / dfs.c
Last active April 27, 2023 03:02
Depth first graph search with history
#include <stdio.h>
#include <stdlib.h>
typedef struct edge_s {
struct edge_s *next;
int to;
} Edge;
typedef struct vertex_s {
Edge *edges;
@gene-ressler
gene-ressler / ams.c
Last active October 9, 2022 22:08
Array merge sort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(int *a, int n) {
if (n <= 1) return;
int m = (n + 1) / 2;
sort(a, m);
sort(a + m, n - m);
int b[m];
@gene-ressler
gene-ressler / hs.c
Last active October 2, 2022 03:33
Basic heapsort
#include <stdio.h>
#include <stdlib.h>
void sift_down(int *a, int n, int j) {
int j_rgt, val = a[j];
while ((j_rgt = 2 * j + 2) <= n) {
int j_lft = j_rgt - 1;
if (j_rgt == n || a[j_lft] > a[j_rgt]) {
if (val >= a[j_lft]) break;
a[j] = a[j_lft];
@gene-ressler
gene-ressler / is.c
Last active October 1, 2022 03:31
Straight insertion sort
#include <stdio.h>
#include <stdlib.h>
void sort(int *a, int n) {
for (int i = 1; i < n; ++i) {
int j, t = a[i];
for (j = i; j > 0 && a[j - 1] > t; --j) a[j] = a[j - 1];
a[j] = t;
}
}
@gene-ressler
gene-ressler / lms.c
Last active February 22, 2023 02:23
List mergesort
#include <stdio.h>
#include <stdlib.h>
typedef struct list_node_s {
struct list_node_s *next;
int val;
} LIST_NODE;
LIST_NODE *sort(LIST_NODE *a) {
if (!a || !a->next) return a;