Skip to content

Instantly share code, notes, and snippets.

@jdeng
jdeng / queens-omp.cc
Last active December 31, 2015 01:39
N Queens with OpenMP
//compile with -fopenmp -Ofast -march=native -funroll-loops
#include <stdio.h>
typedef unsigned int mask_t;
template <int n, int m>
struct queens {
static size_t f(mask_t col, mask_t left, mask_t right) {
mask_t mask = ~(col | left | right);
size_t count = 0;
while (mask) {
@jdeng
jdeng / queens.cc
Created December 11, 2013 16:48
N Queens Problem (N <= 16)
//compile with -Ofast -march=native -funroll-loops
#include <stdio.h>
typedef unsigned short uint16_t;
template <int n, int m>
struct queens {
static void f(uint16_t col, uint16_t left, uint16_t right, size_t& count) {
uint16_t mask = ~(col | left | right);
for (int i = 0; i < n; ++i, mask >>= 1) {
@jdeng
jdeng / constructor
Created March 12, 2013 01:37
Constructor inheritance
#include <vector>
#include <iostream>
template <typename Iterator>
struct range: public std::pair<Iterator, Iterator>
{
using Parent = std::pair<Iterator, Iterator>;
template <typename... Arg> range(Arg&& ... arg): Parent(std::forward<Arg>(arg) ...) {}
Iterator begin() { return this->first; }
@jdeng
jdeng / map_reduce
Created March 10, 2013 22:09
simple map reduce with C++ 11. The sample maps an integer to a string, and reduces with reverse concatenation.
#include <string>
#include <vector>
#include <functional>
#include <iostream>
template <typename R, typename T, typename M>
auto map_reduce(const std::vector<T>& input, std::function<M(const T&)> mapper, std::function<R(const M& m, const R& r)> reducer, const R& init) -> decltype(reducer(std::declval<const M&>(), std::declval<const R&>()))
{
R r = init;
for (auto const & i: input) r = reducer(mapper(i), r);
@jdeng
jdeng / topk
Last active December 14, 2015 18:39
Top k elements of a const vector: lambda with variable capture, one pass trick in std::pop_heap, in c++ 11. Compiled with clang 3.1.
#include <random>
#include <vector>
#include <algorithm>
#include <iostream>
#include <time.h>
std::vector<size_t> topk(const std::vector<double>& values, size_t k)
{
size_t n = values.size();