Skip to content

Instantly share code, notes, and snippets.

View bahmanm's full-sized avatar

Bahman Movaqar bahmanm

View GitHub Profile
@bahmanm
bahmanm / ListCombinations.groovy
Last active August 29, 2015 14:10
Iterator (lazy) style class to compute all the combinations of any number of given lists.
/*
* Author: Bahman Movaqar <Bahman AT BahmanM.com>
* Copyright (c) Bahman Movaqar
* This file is released under public domain license.
*/
///// Tests below the main class
import groovy.transform.PackageScope
/**
@bahmanm
bahmanm / kcombinations.groovy
Last active August 29, 2015 14:10
Function to compute k-Combinations of a list
List kCombinations(List l, Integer k) {
assert k >= 0, 'Invalid "k"'
if (l.empty || !k) []
else if (k == 1) l.collate(1)
else
(0..l.size()-1).inject([] as Set) { acc, i ->
def c = kCombinations(l.drop(i+1), k-1)
acc + [l[i], c].combinations { cn ->
def cnf = cn.flatten()
cnf.size() == k ? cnf : [l[i],c].flatten()
@bahmanm
bahmanm / csv-load-and-process.clj
Created August 13, 2012 18:33
Processing CSV contents
; Suppose you have a CSV file with the first row being the column names
; and the rest being data. Using the following snippet you can process
; the contents passing each row's contents as keyword arguments to
; another function.
;
; Example CSV structure:
; +----------------------------------------------------------+
; | customer-code | name | e-mail | address | phone |
; +----------------------------------------------------------+
;
@bahmanm
bahmanm / clojure-tricks.clj
Created April 15, 2012 12:48
Clojure tricks and useful functions/macros
(defn getfn [fname]
"Gets a function by its fully qualified name."
(let [fsym (symbol fname)
nsym (symbol (namespace fsym))]
(require nsym)
(resolve fsym)))
(defn interpolate [s vals]
"Returns the interpolation of string 's' with a map of key/values."
;Keys in 's' are marked with #{key-name} syntax.