## Problem 22

Problem 22 starts with a text file and... well, I'll let you read it here. We start with two helper functions:
```(defn letter-value [c]
(inc (- (int c) (int \A))))

(defn e22-evaluate [s]
(reduce + (map letter-value  s)))```
The first function gives the numeric value for a letter (A=1, etc.) while the second computes the string value for a name string.

The solution is fairly simple:

```(defn euler-22 []
(let [names (read-string (str "[" (slurp "resources/p022_names.txt") "]"))
snames (sort names)
nvals (map e22-evaluate snames)
cnt (count names)
x (range 1 (inc cnt))
zip (map vector x nvals)]
(reduce (fn [z [x y]] (+ z (* x y))) 0 zip)))```
Here, we use slurp to read the file into a string, use str to turn it into an array by bracketing it, and read the string. Next we sort the array and get the evaluation value for all of the names. Next we get a sequence corresponding to 1..(count names) and zip it with the evaluation values. Finally we use reduce to calculate the Problem's answer.

## Problem 23

A number n is abundant if the sum of its proper divisors exceeds n. Problem 23 asks us to find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. These numbers, according to the problem are all less than 28124.

Our first function checks to see if a number is abundant:

```(defn abundant? [N]
(> (reduce + (proper-divisors N)) N))```
Our solution starts by finding all abundant numbers less than 28124 and collecting all numbers that are sums of pairs of abundant numbers. Next we take all numbers less than 28124 and form a set from them. Finally, we remove all the numbers that were formed from sums of abundant numbers and use reduce to get the solution to the problem:
```(defn euler-23 []
(let [count28123 (range 1 28124)
abundants (filter abundant? count28123)
abundant-pairs (combo/cartesian-product abundants abundants)
sums (into #{} (map (fn [[x y]] (+ x y)) abundant-pairs))
non-pairs (set/difference (into #{} count28123) sums)]
(reduce + non-pairs)))```

## Problem 24

This problem asks what the 1000000'th entry is in the list of lexicographically sorted permutations of the digits from 1..9. The solution is a fairly straightforward transliteration:
```(defn euler-24 []
(let [s "0123456789"
ps (combo/permutations s)
nss (map #(apply str %) ps)
snss (sort nss)]
(first (drop 999999 snss))))```
We first form the permutations of the characters from 1-9. We then convert the permutation sequences into strings. Next we sort the strings. Finally, we get the 1000000'th element.

## Problem 25

This problem asks for the index of the first Fibonacci number having 1000 digits:
```(defn euler-25 []
(loop [idx 2
a (bigint 1)
b 1]
;(println cnt a b res)
(if (= (count (str b)) 1000)
idx
(recur (inc idx) b (+ a b)))))```
Our solution simply loops, producing the next Fibonacci number at each iteration until the number of digits is 1000. When this happens, the index is returned.

I hope you've enjoyed these solutions to the first few Project Euler problems.
I enjoy programming. In addition to being my livelihood, it serves as one of my hobbies. I enjoy code kata and am always searching for new exercises. I had heard of Project Euler, but had not participated yet, and decided that this would be my next challenge. I found a site in github purporting to be Clojure solutions of these problems, but they were neither particularly complete nor well-documented. I thought I could do better, learn more Clojure, and refresh my knowledge of number theory along the way. In addition, the solutions are an interesting way to exercise a language.

I expect that these blog posts will be most useful to beginning to intermediate Clojure programmers. I've searched for the most straightforward solutions I could find for these problems and most of them have relatively simple solutions. Note that these solutions are spoilers for the problems. If you want the maximum benefits from these problems, you might want to solve them first yourself. My code has been checked for correctness, but you might find better solutions! Please share in the comments section any solutions you think are better, why, etc.

## The Namespace Declaration

```(ns euler.core
(:require [clojure.math.combinatorics :as combo])
(:require [clojure.math.numeric-tower :as nt])
(:require [clojure.set :as set]))```
We require three Clojure libraries, which are used for a few minor bits of code in the problems - from combo we get combo/cartesian-product, from nt we obtain nt/expt, and from set we use set/difference. These are useful libraries for anyone doing numeric and/or combinatorial problems (which many programming problems ultimately come down to).

