Skip to content

Instantly share code, notes, and snippets.

@trylks
Last active July 17, 2016 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trylks/a234d1be16fa4ce17fb9effabb3c9014 to your computer and use it in GitHub Desktop.
Save trylks/a234d1be16fa4ce17fb9effabb3c9014 to your computer and use it in GitHub Desktop.
Five small programming problems.

It's Friday night, I'm too tired to do anything useful, but not enough to sleep. I find five small programming katas and I decide that I can start the weekend procrastination already. They are meant to be programmed in the language you feel most comfortable with. Unfortunately, I don't feel comfortable with any language, therefore I used several of them.

PS: Upon closer inspection, probably I should learn Hy.

f1 = (l) ->
r = 0
r += e for e in l
r
f2 = (l) ->
r = i = 0
r += l[i++] while i < l.length
r
f3 = (l) -> l.reduce((a, b) -> a + b)
# because I don't want "cheating" criticism
f4 = (l, a = 0) -> if l[0]? then f4 l[1..], a + l[0] else a
# Bonus (no tail recursion, but JavaScript...):
f5 = (l, a = 0) -> (l[0]? && f5 l[1..], a + l[0]) || a
(defn interleave [x y] (mapcat vector x y))
;-) or alternatively:
(defn myinterleave [x y] (interleave x y))
import scala.language.postfixOps
object FibApp {
// Why do you want to compute a list with 100 Fibonacci
// numbers when you can have all of them in a collection?
// Of course, Haskell is nicer:
// fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
val fib: Stream[BigInt] = 0 #:: 1 #:: (1 to Int.MaxValue)
.iterator
.map { (n: Int) => fib(n - 1) + fib(n) }
.toStream
def main(args: Array[String]) {
println(fib take 100 toVector)
}
}
ponder = lambda n: sum((n[0] - n[i]) / 10 ** i for i in range(1, len(n))) - n[0]
evaluate = lambda s: ponder(list(map(int, s)))
largest = lambda l: ''.join(sorted((str(e) for e in l), key=evaluate))
# yes, I know it's hard to read, but check the JavaScript that it generates!
r for r in (p[-1..][0] for p in ((o.splice i - 1, 0, i; o.join '') for i in [9..1] for o in (
['', '+', '-'][c] for c in p for p in (('00000000' + i.toString 3)[-8..] for i in [0..3**8 - 1])
))) when eval(r) == 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment