Skip to content

Instantly share code, notes, and snippets.

@fmela
fmela / next_permutation.c
Last active November 30, 2017 04:06
Enumerate every permutation
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
bool next_permutation(unsigned a[], unsigned n)
{
if (n <= 1)
return false;
unsigned i = n-2;
while (!(a[i] < a[i+1]))

Keybase proof

I hereby claim:

  • I am fmela on github.
  • I am fmela (https://keybase.io/fmela) on keybase.
  • I have a public key whose fingerprint is 1ED2 D204 B006 BCB0 4494 6F55 0D03 EC4E 67C0 0BCC

To claim this, I am signing this object:

@fmela
fmela / enumerate-combinations.hxx
Created February 18, 2014 00:04
Enumerate every length-K combination of { 1, 2, ..., N } in ascending lexicographic order.
#include <vector>
#include <cassert>
// Call |f| with every length-K combination of { 1, 2, ..., N }, in ascending
// lexicographic order.
template<typename F>
void enumerate_combinations(size_t N, size_t K, const F& f) {
assert(K <= N);
std::vector<size_t> position;
// Initialize with initial position.
@fmela
fmela / flipsign.c
Created February 17, 2014 23:57
Branch-free conditional sign flip in C
int f(int x, int negate) {
return (x ^ -negate) + negate;
}
@fmela
fmela / GNUmakefile
Last active July 8, 2017 18:54
C++ program makefile boilerplate
SOURCES = $(wildcard *.cxx)
HEADERS = $(wildcard *.hxx)
OBJECTS = $(SOURCES:%.cxx=%.o)
PROGRAM = $(shell basename `pwd`)
CC := $(shell which clang || which gcc)
CFLAGS = -Wall -W -O -fno-exceptions -fno-rtti
LIBS = stdc++ m
LDFLAGS = $(LIBS:%=-l%)
@fmela
fmela / GNUmakefile
Created February 17, 2014 23:04
C program makefile boilerplate
SOURCES = $(wildcard *.c)
HEADERS = $(wildcard *.h)
OBJECTS = $(SOURCES:%.c=%.o)
PROGRAM = $(shell basename `pwd`)
CC := $(shell which clang || which gcc)
CFLAGS = -Wall -W -O
LIBS =
LDFLAGS = $(LIBS:%=-l%)
@fmela
fmela / agm_log.c
Created December 30, 2011 20:15
A natural logarithm function that uses the arithmetic-geometric mean.
double
agm_log(double x)
{
double a, b, e, e0 = DBL_MAX;
assert(x > 0.0);
for (a = (x + 1.0) * 0.5, b = sqrt(x); (e = fabs(a - b)) < e0; e0 = e) {
a = 0.5 * (a + b);
b = sqrt(a * b);
@fmela
fmela / stacktrace.cxx
Last active September 22, 2023 10:58
A C++ function that produces a stack backtrace with demangled function & method names.
/*
* Copyright (c) 2009-2017, Farooq Mela
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright