Skip to content

Instantly share code, notes, and snippets.

@dbyrne
dbyrne / gist:424780
Created June 4, 2010 01:25
Project Euler #2 - Ruby
fibs = Fiber.new do
x1, x2 = 1, 2
loop do
Fiber.yield x1
x1, x2 = x2, x2+x1
end
end
sum = 0
begin
@dbyrne
dbyrne / gist:430074
Created June 8, 2010 14:14
Project Euler #18 & #67 - Clojure
(with-test
(defn maximal-path [tree-file]
(with-open [rdr (BufferedReader. (FileReader. tree-file))]
(let [lines (reverse
(map
(fn [x]
(map #(Integer. %) (re-seq #"\d+" x)))
(line-seq rdr)))]
(first
(reduce
@dbyrne
dbyrne / gist:874621
Created March 17, 2011 16:27
Project Euler #18 & #67 - Haskell
maxPath (x:y:xs) = maxPath (z:xs)
where z = zipWith (+) (zipWith max x (tail x)) y
maxPath [[x]] = x
convert = map (map read . words)
prob67 = show . maxPath . reverse . convert . lines
main = readFile "triangle.txt" >>= putStrLn . prob67
@dbyrne
dbyrne / gist:877698
Created March 19, 2011 18:39
Project Euler #24 - Clojure
(def digits (sorted-set 0 1 2 3 4 5 6 7 8 9))
(defn nextLex [substr digits]
(let [lex (apply str substr digits)]
(lazy-cat
[lex]
(loop [s (vec lex)
d (sorted-set)]
(let [i (- (int (peek s)) 48)
d (conj d i)]
@dbyrne
dbyrne / gist:881577
Created March 22, 2011 17:00
Project Euler #2 - Scala
def fib(v1:Int, v2:Int): Stream[Int] = v1 match {
case 0 => Stream.cons(1,fib(1,0))
case 1 => Stream.cons(2,fib(2,1))
case _ => Stream.cons(v1+v2,fib(v1+v2,v1))
}
val fibStream = fib(0,0)
fibStream.filter(_%2 == 0).takeWhile(_ <= 4000000).foldLeft(0)(_+_) //returns 4613732
@dbyrne
dbyrne / gist:881580
Created March 22, 2011 17:01
Project Euler #5 - Scala
val divisors = List(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
def divisibleByAll(x:Int, divs:List[Int]):Boolean = divs match {
case Nil => true
case _ => if (x % divs.head == 0) {
return divisibleByAll(x, divs.tail)
} else {
return false
}
}
@dbyrne
dbyrne / gist:882630
Created March 23, 2011 04:44
Project Euler #1 - Haskell
multiples :: [Int] -> [Int]
multiples = filter (\x -> (mod x 3) == 0 || (mod x 5) == 0)
main = putStrLn $ (show . sum . multiples) [3..999]
@dbyrne
dbyrne / gist:882641
Created March 23, 2011 04:55
Project Euler #2 - Haskell
fibs = 1 : 2 : zipWith (+) fibs (tail fibs)
prob2 = sum $ takeWhile (< 4000000) $ filter even fibs
main = putStrLn (show prob2)
@dbyrne
dbyrne / gist:887605
Created March 25, 2011 20:50
Project Euler #36 - Clojure
(defn palindrome? [x]
(= x (apply str (reverse x))))
(defn palindromic-2-10? [x]
(let [dec (Integer/toString x)
bin (Integer/toString x 2)]
(and (palindrome? dec) (palindrome? bin))))
(with-test
(defn prob-36 []
@dbyrne
dbyrne / gist:908732
Created April 7, 2011 21:11
Micro-benchmark
import collection.breakOut
val s = (0 until 1000000).toSet
def func(i: Int) = "" + i + i
Profiling.timed(Profiling.printTime("Jesper (original): ")){
(s map { i => i -> func(i) }).toMap
}