## Project Euler - Problem 1

The first PE problem wants the sum of all numbers not divisible by three or five less than 1000. The solution would seem to be so simple that it writes itself:
```(defn euler-1a []
(reduce + (filter #(or (zero? (mod % 3)) (zero? (mod % 5))) (range 1 1000))))```
This is a perfectly fine solution (and gets the correct answer) - we take a collection of numbers from 1 to 999 (the range function), filter the ones divisible by 3 or 5, and sum the remainder using reduce. However, the filter function is a bit opaque; its meaning somewhat obscure. The repetition in the test function is a code smell, as well. We can refactor this code a bit to obtain an easier to understand version:
```(defn factor? [n k] "Is n a factor of k?" (zero? (mod k n)))

(defn euler-1b []
(reduce + (filter #(or (factor? 3 %) (factor? 5 %)) (range 1 1000))))```
This version is not only clearer, but provides the function factor? which will be useful in upcoming problems. But can we do a bit better? The problem description talks about ignoring numbers divisible by 3 or 5. Is there a clearer way to capture that? One solution can be obtained by defining a new function divisible-by?. This function, when passed an integer, returns a function to determine if another number is divisible by that integer:
```(defn divisible-by? "Return a function that tests if a number is divisible by the argument."
[n]
(partial factor? n))

(defn euler-1c []
(reduce + (filter #(or ((divisible-by? 3) %) ((divisible-by? 5) %)) (range 1 1000))))```
This solution is a bit clearer, using the same terminology as the original Project Euler problem. The trade off is that a function call in the function position of a form is a bit unusual. The good news is that this unusual usage calls out the special nature of divisible-by? function which, with any luck, will be examined by anyone looking at the code. This function will also be useful in future problems.

The final version of the code uses the threading macro ->>:

