Skip to content

Instantly share code, notes, and snippets.

@Sdaas
Sdaas / quicksort.clj
Last active February 1, 2016 14:08
Quicksort in Clojure
; Improved version of quicksort - uses destructuring for more concise code
; Quicksort works as follows. From the given list of numbers, choose a "pivot". Now make two piles - one consisting of the numbers
; which are less than the pivot, the other greater than the pivot. And sort each one (recursively). Then concat everything to return the
; final list. See http://www.sorting-algorithms.com/quick-sort
(defn qsort
"sort a list of numbers using quicksort"
[[pivot & remaining]]
(if (nil? pivot)
nil
@Sdaas
Sdaas / primes.clj
Last active February 1, 2016 06:50
Clojure code to generate the list of first N prime numbers. Uses lazy sequences
;some simple code to determine if a number is prime.
(defn isPrime?
"returns true if the input number is a prime number, false otherwise"
[n]
(let [divisors (range 2 (inc (int (Math/sqrt n))))
remainders (map #(mod n %) divisors)]
(not-any? #(= % 0) remainders)))
(defn nPrimes
"compute list of first N primes and optionally apply a function to each"
Verifying that +soumendradaas is my blockchain ID. https://onename.com/soumendradaas
@Sdaas
Sdaas / lazy.clj
Last active January 13, 2016 05:33
A simple example to demonstrate laziness in Clojure
; a deliberately ineffienct code to generate the nth Fibonacci number
(defn fibonacci
[n]
(if (< n 2)
n
(+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
; generate the first 10 fibonacci numbers
(map fibonacci (range 10))
@Sdaas
Sdaas / read_csv.clj
Last active December 29, 2015 14:06
Read a CSV file and create a list of records
; Given a CSV file and a list of column names, this function loads all the records into a in-memory data structure.
; For example, consider a CSV file that contains the first/last name of persons, their age, and zip code
;
;Smith,John,45,90210
;Frank,Peter,25,90110
;Dalton,Timothy,38,90110
;Hayes,Fred,45,92101
;
;Define a vector that contains the column names [ :firstname :lastname :age :zip ]
;And a vector of functions specifying how each column is to be transformed after reading [ identity identity #(Integer. %) #(Integer. %)]