```(defn factor? [n k] "Is n a factor of k?" (zero? (mod k n)))

(defn divisible-by? "Return a function that tests if a number is divisible by the argument."
[n]
(partial factor? n))

(defn euler-1 []
(->> (range 1 1000)
(filter #(or ((divisible-by? 3) %) ((divisible-by? 5) %)))
(reduce +)))```
This version looks a bit more Clojure-ish, even though to a classic Lisper, like me, the string of forms still looks a bit too prog-ish for comfort. In general, the longer the set of nested calls, the clearer the threaded solution becomes. Another choice would be to use an internal let to call out intermediate results like this:
```(defn euler-1d []
(let [count999 (range 1 1000)
nums-to-add (filter #(or ((divisible-by? 3) %) ((divisible-by? 5) %)) count999)]
This form is useful when the intermediate results have some significance (not like in this problem) and naming them makes the algorithm easier to understand (also not like this problem). Generally speaking, a competent Clojure programmer should understand the usage of all of these forms of sequencing calls, be able to convert from one form to another, and select the one that is clearest for use. In the next post, we'll cover problems two through four, touching on lazy-seq, prime generation, and factorization.

## Problem 15

Problem 15 in the Project Euler compendium asks for the number of paths through a 20x20 square lattice starting from (0,0) and ending at (20, 20), using steps of (0,1) and (1, 0). We started by searching for a closed formula for this in the Online Encyclopedia of Integer Sequences. Searching for "paths 2-dimensional square lattice" soon brings us to sequence A000984, which has as one of its comments "The number of lattice paths from (0,0) to (n,n) using steps (1,0) and (0,1)," which fits the problem description perfectly. Although this sequence entry would allow us to simply look the answer up immediately, we will implement the formula which is (2n, n) where (n, k) denotes the binomial coefficient. Thus the solution is given as:
```(defn euler-15 []
(binomial-coefficient (* 2 20) 20))```
To avoid potential issues with stack overflow that might result from using recursive definitions of our algorithm, we use an iterative solution to compute the binomial coefficient: (n, k) = Product[i=1..k](n+1-i)/i. We essentially transliterate the program from the definition - take the integers from 1 to k, map them to their terms in the product, and use reduce to compute the product:
```(defn binomial-coefficient
"Calculate the binomial coefficient."
[n k]
(->> (range 1 (inc k))
(map #(/ (inc (- n %)) %))
(reduce *)))```

## Problem 16

This problem asks for the sum of the digits in the number 2^1000. In our solution, the main dilemmas are whether or not to use a threading macro to express this otherwise one-liner and what to alias the numeric-tower package which must be referenced to compute the exponential:
```(defn euler-16 []
(reduce + (map char->int (str (nt/expt 2 1000)))))```
Here (reading inside out) we compute 2^1000, convert it to a string, map the characters in the string to their integer equivalent, and sum them using reduce. Easy peasy.

## Problem 17

In this problem, we're asked to find the count of all characters in the words for the first 1000 integers, omitting spaces and punctuation. The first task in counting these is to define the words we'll be using to write out the numbers:
```(def units-words ["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"])

(def teens-words ["ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"])

(def tens-words ["zero" "ten" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"])```
Next we define the function that returns the string for numbers less than 100:
```(defn sub-hundred-words [N]
(cond (< N 10) (get units-words N)
(< N 20) (get teens-words (- N 10))
(factor? 10 N) (get tens-words (int (/ N 10)))
:else (let
[tw (get tens-words (int (/ N 10)))
uw (get units-words (mod N 10))]
(str tw uw))))```
Here, we dispatch on the number's linguistic type and take the appropriate words from our word lists. We call this function within the function that computes the string for numbers under 1000:
```(defn sub-thousand-words [N]
(cond (< N 100) (sub-hundred-words N)
(factor? 100 N) (str (get units-words (int (/ N 100))) "hundred")
:else (str
(get units-words (int (/ N 100)))
"hundredand"
(sub-hundred-words (mod N 100)))))```
Again, we use the strategy of dispatching on linguistic type.

In our solution to this problem, we map all the numbers from 1 to 999 to their strings, concatenate them, and count the characters in the large resulting string. We then add on the number of characters from the string "onethousand" giving us the answer:

```(defn euler-17 []
bigstr (apply str (map sub-thousand-words (range 1 1000)))
bigstrcnt (count bigstr)]
;(println bigstr)

## Problem 18

Problem 18 gives us a triangular array of numbers and asks us to find the maximal sum of all paths from the top to the bottom. Here is the array and its access function:
```(def e18triangle [

[95 64]
[17 47 82]
[18 35 87 10]
[20 04 82 47 65]
[19 01 23 75 03 34]
[88 02 77 73 07 63 67]
[99 65 04 28 06 16 70 92]
[41 41 26 56 83 40 80 70 33]
[41 48 72 33 47 32 37 16 94 29]
[53 71 44 65 25 43 91 52 97 51 14]
[70 11 33 28 77 73 17 78 39 68 17 57]
[91 71 52 38 17 14 91 43 58 50 27 29 48]
[63 66 04 68 89 53 67 30 73 16 69 87 40 31]
[04 62 98 27 23  9 70 98 73 93 38 53 60 04 23]])

(defn tri-at [i j]
(get (get e18triangle i 0) j 0))```
The function that finds the maximal path is a simple recursive function:
```(defn max-path
"Find the maximal sum of a length n path through the triangle starting at i j."
[i j n]
(cond (= n 1) (tri-at i j)
(> i (count e18triangle)) 0
:else (let [here (tri-at i j)
l (max-path (inc i) j (dec n))
r (max-path (inc i) (inc j) (dec n))]
(+ here (if (> l r) l r)))))

(def max-path (memoize max-path))```
We compute the maximal sum recursively by checking whether the left or right branch's maximal sum is greater and adding that to the number at the starting point. Our recursion terminates for a path of length 1 which returns the value from the starting point.

Finally, our solution calls max-path to compute the maximal sum path:

```(defn euler-18 []
(max-path 0 0 15))```

## Problem 19

My solution to Problem 19 is not elegant, but it makes up for that by being somewhat straightforward. In it, I set up counters for dates and days of the week. Starting a counter at Monday and January 1, 1900, we increment the day of week and date until we reach January 1, 1901. We then increment a counter each Monday until the date reaches Dec. 31, 2000 when we stop. The Monday counter holds the answer to the problem. The first routine increments the day of week counter (0 = Sunday, etc.):
```(defn inc-dow [dow]
(mod (inc dow) 7))

(defn sunday? [dow]
(= dow 0))```
Next we define the number of days in each month:
`(def days-in-month-non-leap [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])`
One issue with the problem is that it doesn't mention that years ending in 000 are leap years, something that our leap year function takes into account (and which is necessary to solve the problem correctly):
`(defn leap-year? [y] (or (= 0 (mod y 1000)) (and (= 0 (mod y 4)) (not (= 0 (mod y 100))))))`
We zero-index our days of the month and months:
```(defn first-of-month? [[y m d]] (= d 0))

(defn inc-cal [[y m d]]
(let [d' (mod (inc d) (days-in-month y m))
m' (mod (inc m) 12)
y' (inc y)]
[(if (and (= 0 d') (= 0 m')) y' y) (if (= 0 d') m' m) d']))```
After we define the function that increments the calendar date, we define a date comparison function:
```(defn dt-cmp [[y1 m1 d1] [y2 m2 d2]]
(let [ydiff (- y2 y1)
mdiff (- m2 m1)
ddiff (- d2 d1)]
(if (= 0 ydiff)
(if (= 0 mdiff)
ddiff
mdiff)
ydiff)))```
Finally, we have enough functions to easily write our solution (remember that the dates are all zero-indexed by their month and day). The first loop counts from January 1, 1900 to January 1, 1901 while the second loop then counts to December 31, 2000, incrementing the answer counter when Sunday falls on the first day of a month:
```(defn euler-19 []
(loop [e19cnt 0
dt [1900 0 0]
dow 1
dt-cmp-start (dt-cmp dt [1901 0 0])
dt-cmp-end (dt-cmp dt [2000 11 10])]
;(println dt)
(cond (< 0 dt-cmp-start)
(recur 0
(inc-cal dt)
(inc-dow dow)
(dt-cmp (inc-cal dt) [1901 0 0])
(dt-cmp (inc-cal dt) [2000 11 10]))

(and (>= 0 dt-cmp-start) (< 0 dt-cmp-end))
(recur (if (and (first-of-month? dt) (sunday? dow)) (inc e19cnt) e19cnt)
(inc-cal dt)
(inc-dow dow)
(dt-cmp (inc-cal dt) [1901 0 0])
(dt-cmp (inc-cal dt) [2000 11 10]))```

## Problem 20

In this problem we are asked to sum the digits in 100! where ! denotes the factorial function. We first define our factorial function:
```(defn fact' [n acc]
(if (< n 2)
acc
(recur (dec n) (* n acc))))

(defn fact [n] (fact' n (bigint 1)))```
After this is defined, we can transcribe the solution - calculate 100!, turn it into a string, map the string's characters to numbers, and use reduce to sum the digits:
```(defn euler-20 []
(reduce + (map char->int (str (fact 100)))))```

## Problem 21

Problem 21 asks for the sum of all amicable numbers < 10000. We start by defining a function that returns all proper divisors of N which loops through numbers < N/2 checking to see if they divide N evenly:
```(defn proper-divisors [N]
;(println "D" N)
(loop [tst 1
divisors []]
(cond (> tst (/ N 2)) divisors
(factor? tst N) (recur (inc tst) (conj divisors tst))
:else (recur (inc tst) divisors))))

(def proper-divisors (memoize proper-divisors))```
Next comes our amicability check:
```(defn amicable? [[x y]]
(and (= y (reduce + (proper-divisors x))) (= x (reduce + (proper-divisors y)))))```
We'll need to generate pairs of numbers (i, j) to test for amicability - we make sure to only use pairs with i < j to ensure that we don't count pairs twice:
```(defn triangular-indices [N]
(filter (fn [[i j]] (< i j))
(combo/cartesian-product (range 1 (inc N)) (range 1 (inc N)))))```
Finally, we can write our solution:
```(defn euler-21 []
(let [pairs (triangular-indices 10000)
amicable-pairs (filter amicable? pairs)]
(reduce (fn [z [x y]] (+ x y z)) 0 amicable-pairs)))```
 There is an old open source saying that "Many eyes make all bugs shallow". So what happened with the now infamous heartbleed bug? Supposedly, open source code is less prone to these kind of security breaches because so many eyes can look at it. In addition, open source is supposed to have better fix properties because fixes can be turned around and disseminated quickly. However, something happened with heartbleed.One issue is that most eyes are shallow, not deep. If code is opaque (as is the case for Open SSL) than it doesn't matter how many eyes are on it - bugs can be hiding in the submerged depths where only the deepest eyes are likely to stumble upon them. And it is likely that the number of deep eyes looking at the code is still as small as is usual in any other software, closed or open.The second issue is that the decentralized nature of open source movement actually harms as much as helps with dissemination. Commercial software, with its lists of registered users at least has a starting point to make issues known and patches distributed. Open source projects tend to have much more chaotic and imprecise means of the same. No one, commercial nor open source, can be sure that software will be patched - but at least commercial software has a starting point.So, what can the open source community learn from this issue?First, make sure that the code is written in the clearest possible way. Make sure that as many eyes can peer into its depths without obscuring murk. It may hurt performance, especially with ubiquitous software like Open SSL, but the alternative, as we have seen, sucks. An old wise man once said that "Premature optimization is the root of all evil." Although this is true, code that needs to be secure cannot afford any optimization - the code must be lucid enough to be easily understood and checked, lest hard-to-detect security defects sneak in. God knows you probably shouldn't be wrapping OS calls (the putative source of this defect).Second, for code as ubiquitous and as important for security as this code is, independent review by people qualified to do so is vital. Most projects have only people related to the project reviewing the code. This is probably fine for the latest Zul Zebra Zaga game, or other kind of fart app, but not so good for a piece of code upon which most of the current internet's security rests.Third, it is almost certain that the crucial parts of the Open SSL code, had it been written in a simple intelligible form would have been small enough to be formally verified. And, again, given the criticality of this code to secure operation of the internet, it should have been done.Do all of these ideas have costs? Yes. But so do bugs that have as high an impact as heartbleed appears to. We've known how to not come a cropper when the stakes are high for at least the past thirty years. The fact that these kinds of issues are still arriving (and in such crucial code) is an embarrassment to the whole industry.
 The latest CD from This, Not This!, Waiting for the World, has been released! To celebrate, we're holding a CD Release Party at the Lounge of the Hawthorne Theater in Portland at 9 pm on 29 March. Our old friend Mike Ailes will be there with his band, Aina Haina, to open for us. It's going to be a great show, with lots of songs from both our first and the new CD. If you'd like to have your own copy of the new CD (or the first one), they'll be on sale there for \$5. Of course, you can also buy it from iTunes or from CDBaby. I'm really proud of this album, as it's the first I've recorded and mixed for the band. And, of course, come out to see us and Aina Haina play!
 I'm doing final touch-up on the mixing and mastering for the next single from This, Not This! - a song I wrote called Dimensions. It's been a favorite in our live shows and I'm looking forward to having it finished and up on iTunes and Amazon Music sometime next week. Frankly, I did a car check on my mastering for the single and I think it actually sounds better to me than the songs on the EP which we sent out for "professional" mastering (of course, I'm biased). This one really rocks, so take a listen at the streaming "pre-release" on the This, Not This! website.  Look for it when it's out there, buy it, and enjoy. Next up? Mixing one of Phil's songs - Touch of Magic - and recording harmony parts on another one of mine - Waiting for the World.Dave Wakeling and his wife, Candace Schimp, and I will have a three hour acoustic show at Urban Decanter, a wine shop and restaurant at 2030 Main Street, Forest Grove at 7 pm on October 20 (this coming Saturday). The material will be mainly Dave's, with some covers thrown in, but I'll sing a few of my songs, too, including a couple that have never been performed live before - Icarus and Stupid Genius. I'll be playing bass and singing harmony, for the most part, but will also help Dave out on guitar on some songs. Dave, Candee, and I always have a great time performing together - wonderful songs and harmonies and you might get to hear Dave call me a wimp, live, for not wanting to play certain songs so much. A good time will be had by all, so get there and listen.On December 7, Dave and I will be playing with This, Not This! (our electric band) at the Mt. Tabor Theater at 4811 Southeast Hawthorne Boulevard in Portland. As usual, about half the songs will be mine and I'll be playing bass and singing backup. Appearing with us will be Aina Haina and Ill Lucid Onset. Aina Haina features our old buddy Mike Ailes, who has opened for us before. This is, however, the first time we get to hear him with his band - we think it will be really great. We met Ill Lucid Onset when we played the Clark County Fair in August - they had a really good show and some great songs. We're looking forward to playing with all of these guys.Also, if you haven't heard them yet, check out Dusty Santamaria and his band, The Singing Knives. Their online material doesn't do them justice - Dusty is a riveting performer and his performances shouldn't be missed. Sherry and I have been trying to get This, Not This! and Dusty together for a show for... well, for a long time. We hope to have a show with them soon (probably sometime early next year) - negotiations with Dusty and various venues are underway. Keep checking back to the This, Not This! website for more information. Or better yet, go there and join our mailing list, after which you can be notified of all of our upcoming stuff! See you at a show soon!
 Joe Gilder over at Home Studio Corner has a some good tips about balancing levels in songs. I'd add one other little bit of advice with respect to overall dynamics: One way to judge whether a mix's levels are right is by listening to the relative levels of "focal points" in the song.What's a focal point? At any point in time, one of the parts is usually the focus of the song, whether it's the vocal or a lead or a drum fill. Use automation to keep these focal points even in perceived volume (+/- a few dB) and make them louder than the rest of the elements in the mix (they are, after all, the focus at that time). Because your final bus compressor will key off the loudest element in the mix (OK, it's a bit more complicated than that, but I don't want to go into it now), the compression will be more even and the overall mix will have fewer compression artifacts. As an added benefit, it will make the mastering process easier.I can hear the complaining now - "But, Frank, I've just reduced the drum volume to put them in the back of the soundfield. Now you're telling me to turn up fills?" Yes. I'm telling you to bring the drums forward on fills, assuming the fill happens to be the focal point at that time. Drummers tend to hit fills harder than normal rhythm strokes, so we're used to hearing them get louder - it works psycho-acoustically and a bit more volume won't break the fourth wall. Same way with that killer bass run. Or that interstitial guitar lick. You don't even have to increase their volume that much - you can also use automation to slap an EQ on the focal points to boost them in the presence band (3-6 KHz, season to taste) or turn down their reverb a bit. It will make them stand out without as much overall level change - we're talking psycho-acoustics here, not numerical equality.Getting focal point levels right will go a long way towards making your mix even. And an even mix is one of the hallmarks of a good mix.
 The posts will tend to be a bit late on Monday, Friday, and some Thursdays.Mondays and Fridays can be explained by two photos: The first is me after my freshman year in college when I was working construction, and practicing or playing with a band three or four nights a week. The second is me now (well, actually about a year ago). You may notice the size differential (Note to the visually impaired: I appear to be much narrower in the first picture. I am also not wearing a tie)...In short, I am trying to get closer to what I looked like in the first photo than to what I look like in the second. To do this, I am cutting my caloric intake drastically and walking and exercising more. Part of this routine is taking the train to the office on Mondays and Fridays. As I have to walk about a mile to and from the train on each end of the trip, taking the train allows me to walk four miles each of these days. This doesn't greatly affect my daily routine, except for blocking the early pre-job hours to work on the daily essay. Because of this, Monday's and Friday's posts may be delayed slightly.But what about Thursday, you may ask? That's a bit more mundane - I have a some standing morning meetings that could get in the way on Thursdays. Other than for these minor inconveniences, you can expect my post fairly early each morning.Oh yeah - two other things... I'm not going to post on weekends (mainly because I think I deserve some days off) and I no longer have guitar face when I play (I hope).
 The assistant and myself will be hanging bass traps and fishing cables through walls. Still waiting for the headphone distribution system to arrive. Next stop - wiring. It's getting closer...