December 30, 2008

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110 therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142 so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.


(defun divisor-p (num divisor)
"Tests if divisor is a divisor of num"
(zerop (mod num divisor)))

(defun divisors (num)
"Returns a list of num's divisors"
(do ((i 2 (1+ i))
(result '(1)))
((> i (isqrt num)) (remove-duplicates result))
(when (divisor-p num i)
(setf result (append result (list i (/ num i)))))))

(defun sum-divisors (num)
"Sums the divisors of num"
(reduce #'+ (divisors num)))

(defun amicable-p (num)
"Tests if num is amicable"
(let ((divisors-sum (sum-divisors num)))
(when (and (= num (sum-divisors divisors-sum))
(not (= num divisors-sum)))
num)))

(defun amicable-sum (limit)
"Returns the sum of all amicable numbers below limit"
(do ((i 1 (1+ i))
(result 0))
((>= i limit) result)
(when (amicable-p i)
(incf result i))))

(defun euler-21 ()
(amicable-sum 10000))

n! means n × (n − 1) × ... × 3 × 2 × 1

Find the sum of the digits in the number 100!


(defun add-digits (num)
"Returns the sum of the number's digits"
(let ((sum 0)
(num-string (write-to-string num)))
(dotimes (i (length num-string))
(setf sum (+ sum (digit-char-p (schar num-string i)))))
sum))

(defun fact (num)
(if (= num 1)
1
(* num (fact (1- num)))))

(defun euler-20 ()
(add-digits (fact 100)))

You are given the following information, but you may prefer to do some research for yourself.

* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?



(defconstant +months+ '("Jan" "Feb" "Mar" "April" "May" "June"
"July" "Aug" "Sept" "Oct" "Nov" "Dec"))

(defconstant +days+ '("Sun" "Mon" "Tue" "Wed" "Thurs" "Fri" "Sat"))

(defun days-in-month (month year)
"Returns the number of days in the month given the month and year"
(cond ((member month '("Sept" "April" "June" "Nov") :test #'string=)
30)
((and (string= "Feb" month) (zerop (mod year 4))) 29)
((string= "Feb" month) 28)
(t 31)))

(defun move-ahead (today days)
"Moves ahead a number of days and returns the day.
Example: (move-ahead 'Mon' 3) => 'Thurs'
(move-ahead 'Sun' 8) => 'Mon'"
(let ((cur-day-num (position today +days+ :test #'string=)))
(elt +days+ (mod (+ cur-day-num days) 7))))

(defun euler-19 ()
(let ((today "Mon")
(result 0))
(loop for year from 1900 to 2000 do
(dolist (month +months+)
(when (and (string= today "Sun") (> year 1900))
(incf result))
(setf today (move-ahead today (days-in-month month year)))))
result))

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 5
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

75
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 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows it cannot be solved by brute force, and requires a clever method! ;o)



This problem is best solved by starting at the base and working up. Increment the number above each pair of nodes by the largest of the two nodes, and continue until you reach the top.
(defconstant +triangle+ 
'(
(75)
(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 09 70 98 73 93 38 53 60 04 23)))

(defun bottom-two-rows (triangle)
"Returns the bottom two rows of a triangle"
(list (car (last (butlast triangle)))
(car (last triangle))))

(defun first-node-and-stems (triangle)
"Given two rows of a triangle, returns the first node and the
first node's stems.
Example: (first-node-and-stems '((2 4 6) (8 5 9 3))) => 2 8 5"
(let ((node (caar triangle))
(left-stem (first (cadr triangle)))
(right-stem (second (cadr triangle))))
(values node left-stem right-stem)))

(defun max-node (node left-stem right-stem)
(max (+ node left-stem)
(+ node right-stem)))

(defun sum-stems (rows)
"Given two adjacent rows of a triangle, returns a list of the
maximum total of the stems for each node.
Example: (sum-stems '((2 4 6) (8 5 9 3))) => (10 13 15)"
(when (first rows)
(multiple-value-bind (node left-stem right-stem)
(first-node-and-stems rows)
(cons (max-node node left-stem right-stem)
(sum-stems (mapcar #'cdr rows))))))

(defun max-route (triangle)
"Returns the sum of the route that produces the maximum total of
the given triangle"
(if (= (length triangle) 2)
(multiple-value-bind (node left-stem right-stem)
(first-node-and-stems triangle)
(max-node node left-stem right-stem))
(max-route (append (butlast (butlast triangle))
(list (sum-stems
(bottom-two-rows triangle)))))))

(defun euler-18 ()
(max-route +triangle+))

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.


(defun remove-hyphens (str)
"Removes any hyphens from str"
(remove #\- str))

(defun remove-spaces (str)
"Removes any spaces from str"
(remove #\Space str))

(defun euler-17 ()
(+ (loop for i from 1 to 1000 sum
(length (remove-hyphens (remove-spaces
(format nil "~R" i)))))
;; SBCL does not include the word 'and', so add
;; those letters also
(* 3 99 9)))

December 21, 2008

2^(15) = 32768 and the sum of its digits is
3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^(1000)?


(defun add-digits (num)
"Returns the sum of the number's digits"
(let ((sum 0)
(num-string (write-to-string num)))
(dotimes (i (length num-string))
(setf sum (+ sum (digit-char-p (schar num-string i)))))
sum))

(defun euler-16 ()
(add-digits (expt 2 1000)))

December 20, 2008

Starting in the top left corner of a 2×2 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there through a 20×20 grid?


Since we can not backtrack, we can only move down and right. If we have a 2x2 grid, this means every route consists of exactly 2 right moves and 2 down moves. We can think of the routes as a set of moves, such as (d d r r), and the total number of routes will be all the different combinations of the set minus the identical combinations. To find the number of unique combinations, suppose we have the route (d d r r). Treating each move distinctly, lets write the set as (d1 d2 r1 r2). Notice how this route is equal to the route(d2 d1 r2 r1), and we only want to count this as one route. It turns out that the number of unique routes per combination is 2!*2! = 4: (d1 d2 r1 r2) (d1 d2 r2 r1) (d2 d1 r1 r2)(d2 d1 r2 r1). This means each route in the set of all possible route combinations, 4!, will have 3 other identical routes in the set, resulting in 4!/(2!2!) unique routes. This formula applies to larger grids as well.

(defun factorial (n &optional (acc 1))
(if (<= n 1)
acc
(factorial (- n 1) (* acc n))))

(defun grid-routes (x-dim y-dim)
"Calculates the number of routes from the top left corner
of a grid to the bottom right corner, without backtracking"
(let ((total-number-of-moves (+ x-dim y-dim)))
(/ (factorial total-number-of-moves)
(* (factorial x-dim)
(factorial y-dim)))))

(defun euler-15 ()
(grid-routes 20 20))

December 18, 2008

The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.


I listed two solutions to this problem in Common Lisp below. alt-euler-14 strictly follows the formula and computes the solution inefficiently. euler-14 stores computed values in a hash table so it never applies the formula to the same number more than once.

;;; *collatz-table* holds the number of terms for previously performed
;;; collatz calculations. For example, say that we already found
;;; the number of terms to compute 10, which is 7. If we compute
;;; the number of terms for 13, as in the example above, when it
;;; reaches 10 it will find this value in the table and add 7 to
;;; the current terms value to get the answer.
(defparameter *collatz-table* (make-hash-table))

(defun collatz (num)
(cond ((= num 1) 1)
((gethash num *collatz-table*)
(gethash num *collatz-table*))
((evenp num)
(setf (gethash num *collatz-table*)
(1+ (collatz (/ num 2)))))
(t (setf (gethash num *collatz-table*)
(1+ (collatz (1+ (* 3 num))))))))

(defun euler-14 ()
(let ((answer 0)
(max-terms 0))
(do ((x 1 (1+ x)))
((>= x 1000000) answer)
(let ((terms-of-x (collatz x)))
(when (> terms-of-x max-terms)
(setf max-terms terms-of-x
answer x))))))

(defun alt-collatz (num &optional (term 1))
(cond ((= num 1) term)
((evenp num) (alt-collatz (/ num 2) (1+ term)))
(t (alt-collatz (1+ (* 3 num)) (1+ term)))))

(defun alt-euler-14 ()
(let ((answer 0)
(max-terms 0))
(do ((x 1 (1+ x)))
((>= x 1000000) answer)
(let ((terms-of-x (alt-collatz x)))
(when (> terms-of-x max-terms)
(setf max-terms terms-of-x
answer x))))))

Alt-euler-14 took 8.5 seconds. euler-14's first run took 3 seconds, but the second run took 0.28 seconds. This speed came at a cost of more memory.

December 7, 2008

I'm currenlty working on a spring application that uses Spring Security to manage logins and page access on my site. After following the general process to set up Spring Security, as outlined in many online tutorials, you can retrieve the user information stored in the session as follows:

final SecurityContext sc = SecurityContextHolder.getContext();
final Authentication auth = sc.getAuthentication();
auth.getPrincipal();


In a typical security setup auth.getPrincipal will return a Spring Security user object which contains the current user's login name, password and roles. For my application, I wanted this object to also contain the user's unique id. This can be accomplished by extending two classes in a typical spring security setup.

In Spring Security, the authenticationDao is responsible for looking up the user's credentials. In my application the users are stored in a database, so at first I used JdbcDaoImpl for this. I wanted to return the user id as well, so this class needed some slight modifications. My new class extended JdbcDaoImpl and looks similar to this:
public class JdbcDaoUserIdImpl extends JdbcDaoImpl {

/**
* Injected by spring
*/
private UserDao userDao;

public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

/**
* Returns a UserDetails object that also contains the user's unique id
*
* @see org.springframework.security.userdetails.jdbc.JdbcDaoImpl#createUserDetails(java.lang.String,
* org.springframework.security.userdetails.UserDetails,
* org.springframework.security.GrantedAuthority[])
*/
protected UserDetails createUserDetails(String username,
UserDetails userFromUserQuery,
GrantedAuthority[] combinedAuthorities) {
String returnUsername = userFromUserQuery.getUsername();

if (!isUsernameBasedPrimaryKey()) {
returnUsername = username;
}

User user = userDao.getUser(username);

return new UserId(user.getId(), returnUsername, userFromUserQuery
.getPassword(), userFromUserQuery.isEnabled(), true, true,
true, combinedAuthorities);
}

}


Notice that instead of returning a Spring Security User object it returns a UserId object. This class extends the User class and simply has one additional field containing, as you guessed, the user Id. It looks something like this:
public class UserId extends User {

private static final long serialVersionUID = -8275492272371421013L;
private long id;

public UserId( long id, String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, GrantedAuthority[] authorities)
throws IllegalArgumentException {
super(username, password, enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities);
this.id = id;
}

/**
* Sets the user's unique id in the server's session object
* @param id the user's id
*/
public void setId(long id) {
this.id = id;
}

/**
*
* @return the user's unique id
*/
public long getId() {
return this.id;
}

public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString()).append(": ");
sb.append("Id: ").append(this.id).append("; ");
return sb.toString();
}


}


After updating the security configuration files to use the new classes , we can store as many details as we like in each session. To get to the details, in your servlets cast the auth.getPrincipal object to your new class, in our case UserId.

at Sunday, December 07, 2008 Labels: Posted by Billy 0 comments

Abstract: When in System > Preferences > Screen Resolution, if you change the refresh rate and you monitor goes blank, reboot into the terminal, then from your home directory remove the file .config/monitors.xml



This week I was playing around with different desktop wallpapers for Ubuntu and wandered off into the screen resolution settings for gnome. Now, it has been a while since I configured my current monitor, so when I saw I had options for a faster refresh rate I just had to modify it, even though I should have known my monitor didn't support higher rates. I increased the refresh rate and my monitor immediately went blank, then displayed the message "Mode not supported". I patiently waited a couple minutes to see if Ubuntu would automatically revert the settings, but nothing happened. I rebooted the system.

I figured I would have to manually edit the xorg.conf file, something I've done before and have no problem doing. But to my surprise the login splash screen displayed. I logged in and the screen went blank with the same message blinking.

Evidently it must be some gnome user configuration rather than an xorg.conf problem since it happens only after logging in. From another computer I googled for answers, but none seemed to address my particular problem; most dealt with xorg configurations. Then I found a post stating gnome stores settings files in a series of .gnome directories, and removing these files would change my desktop setting back to default.

After booting into a terminal, I searched the files in those directories but none seemed to deal with monitor configurations. Desperate, I deleted them all. I went to log in again but the screen turned blank once again.

To solve this problem, I knew I had to find the configuration file that gnome modifies when configuring the monitor. I created a new user and logged in and opened Monitor Resolutions window. I changed the resolution this time, and saved the settings.

To find files that were recently modified, from your home directory type the command ls -atu | less, which list all files and directories and sorts by time last modified. If you were following my steps, you should notice that the .config directory was modified. Issuing the command again in that directory reveals that a file called monitors.xml was recently modified. Here lies the problem.

The monitors.xml file contains the monitor settings for each user, including screen refresh rate. I simply deleted this file, and everything returned to normal. All this hassle could have easily been resolved if the monitor settings revert back to the previous settings if the user doesn't confirm the changes within a few seconds time. Despite all the trouble, Ubuntu is still my favorite operating system.

November 30, 2008

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.


Common Lisp handles big numbers for you, so this problem is very easy.

(defparameter numbers '(
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690 ))

(defun euler-13 ()
(subseq (write-to-string (apply #'+ numbers))
0 10))

November 29, 2008

What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 2020 grid?


This solution scans four rows at a time, saves the max adjacent product and scans the next four rows.

(defparameter *grid*
'((08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08)
(49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00)
(81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65)
(52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91)
(22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80)
(24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50)
(32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70)
(67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21)
(24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72)
(21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95)
(78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92)
(16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57)
(86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58)
(19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40)
(04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66)
(88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69)
(04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36)
(20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16)
(20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54)
(01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48)))

(defun max-r (grid)
"Returns the maximum product of each rows elements"
(apply #'max (mapcar #'(lambda (lst) (apply #'* lst))
grid)))

(defun max-c (grid)
"Returns the maximum product of each columns elements"
;; Transpose the grid then call max-r
(max-r (apply #'mapcar #'list grid)))

(defun diag-prod (grid &optional (accum 1))
"Returns the product of the grids diagonal elements,
starting from the top left to the bottom right.
The function works recursively. If there is a top-left
element in the grid, it multiplies accum by the element.
Then it calls itself with the top row and first column
of the grid removed"
(if grid
(diag-prod (mapcar #'cdr (cdr grid)) (* accum (caar grid)))
accum))

(defun max-d (grid)
"Returns the maximum product of each diagonals elements"
(max (diag-prod grid)
(diag-prod (mapcar #'reverse grid))))

(defun max-adj (grid)
"Returns the maximum product of the grids adjacent elements.
Elements are multiplied in rows, columns, and diagonals"
(max (max-r grid) (max-c grid) (max-d grid)))

(defun max-in-4byX (grid &optional (result 0))
"Returns the maximum product of 4 adjacent elements in
a grid with 4 rows and a variable number of columns"
(if (< (length (car grid)) 4)
result
(let* ((subgrid (mapcar #'(lambda (lst)
(subseq lst 0 4))
grid))
(max-in-subgrid (max-adj subgrid))
(cur-result (cond ((< result max-in-subgrid) max-in-subgrid)
(t result))))
(max-in-4byX (mapcar #'cdr grid) cur-result))))

(defun euler-11 (grid &optional (result 0))
"Calculates the max prod of 4 adjacent elements in the top 4 rows
of a grid, removes the top row and repeats. Returns the maximum
product of 4 adjacent numbers in the entire grid"
(if (< (length grid) 4)
result
(let* ((top-4-rows (subseq grid 0 4))
(max-in-top-4 (max-in-4byX top-4-rows))
(cur-result (cond ((< result max-in-top-4) max-in-top-4)
(t result))))
(euler-11 (cdr grid) cur-result))))

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.

This solution tests if a number is prime by testing if the number's smallest divisor is equal to itself. It then loops through all the odd numbers by two and sums the primes.

;;; Functions for testing if a number is prime
(defun square (x) (* x x))

(defun dividesp (a b)
(zerop (mod b a)))

(defun find-divisor (n test-divisor)
(cond ((> (square test-divisor) n) n)
((dividesp test-divisor n) test-divisor)
(t (find-divisor n (+ test-divisor 1)))))

(defun smallest-divisor (n)
(find-divisor n 2))

(defun primep (n)
(= n (smallest-divisor n)))

;;; End of prime functions

(defun sum-of-primes-below (num)
"Returns the sum of all the prime numbers below num"
(+ 2 (loop for i from 3 to num by 2 when (primep i) sum i)))

(defun euler-10 ()
(sum-of-primes-below 2000000))

A Pythagorean triplet is a set of three natural numbers, a b c, for which a2 + b2 = c2.

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.


A brute-force solution in Common Lisp:

(defun sqrd (x)
(* x x))

(defun pythag-trip-p (a b c)
"Tests if a b and c satisfies the pythagorean equation"
(eq (sqrd c)
(+ (sqrd a) (sqrd b))))

(defun sum-eq-1000-p (a b c)
"Tests if the sum equals 100"
(= 1000 (+ a b c)))

(defun euler-9 ()
(let ((result nil))
(loop for a from 1 to 1000 until (not (null result)) do
(loop for b from 1 to 1000 until (not (null result)) do
(let ((c (sqrt (+ (sqrd a) (sqrd b)))))
(when (sum-eq-1000-p a b c)
(print (list a b c))
(setf result (list a b c))))))
(apply #'* result)))

Find the greatest product of five consecutive digits in the 1000-digit number.


;;; Use emacs to paste and format the 1000 digit number
(defvar long-number '(
7 3 1 6 7 1 7 6 5 3 1 3 3 0 6 2 4 9 1 9 2 2 5 1 1 9 6 7 4 4 2 6 5 7 4
7 4 2 3 5 5 3 4 9 1 9 4 9 3 4 9 6 9 8 3 5 2 0 3 1 2 7 7 4 5 0 6 3 2 6
2 3 9 5 7 8 3 1 8 0 1 6 9 8 4 8 0 1 8 6 9 4 7 8 8 5 1 8 4 3 8 5 8 6 1
5 6 0 7 8 9 1 1 2 9 4 9 4 9 5 4 5 9 5 0 1 7 3 7 9 5 8 3 3 1 9 5 2 8 5
3 2 0 8 8 0 5 5 1 1 1 2 5 4 0 6 9 8 7 4 7 1 5 8 5 2 3 8 6 3 0 5 0 7 1
5 6 9 3 2 9 0 9 6 3 2 9 5 2 2 7 4 4 3 0 4 3 5 5 7 6 6 8 9 6 6 4 8 9 5
0 4 4 5 2 4 4 5 2 3 1 6 1 7 3 1 8 5 6 4 0 3 0 9 8 7 1 1 1 2 1 7 2 2 3
8 3 1 1 3 6 2 2 2 9 8 9 3 4 2 3 3 8 0 3 0 8 1 3 5 3 3 6 2 7 6 6 1 4 2
8 2 8 0 6 4 4 4 4 8 6 6 4 5 2 3 8 7 4 9 3 0 3 5 8 9 0 7 2 9 6 2 9 0 4
9 1 5 6 0 4 4 0 7 7 2 3 9 0 7 1 3 8 1 0 5 1 5 8 5 9 3 0 7 9 6 0 8 6 6
7 0 1 7 2 4 2 7 1 2 1 8 8 3 9 9 8 7 9 7 9 0 8 7 9 2 2 7 4 9 2 1 9 0 1
6 9 9 7 2 0 8 8 8 0 9 3 7 7 6 6 5 7 2 7 3 3 3 0 0 1 0 5 3 3 6 7 8 8 1
2 2 0 2 3 5 4 2 1 8 0 9 7 5 1 2 5 4 5 4 0 5 9 4 7 5 2 2 4 3 5 2 5 8 4
9 0 7 7 1 1 6 7 0 5 5 6 0 1 3 6 0 4 8 3 9 5 8 6 4 4 6 7 0 6 3 2 4 4 1
5 7 2 2 1 5 5 3 9 7 5 3 6 9 7 8 1 7 9 7 7 8 4 6 1 7 4 0 6 4 9 5 5 1 4
9 2 9 0 8 6 2 5 6 9 3 2 1 9 7 8 4 6 8 6 2 2 4 8 2 8 3 9 7 2 2 4 1 3 7
5 6 5 7 0 5 6 0 5 7 4 9 0 2 6 1 4 0 7 9 7 2 9 6 8 6 5 2 4 1 4 5 3 5 1
0 0 4 7 4 8 2 1 6 6 3 7 0 4 8 4 4 0 3 1 9 9 8 9 0 0 0 8 8 9 5 2 4 3 4
5 0 6 5 8 5 4 1 2 2 7 5 8 8 6 6 6 8 8 1 1 6 4 2 7 1 7 1 4 7 9 9 2 4 4
4 2 9 2 8 2 3 0 8 6 3 4 6 5 6 7 4 8 1 3 9 1 9 1 2 3 1 6 2 8 2 4 5 8 6
1 7 8 6 6 4 5 8 3 5 9 1 2 4 5 6 6 5 2 9 4 7 6 5 4 5 6 8 2 8 4 8 9 1 2
8 8 3 1 4 2 6 0 7 6 9 0 0 4 2 2 4 2 1 9 0 2 2 6 7 1 0 5 5 6 2 6 3 2 1
1 1 1 1 0 9 3 7 0 5 4 4 2 1 7 5 0 6 9 4 1 6 5 8 9 6 0 4 0 8 0 7 1 9 8
4 0 3 8 5 0 9 6 2 4 5 5 4 4 4 3 6 2 9 8 1 2 3 0 9 8 7 8 7 9 9 2 7 2 4
4 2 8 4 9 0 9 1 8 8 8 4 5 8 0 1 5 6 1 6 6 0 9 7 9 1 9 1 3 3 8 7 5 4 9
9 2 0 0 5 2 4 0 6 3 6 8 9 9 1 2 5 6 0 7 1 7 6 0 6 0 5 8 8 6 1 1 6 4 6
7 1 0 9 4 0 5 0 7 7 5 4 1 0 0 2 2 5 6 9 8 3 1 5 5 2 0 0 0 5 5 9 3 5 7
2 9 7 2 5 7 1 6 3 6 2 6 9 5 6 1 8 8 2 6 7 0 4 2 8 2 5 2 4 8 3 6 0 0 8
2 3 2 5 7 5 3 0 4 2 0 7 5 2 9 6 3 4 5 0))

(defun euler-8 (num &optional (current-max 0))
"Returns the greatest product of five consecutive digits in the
given number. The digits must be supplied as a list"
(if (< (length num) 5)
current-max
(let ((product (apply #'* (subseq num 0 5))))
(if (> product current-max)
(euler-8 (cdr num) product)
(euler-8 (cdr num) current-max)))))

SICP Exerice 1.29
Simpson's Rule is a more accurate method of numerical integration than the method illustrated above. Using Simpson's Rule, the integral of a function f between a and b is approximated as

(h/3)(y0 + 4y1 + 2y2 + 4y3 + 2y4 + ...+ 2yn-2 + 4yn-4 + yn)

where h = (b - a)/n, for some even integer n, and yk = f(a + kh). (Increasing n increases the accuracy of the approximation.) Define a procedure that takes as arguments f, a, b, and n and returns the value of the integral, computed using Simpson's Rule. Use your procedure to integrate cube between 0 and 1 (with n = 100 and n = 1000), and compare the results to those of the integral procedure shown above.


(defun cube (x) (* x x x))

(defun sum (term a next b)
(if (> a b)
0
(+ (funcall term a)
(sum term (funcall next a) next b))))

(defun integral (f a b n)
(let ((h (/ (- b a) n)))
(labels ((yk (k)
(funcall f (+ a (* k h))))
(inc2 (n) (+ n 2)))
(* (/ h 3)
(+ (yk 0)
(* 4 (sum #'yk 1 #'inc2 (- n 1)))
(* 2 (sum #'yk 2 #'inc2 (- n 2)))
(yk n))))))



SICP Exercise 1.30
The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:

(define (sum term a next b)
(define (iter a result)
(if <??>
<??>
(iter <??> <??>)))
(iter <??> <??>))


(defun new-sum (term a next b)
(labels ((iter (a result)
(if (> a b)
result
(iter (funcall next a)
(+ result (funcall term a))))))
(iter a 0)))

(defun inc (x) (+ x 1))



SICP Exercise 1.31
a. The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures.51 Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Show how to define factorial in terms of product. Also use product to compute approximations to using the formula

(pie/4)=((2/3)(4/3)(4/5)(6/5)(6/7)(8/7)...)

b. If your product procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.


(defun product (term a next b)
(if (> a b)
1
(* (funcall term a)
(product term (funcall next a) next b))))

(defun new-product (term a next b)
(labels ((iter (a result)
(if (> a b)
result
(iter (funcall next a) (* result (funcall term a))))))
(iter a 1)))

(defun factorial (n)
(labels ((ident (x) x))
(product #'ident 1 #'inc n)))

(defun my-pie (n)
(labels ((num-term (n)
(if (oddp n)
(- n 1)
n))
(den-term (n)
(if (evenp n)
(- n 1)
n)))
(float(* 4
(/ (product #'num-term 3 #'inc n)
(product #'den-term 3 #'inc n))))))



SICP Exercise 1.32
a. Show that sum and product (exercise 1.31) are both special cases of a still more general notion called accumulate that combines a collection of terms, using some general accumulation function:

(accumulate combiner null-value term a next b)

Accumulate takes as arguments the same term and range specifications as sum and product, together with a combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a null-value that specifies what base value to use when the terms run out. Write accumulate and show how sum and product can both be defined as simple calls to accumulate.

b. If your accumulate procedure generates a recursive process,write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.


(defun accumulate (combiner null-value term a next b)
(if (> a b)
null-value
(funcall combiner (funcall term a)
(accumulate combiner null-value term
(funcall next a)
next b))))

(defun new-accumulate (combiner null-value term a next b)
(labels ((iter (a result)
(if (> a b)
result
(iter (funcall next a)
(funcall combiner result (funcall term a))))))
(iter a null-value)))



SICP Exercise 1.33
You can obtain an even more general version of accumulate (exercise 1.32) by introducing the notion of a filter on the terms to be combined. That is, combine only those terms derived from values in the range that satisfy a specified condition. The resulting filtered-accumulate abstraction takes the same arguments as accumulate, together with an additional predicate of one argument that specifies the filter. Write filtered-accumulate as a procedure. Show how to express the following using filtered-accumulate:

a. the sum of the squares of the prime numbers in the interval a to b (assuming that you have a prime? predicate already written)

b. the product of all the positive integers less than n that arerelatively prime to n (i.e., all positive integers i < n suchthat GCD(i,n) = 1).


(defun accumulate-if (filter combiner null-value term a next b)
(cond ((> a b) null-value)
((funcall filter a)
(funcall combiner
(funcall term a)
(accumulate-if filter
combiner
null-value
term
(funcall next a)
next
b)))
(t (accumulate-if filter
combiner
null-value
term
(funcall next a)
next
b))))

(defun prime-squared-sum (a b)
(accumulate-if 'primep
'+
0
#'(lambda(x) (* x x))
a
'inc
b))

(defun rel-prime-product (n)
(labels ((rel-prime-p (x)
(if (= 1 (gcd x n))
t)))
(accumulate-if #'rel-prime-p
'*
1
#'(lambda(x) x)
1
'inc
(- n 1))))



SICP Exercise 1.35
Show that the golden ratio (section 1.2.2) is a fixed point of the transformation x - 1 + 1/x, and use this fact to compute GO by means of the fixed-point procedure.


(defconstant +tolerance+ .00001)

(defun fixed-point (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) +tolerance+))
(try (guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))



SICP Exercise 1.36
Modify fixed-point so that it prints the sequence of approximations it generates, using the newline and display primitives shown in exercise 1.22. Then find a solution to xx = 1000 by finding a fixed point of x log(1000)/log(x). (Use Scheme's primitive log procedure, which computes natural logarithms.) Compare the number of steps this takes with and without average damping. (Note that you cannot start fixed-point with a guess of 1, as this would cause division by log(1) =
0.)


(defun fixed-point-print (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) +tolerance+))
(try (guess)
(print guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))



SICP Exercise 1.37
a. An infinite continued fraction is an expression of the form

f = N1/(D1+(N2/(D2+(N3/(D3+...

As an example, one can show that the infinite continued fraction expansion with the Ni and the Di all equal to 1 produces 1/phi , where phi is the golden ratio (described in section 1.2.2). One way to approximate an infinite continued fraction is to truncate the expansion after a given number of terms. Such a truncation -- a so-called k-term finite continued fraction -- has the form

N1/(D1+(N2/(...+Nk/Dk)

Suppose that n and d are procedures of one argument (the term index i) that return the Ni and Di of the terms of the continued fraction. Define a procedure cont-frac such that evaluating (cont-frac n d k) computes the value of the k-term finite continued fraction. Check your procedure by approximating1/phi using

(cont-frac (lambda (i) 1.0)
(lambda (i) 1.0)
k)

for successive values of k. How large must you make k in order to get an approximation that is accurate to 4 decimal places?b. If your cont-frac procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.


(defun cont-frac (n d k &optional (i 1))
(if (> i k)
0
(/ (funcall n i)
(+ (funcall d i) (cont-frac n d k (+ i 1))))))

(defun cont-frac-iter (n d k &optional (i k) (result 0))
(if (< i 1)
result
(cont-frac-iter n d k
(- i 1)
(/ (funcall n i)
(+ (funcall d i) result)))))



SICP Exercise 1.38
In 1737, the Swiss mathematician Leonhard Euler published a memoir De Fractionibus Continuis, which included a continued fraction expansion for e - 2, where e is the base of the natural logarithms. In this fraction, the Ni are all 1, and the Di are successively 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, .... Write a program that uses your cont-frac procedure from exercise 1.37 to approximate e, based on Euler's expansion.


(defun d (i)
"The D function to pass to cont-frac"
(cond ((= i 2) 2)
((zerop (mod (+ 1 i) 3)) (- i (/ i 3)))
(t 1)))



SICP Exercise 1.39
A continued fraction representation of the tangent function was published in 1770 by the German mathematician J.H. Lambert:

tan r = r/(1-(r^2/(3-(r^2/5-....

where x is in radians. Define a procedure (tan-cf x k) that computes an approximation to the tangent function based on Lambert's formula. K specifies the number of terms to compute, as in exercise 1.37.


(defun tan-cf (x k)
(labels ((tan-n (i)
(if (= i 1)
x
(- (* x x))))
(tan-d (i)
(if (= i 1)
1
(- (* 2 i)
1))))
(cont-frac #'tan-n #'tan-d k)))



SICP Exercise 1.40
Define a procedure cubic that can be used together with the
newtons-method procedure in expressions of the form (newtons-method
(cubic a b c) 1) to approximate zeros of the cubic x3 + ax2 + bx + c.


;;; Scheme functions redefined in CL

(defconstant +tolerance+ 0.00001)

(defconstant +dx+ 0.00001)

(defun deriv (g)
(lambda (x)
(/ (- (funcall g (+ x +dx+)) (funcall g x))
+dx+)))

(defun newton-transform (g)
(lambda (x)
(- x (/ (funcall g x) (funcall (deriv g) x)))))

(defun newton-method (g guess)
(fixed-point (newton-transform g) guess))

;;; Cubic function
(defun cubic (a b c)
(lambda (x)
(+ (* x x x)
(* a x x)
(* b x)
c)))



SICP Exercise 1.41
Define a procedure double that takes a procedure of one argumentasargument and returns a procedure that applies the original proceduretwice. For example, if inc is a procedure that adds1 to its argument,then (double inc) should be a procedure that adds 2. What value is returned by (((double (double double)) inc) 5)


(defun double (procedure)
(lambda (x)
(funcall procedure (funcall procedure x))))



SICP Exercise 1.42
Let f and g be two one-argument functions. The composition f afterg is defined to be the function x f(g(x)). Define a procedure compose that implements composition. For example, if inc is a procedure that adds 1 to its argument,((compose square inc) 6) 49


(defun compose (f g)
(lambda (x)
(funcall f (funcall g x))))



SICP Exercise 1.43
If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x x + 1, then the nth repeated application of f is the function x x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows:
((repeated square 2) 5)
625


(defun repeated (f n &optional (count 1))
(if (>= count n)
(lambda (x) (funcall f x))
(compose (repeated f n (+ count 1)) f)))



SICP Exercise 1.44
The idea of smoothing a function is an important concept in signal processing. If f is a function and dx is some small number, then the smoothed version of f is the function whose value at a point x is the average of f(x - dx), f(x), and f(x + dx). Write a procedure smooth that takes as input a procedure that computes f and returns a procedure that computes the smoothed f. It is sometimes valuable to repeatedly smooth a function (that is, smooth the smoothed function, and so on) to obtained the n-fold smoothed function. Show how to generate the n-fold smoothed function of any given function using smooth and repeated from exercise 1.43.


(defun smoothed (f)
(lambda (x)
(/ (+ (funcall f (- x +dx+))
(funcall f x)
(funcall f (+ x +dx+)))
3)))

(defun n-fold-smoothed (f n)
(repeated (smoothed f) n))



SICP Exercise 1.45
We saw in section 1.3.3 that attempting to compute square roots by naively finding a fixed point of y x/y does not converge, and that this can be fixed by average damping. The same method works for finding cube roots as fixed points of the average-damped y x/y2. Unfortunately, the process does not work for fourth roots -- a single average damp is not enough to make a fixed-point search for y x/y3 converge. On the other hand, if we average damp twice (i.e., use the average damp of the average damp of y x/y3) the fixed-point search does converge. Do some experiments to determine how many average damps are required to compute nth roots as a fixed-point search based upon repeated average damping of y x/yn-1. Use this to implement a simple procedure for computing nth roots using fixedpoint, average-damp, and the repeated procedure of exercise 1.43. Assume that any arithmetic operations you need are available as primitives.


;;; Scheme functions redefined in CL
(defun average-damp (f)
(lambda (x) (/ (+ x (funcall f x))
2)))
;;; End scheme functions

(defun nth-root (x n times)
(fixed-point (repeated (average-damp (lambda (y)
(/ (+ y
(/ x (expt y (- n 1))))
2)))
times)
1.0))



SICP Exercise 1.46
Several of the numerical methods described in this chapter are instances of an extremely general computational strategy known as iterative improvement. Iterative improvement says that, to compute something, we start with an initial guess for the answer, test if the guess is good enough, and otherwise improve the guess and continue the process using the improved guess as the new guess. Write a procedure iterative-improve that takes two procedures as arguments: a method for telling whether a guess is good enough and a method for improving a guess. Iterative-improve should return as its value a procedure that takes a guess as argument and keeps improving the guess until it is good enough. Rewrite the sqrt procedure of section 1.1.7 and the fixed-point procedure of section 1.3.3 in terms of iterative-improve.


(defun iterative-improve (good-enough-p improve)
(lambda (x)
(labels ((next-guess (guess)
(let ((improved-guess (funcall improve guess)))
(if (funcall good-enough-p guess improved-guess)
improved-guess
(next-guess improved-guess)))))
(next-guess x))))

(defun sqrt-improve (x)
(funcall (iterative-improve (lambda (guess z)
(let ((ratio (/ guess z)))
(and (< ratio 1.001) (> ratio 0.999))))
(lambda (guess)
(/ (+ guess (/ x guess))
2)))
1.0))

November 23, 2008

SICP Exercise 1.11
A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.


(defun f (n)
"Recursive"
(cond ((< n 3) n)
(t (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))

(defun f2 (n)
"Iterative"
(if (< n 3)
n
(f2-iter n 2 1 0)))

(defun f2-iter (count &optional fn-1 fn-2 fn-3)
(if (< count 3)
fn-1
(progn (psetf fn-1 (+ fn-1 (* 2 fn-2) (* 3 fn-3))
fn-2 fn-1
fn-3 fn-2)
(f2-iter (- count 1) fn-1 fn-2 fn-3))))



SICP Exercise 1.12
Write a procedure that computes elements of Pascal's triangle by means of a recursive process.


(defun gen-row (lst)
"Given a list of values of the above row in Pascal's triangle,
generates the values in the current row except for the leading and
trailing 1"
(when (> (length lst) 1)
(cons (+ (first lst) (second lst)) (gen-row (cdr lst)))))

(defun pascal (row)
"Returns the values in the given row number of Pascal;s triangle"
(if (eq row 1)
'(1)
(append '(1) (gen-row (pascal (- row 1))) '(1))))



SICP Exercise 1.16
Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)


(defun my-expt (b n &optional (result 1))
(cond ((zerop n) result)
((evenp n) (my-expt (* b b) (/ n 2) result))
(t (my-expt b (- n 1) (* b result)))))



SICP Exercise 1.17
The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:
(define (* a b)
(if (= b 0)
0
(+ a (* a (- b 1)))))
This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.


(defun double (x) (+ x x))
(defun half (x) (/ x 2))

(defun fast-mult (a b)
(cond ((zerop b) 0)
((evenp b) (double (fast-mult a (half b))))
(t (+ a (fast-mult a (- b 1))))))



SICP Exercise 1.18
Using the results of exercises 1.16 and 1.17, devise a procedure that generates an iterative process for multiplying two integers in terms of adding, doubling, and halving and uses a logarithmic number of steps.


(defun my-mult (a b &optional (result 0))
(cond ((zerop b) result)
((evenp b) (my-mult (double a) (half b) result))
(t (my-mult a (- b 1) (+ a result)))))



SICP Exercise 1.22
Most Lisp implementations include a primitive called runtime that returns an integer that specifies the amount of time the system has been running (measured, for example, in microseconds). The following timed-prime-test procedure, when called with an integer n, prints n and checks to see if n is prime. If n is prime, the procedure prints three asterisks followed by the amount of time used in performing the test.
(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime (- (runtime) start-time))))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time))
Using this procedure, write a procedure search-for-primes that checks the primality of consecutive odd integers in a specified range. Use your procedure to find the three smallest primes larger than 1000; larger than 10,000; larger than 100,000; larger than 1,000,000. Note the time needed to test each prime. Since the testing algorithm has order of growth of (n), you should expect that testing for primes around 10,000 should take about 10 times as long as testing for primes around 1000. Do your timing data bear this out? How well do the data for 100,000 and 1,000,000 support the n prediction? Is your result compatible with the notion that programs on your machine run in time proportional to the number of steps required for the computation?


;;; Redefine given functions for common lisp
(defun smallest-divisor (n)
(find-divisor n 2))

(defun find-divisor (n test-divisor)
(cond ((> (square test-divisor) n) n)
((dividesp test-divisor n) test-divisor)
(t (find-divisor n (+ test-divisor 1)))))

(defun dividesp (a b) (zerop (mod b a)))

(defun square (x) (* x x))

(defun primep (n) (= n (smallest-divisor n)))

(defun timed-prime-test (n)
(print n)
(start-prime-test n (get-internal-run-time)))

(defun start-prime-test (n start-time)
(if (primep n)
(report-prime (- (get-internal-run-time) start-time))))

(defun report-prime (elapsed-time)
(print '***)
(print elapsed-time))

(defun search-for-primes (start end)
(loop for i from start to end do (timed-prime-test i)))

Exercise 1.3
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.


(defun square (x) (* x x))

(defun sum-of-squares (lst)
(apply #'+ (mapcar #'square lst)))

(defun get-largest-2 (lst)
(when (>= (length lst) 2)
(let ((sorted-lst (sort lst #'>)))
(list (first sorted-lst)
(second sorted-lst)))))

;;; This does better and takes any number of arguments
(defun sum-sqr-lrgst (lst)
(sum-of-squares (get-largest-2 lst)))


Exercise 1.8
Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value
(x/y^2 + 2y)/3
Use this formula to implement a cube-root procedure analogous to the square-root procedure.


(defconstant +tolerance+ 0.001)

(defun cube (x) (* x x x))

(defun good-enough-p (guess x)
"Returns true if the cube of the guess differs from x by less
than the tolerance"
(< (abs (- (cube guess) x)) +tolerance+))

(defun improve (guess x)
"Returns a better approximation of the cube root of x"
(/ (+ (/ x
(square guess))
(* 2 guess))
3))

(defun cube-rt-iter (guess x)
(if (good-enough-p guess x)
guess
(cube-rt-iter (improve guess x) x)))

(defun cube-rt (x)
"Calculates the cube root of x"
(cube-rt-iter 1.0 x))

November 10, 2008

I am creating a Java web application using Spring and Hibernate. Although I clearly see the benefit of using the Spring framework and Hibernate object/relational mapping tool, configuring it properly can cause some headaches.

Recently I was using Spring's HibernateTemplate to retrieve a list of users from my database. After successfully running a simple query, I then wanted to return the users starting at result number 10 instead of 0. I scanned HibernateTemplate's api to no avail, then searched Google and, to my surprise, found there was no way to return specific rows using HibernateTemplate. The forum posts suggested using Hibernate session instead.

I added a SessionFactory to my class and changed my query code to something like this:

return sessionFactory.getCurrentSession().createQuery("FROM User")
.setMaxResults(10).setFirstResult(10).list();


I confidently ran the code and received the following error:

- Method execution failed:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here



This error happened because I did not have my transaction managment configured properly. HibernateTemplate handles this on its own, but when using Hibernate sessions directly, put something like this in your Spring bean files:
 <!-- enable the configuration of transactional behavior based on annotations -->  
<tx:annotation-driven />

<!-- a PlatformTransactionManager is still required -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>


More information can be found in the Spring documentation.

November 8, 2008

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?


This Common Lisp solution uses the Sieve of Eratosthenes algorithm to find all the prime numbers under a million then returns the 10001st prime.

(defconstant +max+ 1000000)

(defun range (start end)
"Creates a list of integers from start to end"
(loop for i from start to end collect i))

(defun e.6 ()
(let ((limit (sqrt +max+))
(lst (range 2 +max+)))
(loop for i in lst until (> i limit) do
;; Delete all multiples of i from the list
(delete-if #'(lambda (x)
(and (not (eq x i))
(zerop (mod x i))))
lst))
;; The resulting list is a list of all prime numbers
;; up to +max+. Get the 10001st prime number
(nth 10000 lst)))

October 4, 2008

The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.


A simple, straight forward solution in common lisp:

;;; Project Euler Problem 6

(defun sum-of-squares (upper-limit)
(loop for i from 1 to upper-limit sum (* i i)))

(defun square-of-sum (upper-limit)
(expt (loop for i from 1 to upper-limit sum i)
2))

(defun difference (upper-limit)
(- (square-of-sum upper-limit)
(sum-of-squares upper-limit)))

September 30, 2008

Chapter: Generics

Create and test a SixTuple generic.


In Java:

package chapter.generics;

class SixTuple<A, B, C, D, E, F> {
public final A a;
public final B b;
public final C c;
public final D d;
public final E e;
public final F f;

public SixTuple(A a, B b, C c, D d, E e, F f) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
}

public class Exercise3 {

static SixTuple<Integer, String, Double, Boolean, String, Integer> foo() {
return new SixTuple<Integer, String, Double, Boolean, String, Integer>(
5, "hi", 33.3, true, "bye", 100);
}

public static void main(String[] args) {
SixTuple<Integer, String, Double, Boolean, String, Integer> x = foo();
System.out.println(x.b);
System.out.println(x.a);
System.out.println(x.e);

}

}


Lisp can return values in many natural and easy ways, including lists and the values function. Since a lisp programmer would probably avoid creating a special tuple class just to return multiple values, here is an alternative and simple way to accomplish the feat:
(defun foo ()
(values 5 "hi" 33.3 t "bye" 100))

(multiple-value-bind (a b c d e f) (foo)
(print b)
(print a)
(print e))

September 7, 2008

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?


Here is a quick and simple solution in Common Lisp:

(defun simple-euler-5 ()
(lcm 11 12 13 14 15 16 17 18 19 20))


However, coding our own solution isn't too difficult. Using Euclid's algorithm for the greatest common divisor, here is another solution is Common Lisp:

(defun range (start end)
"Generates a list of integers from start to end"
(loop for i from start to end collect i))

(defun my-lcm (lst)
(let ((result 1))
(dolist (n lst)
(setq result (/ (* result n) (gcd result n))))
result))

(defun euler-5 ()
(my-lcm (range 11 20)))

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.


Here is my solution in Common Lisp:

(defun 3-digit-divisors (num)
(do ((i (isqrt num) (- i 1)))
((or (and (zerop (mod num i))
(= 3 (length (write-to-string i))
(length (write-to-string (/ num i)))))
(eq i 99))
(cond ((= i 99) nil)
(t (list i (/ num i)))))))

(defun palindrome? (num)
(let ((x (write-to-string num)))
(if (equalp x (reverse x))
t
nil)))

(defun problem-4 ()
(do ((i 998899 (- i 1)))
((or (and (palindrome? i)
(3-digit-divisors i))
(< i 1))
(list i (3-digit-divisors i)))))


2-digit-divisors takes a number and returns a list of its largest three-digit divisors if it has any or nil. palindrom? tests to see if a number is a palindrome by comparing the number to the reverse of the number. The solution is calculated by starting with the largest six digit palindrome and testing for the conditions.

Of course, problem-4 can be tweaked for better performance by looping for every palindrome rather than decrementing by one.

August 9, 2008

Chapter: Holding Your Objects

Create and populate a List. Create a second List of the same size as the first, and use ListIterators to read elements from the first List and insert them into the second in reverse order.


In Java:
package chapter.holdingYourObjects;

import java.util.*;

public class Exercise12 {
public static void main(String[] args) {
List<Integer> x = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> y = new ArrayList<Integer>(x);

ListIterator<Integer> it = x.listIterator();
while(it.hasNext()) {
y.set(x.size() - it.nextIndex() - 1, it.next());
}

System.out.println("x = " + x);
System.out.println("y = " + y);
}
}

/* Output:
* x = [1, 2, 3, 4, 5]
* y = [5, 4, 3, 2, 1]
*/


In Python:
x = [1, 2, 3, 4, 5]
y = x[:]
y.reverse()

print "x = " + str(x)
print "y = " + str(y)


In Lisp:
(defparameter *x* '(1 2 3 4 5))
(defparameter *y* (reverse *x*))

(format t "x = ~s~%" *x*)
(format t "y = ~s" *y*)

Chapter: Holding Your Objects

Create a class, then make an initialized array of objects of your class. Fill a List from your array. Create a subset of you List by using subList(), then remove this subset from your list.


In Java:
package chapter.holdingYourObjects;

import java.util.*;

class MyClass {}

public class Exercise7 {

public static void main(String[] args) {
MyClass[] myClassArray = {new MyClass(), new MyClass(), new MyClass()};
List<MyClass> myClassList = new ArrayList<MyClass>(Arrays.asList(myClassArray));

// Can't use sublist because removeall won't work
List<MyClass> sublist = Arrays.asList(myClassList.get(0), myClassList.get(1));

System.out.println("myClassList = " + myClassList);
System.out.println("sublist = " + sublist);

myClassList.removeAll(sublist);

System.out.println("myClassList = " + myClassList);
}
}
/* Output:

myClassList = [chapter.holdingYourObjects.MyClass@3e25a5, chapter.holdingYourObjects.MyClass@19821f, chapter.holdingYourObjects.MyClass@addbf1]
sublist = [chapter.holdingYourObjects.MyClass@3e25a5, chapter.holdingYourObjects.MyClass@19821f]
myClassList = [chapter.holdingYourObjects.MyClass@addbf1]

*/


In Python:
class MyClass():
pass

myClassArray = [MyClass(), MyClass(), MyClass()]
sublist = myClassArray[0:2]

print "myClassArray = " + str(myClassArray)
print "sublist = " + str(sublist)

for item in sublist:
myClassArray.remove(item)

print "myClassArray = " + str(myClassArray)

#>>> ## working on region in file /tmp/python-7533hFb...
#myClassArray = [<__main__.MyClass instance at 0xb7d9ee8c>, <__main__.MyClass instance at 0xb7d9ef0c>, <__main__.MyClass instance at 0xb775830c>]
#sublist = [<__main__.MyClass instance at 0xb7d9ee8c>, <__main__.MyClass instance at 0xb7d9ef0c>]
#myClassArray = [<__main__.MyClass instance at 0xb775830c>]


In Lisp:
(defclass MyClass () ())

(defparameter *MyClass-array* (list (make-instance 'MyClass)
(make-instance 'MyClass)
(make-instance 'MyClass)))

(defparameter *sublist* (butlast *MyClass-array* 1))

(format t "MyClass = ~s~%" *MyClass-array*)
(format t "sublist = ~s~%" *sublist*)

(loop for item in *sublist* do
(setf *MyClass-array* (remove item *MyClass-array*)))

(format t "MyClass = ~s~%" *MyClass-array*)

;;;Output:
;MyClass = (#<MYCLASS #x20513866> #<MYCLASS #x20513876> #<MYCLASS #x20513886>)
;sublist = (#<MYCLASS #x20513866> #<MYCLASS #x20513876>)
;MyClass = (#<MYCLASS #x20513886>)

July 28, 2008

Chapter: Holding Your Objects

Create a new class called Gerbil with an int gerbilNumber that's initialized in the constructor. Give it a method called hop() that displays which gerbil number this is, and that it's hopping. Create an ArrayList and add Gerbil objects to the List. Now use the get() method to move through the List and call hop() for each Gerbil.


As we proceed deeper into the book, completing the exercises using multiple languages exposes the differences more clearly. In my opinion Lisp and Java are completely different beasts, with Python combining Lisp's ease of programming with Java-like syntax.

In Java:
package chapter.holdingYourObjects;

import java.util.*;

class Gerbil {
private int gerbilNumber;

Gerbil(int gerbilNumber) {
this.gerbilNumber = gerbilNumber;
}

public void hop() {
System.out.println("Gerbil " + gerbilNumber + " is hopping");
}
}

public class Exercise1 {
public static void main(String[] args) {
ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
for(int i = 0; i < 10; i++)
gerbils.add(new Gerbil(i));

for(int i = 0; i < gerbils.size(); i++)
gerbils.get(i).hop();
}
}


In Python:
class Gerbil:
def __init__(self, gerbilNumber):
self.gerbilNumber = gerbilNumber
def hop(self):
print "Gerbil " + str(self.gerbilNumber) + " is hopping"

gerbils = []
for i in range(10):
gerbils.append(Gerbil(i))

for i in range(len(gerbils)):
gerbils[i].hop()


In Lisp:
(defclass Gerbil ()
((gerbil-number :accessor gerbil-number
:initarg :num)))

(defmethod hop ((g Gerbil))
(format t "Gerbil ~d is hopping~%" (gerbil-number g)))

(defparameter *gerbil-list*
(loop for i from 0 to 9 append
(list (make-instance 'Gerbil :num i))))

(loop for a-gerbil in *gerbil-list* do (hop a-gerbil))

July 27, 2008

at Sunday, July 27, 2008 Labels: , Posted by Billy 0 comments

While I was working on a Spring application, I saw the following error after deploying:

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/BCC-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: White spaces are required between publicId and systemId.



Here are the first few lines of the xml file the stack trace was referring to:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


The report stateed the error was in Line 1, which was obviously not the case. The problem was the order of the schemaLocation values was incorrect. Here is the correct order:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

July 10, 2008

Chapter: Inner Classes

Create an interface U with three methods. Create a class A with a method that produces a reference to a U by building an anonymous inner class. Create a second class B that contains an array of U. B should have one method that accepts and stores a reference to a U in the array, a second method that sets a reference in the array (specified by the method argument) to null, and a third method that moves through the array and calls the methods in U. In main(), create a group of A objects and a single B. Fill the B with U references produced by the A objects. Use the B to call back into all the A objects. Remove some of the U references from the B.



I also added a couple lines of code to show that A's inner class has access to it's private methods.

package chapter.innerClasses;

interface U {
void one();
void two();
void three();
}

class A {
U getU() {
return new U() {
public void one() {System.out.println("one");}
public void two() {System.out.println("two");}
public void three() {System.out.println("three"); printSomething();}
};
}

private void printSomething() {System.out.println("Something");}
}

class B {
private U[] arrayOfU = new U[10];
private int position = 0;

public void storeU(U U_Reference) {
if (position < 10 && position >= 0)
arrayOfU[position++] = U_Reference;
}

public void setNull(int index) {
if (index < 10 && index >= 0)
arrayOfU[index] = null;
}

public void callU() {
for (U myU : arrayOfU) {
if (myU != null) {
myU.one();
myU.two();
myU.three();
}
}
}
}

public class Excercise23 {
public static void main(String[] args) {
A firstA = new A(), secondA = new A();
B theB = new B();
theB.storeU(firstA.getU());
theB.storeU(secondA.getU());
theB.storeU(secondA.getU());
theB.callU();
theB.setNull(1);
theB.callU();
}
}

July 7, 2008

Chapter: Interfaces

Create a framework using Factory Methods that performs both coin tossing and dice tossing.


In Java:
package chapter.interfaces;

import java.util.*;

interface Game {
int toss();
}

interface GameFactory {
Game getGame();
}

class Dice implements Game {
public int toss() {
Random rand = new Random(55);
return rand.nextInt(7);
}
}

class DiceFactory implements GameFactory {
public Game getGame() {
return new Dice();
}
}

class Coins implements Game {
public int toss() {
Random rand = new Random(55);
return rand.nextInt(3);
}
}

class CoinsFactory implements GameFactory {
public Game getGame() {
return new Coins();
}
}

public class Exercise19 {

public static void playGame(GameFactory factory) {
Game game = factory.getGame();
for (int i = 0; i < 8; i++)
System.out.println(game.toss());
}

public static void main(String[] args) {
playGame(new CoinsFactory());
playGame(new DiceFactory());
}

}

Chapter: Interfaces

Create three interfaces, each with two methods. Inherit a new interface that combines the three, adding a new method. Create a class by implementing the new interface and also inheriting from a concrete class. Now write four methods, each of which takes one of the four interfaces as an argument. In main(), create an object of your class and pass it to each of the methods.


In Java:
package chapter.interfaces;

interface A {
void a1();
void a2();
}

interface B {
void b1();
void b2();
}

interface C {
void c1();
void c2();
}

interface D extends A, B, C {
void d1();
}

class E {
public void e1() {System.out.println("e1");}
}

class F extends E implements A, B, C, D {
public void a1() {System.out.println("a1");}
public void a2() {System.out.println("a2");}
public void b1() {System.out.println("b1");}
public void b2() {System.out.println("b2");}
public void c1() {System.out.println("c1");}
public void c2() {System.out.println("c2");}
public void d1() {System.out.println("d1");}
}



public class Exercise14 {
public static void foo(A a) {
a.a1();
a.a2();
}
public static void bar(B b) {
b.b1();
b.b2();
}
public static void yen(C c) {
c.c1();
c.c2();
}
public static void zen(D d) {
d.a1();
d.a2();
d.b1();
d.b2();
d.c1();
d.c2();
d.d1();
}
public static void main(String[] args) {
F f = new F();
foo(f);
bar(f);
yen(f);
zen(f);
f.e1();


}

}

Chapter: Interfaces

Create an interface, and inherit two new interfaces from that interface. Multiply inherit a third interface from the second two.


In Java:
package chapter.interfaces;

interface AI {
void top();
}

interface BI extends AI {
void left();
}

interface CI extends AI {
void right();
}

interface DI extends CI, BI {
void bottom();
}

class EC implements DI {
public void top() {System.out.println("Top");}
public void left() {System.out.println("Left");}
public void right() {System.out.println("Right");}
public void bottom() {System.out.println("Bottom");}
}

public class Exercise13 {
public static void main(String[] args) {
EC e = new EC();
e.top();
e.left();
e.right();
e.bottom();
}
}

at Monday, July 07, 2008 Posted by Billy 0 comments

Chapter: Interfaces

Create an abstract class with no methods. Derive a class and add a method. create a static method that takes a reference to the base class, downcasts it to the derived class, and calls the method.


In Java:
package chapter.interfaces;

abstract class Base {
}

class Sub extends Base {
public void foo() {
System.out.println("Sub foo");
}
}

public class Exercise4 {
private static void bar(Base b) {
((Sub) b).foo();
}

public static void main(String[] args) {
bar(new Sub());
}
}

Chapter: Polymorphism

Create an inheritance hierarchy of Rodent: Mouse, Gerbil, and Hamster. In the base class, provide methods that are common to all Rodents, and override these in the derived classes to perform different behaviors depending on the specific type of Rodent. Create an array of Rodent, fill it with different types of Rodents, and call your base class methods to see what happens.


In Java:
package chapter.polymorphism;

class Rodent {
public void play() {
System.out.println("Rodent playing");
}
public void eat() {
System.out.println("Rodent eating");
}
}

class Mouse extends Rodent {
public void play() {
System.out.println("Mouse playing");
}
public void eat() {
System.out.println("Mouse eating");
}
}

class Gerbil extends Rodent {
public void play() {
System.out.println("Gerbil playing");
}
public void eat() {
System.out.println("Gerbil eating");
}
}

class Hamster extends Rodent {
public void play() {
System.out.println("Hamster playing");
}
public void eat() {
System.out.println("Hamster eating");
}
}

public class Exercise9 {
public static void main(String[] args) {
Rodent[] rodents = { new Rodent(), new Mouse(), new Gerbil(),
new Hamster() };

for (Rodent rodent : rodents) {
rodent.play();
rodent.eat();
}
}
}


In Python:
class Rodent:
def play(self): print 'Rodent playing'
def eat(self): print 'Rodent eating'

class Mouse(Rodent):
def play(self): print 'Mouse playing'
def eat(self): print 'Mouse eating'

class Gerbil(Rodent):
def play(self): print 'Gerbil playing'
def eat(self): print 'Gerbil eating'

class Hamster(Rodent):
def play(self): print 'Hamster playing'
def eat(self): print 'Hamster eating'

rodents = (Rodent(), Mouse(), Gerbil(), Hamster())
for rodent in rodents:
rodent.play()
rodent.eat()

Chapter: Reusing Classes

Create a class called Amphibian. From this, inherit a class called Frog. Put appropriate methods in the base class. In main(), create a Frog and upcast it to Amphibian and demonstrate that all the methods will work.


In Java:
package chapter.reusingClasses;

class Amphibian {

private void move() {
System.out.println("Moving");
}

private void swim() {
System.out.println("Swimming");
}

static void travel(Amphibian a) {
a.move();
a.swim();
}
}

class Frog extends Amphibian {

}

public class Exercise16 {

public static void main(String[] args) {

Frog kermit = new Frog();

Amphibian.travel(kermit);

}

}


In Python:
class Amphibian:
def move(self):
print "Moving"

def swim(self):
print "Swimming"

def travel(self):
self.move()
self.swim()

class Frog(Amphibian):
pass

frog = Frog()
frog.travel()

Chapter: Reusing Classes

Create two classes, A and B, with default constructors (empty argument lists) that announce themselves. Inherit a new class called C from A, and create a member of class B inside C. Do not create a constructor for C. Create an object of class C and observe the results.


Notice the different output in the two solutions.

In Java:
package chapter.reusingClasses;

class A {
A() {
System.out.println("A");
}
}

class B {
B() {
System.out.println("B");
}
}

class C extends A {
B b = new B();
}

public class Exercise5 {

public static void main(String[] args) {

C c = new C();

}

} /* Output:
A
B
*///


In Python:
class A:
def __init__(self):
print "A"

class B:
def __init__(self):
print "B"

class C(A):
b = B()

C()

# Output:
# B
# A

Chapter: Initialization and Cleanup

Create an array of String objects and assing a String to each element. Print the array by using a for loop


I also demonstrate an alternative way to print the array.

In Java:
package chapter.initialization;

import java.util.*;

public class Exercise16 {

public static void main(String[] args) {

String[] stringArray = new String[] { "aaa", "bbb", "ccc", "ddd" };

for (String x : stringArray)
System.out.println(x);

System.out.println(Arrays.toString(stringArray));
}
}


In Python:
stringArray = ("aaa", "bbb", "ccc", "ddd")

for x in stringArray:
print x

print stringArray


In Lisp:
(setq string-array '("aaa" "bbb" "ccc" "ddd"))

(loop for x in string-array do (print x))

(print string-array)

June 21, 2008

Chapter: Controlling Execution

Exercise 10: (5) A vampire number has an even number of digits and is formed by multiplying a pair of numbers containing half the number of digits of the result. The digits are taken from the original number in any order. Pairs of trailing zeroes are not allowed. Examples include:
1260 = 21 * 60
1827 = 21 * 87
2187 = 27 * 81
Write a program that finds all the 4-digit vampire numbers.


The straight foward way to solve this problem is through brute force: check every four digit number and test if it qualifies as a vampire number. If we write out all the ways to multiple two 2-digit numbers we can see a pattern that fits nicely into loops. Let a, b, c and d be the digits of a four-digit number. The possible vampire factors (called "fangs") are:
ab * cd
ab * dc
ba * cd
ba * dc
ac * bd
...
ad * bc
...
and so forth, for a total of 12 combinations. The solutions below use multiple for-loops to test all the combinations by swapping the digits. The inner for-loop swaps the third and fourth digits, the middle for-loop swaps the first and second digits, and the outer for-loop swaps the second digit with either the third or fourth digit. This tests all the combinations in the same sequence as the pattern above. (Note, I have not verified the results. See the bottom of this post for the numbers I got).

In Java:
package chapter.controllingExecution;

public class Exercise10 {

public static void main(String[] args) {

for (int i = 1000; i < 10000; i++)
if (isVampire(i))
System.out.println(i);

}

static boolean isVampire(int num) {

int temp;

int a = Integer.parseInt((String.valueOf(num)).substring(0, 1));
int b = Integer.parseInt((String.valueOf(num)).substring(1, 2));
int c = Integer.parseInt((String.valueOf(num)).substring(2, 3));
int d = Integer.parseInt((String.valueOf(num)).substring(3));

for (int i = 3; i <= 5; i++) {
for (int y = 1; y <= 2; y++) {
for (int z = 1; z <= 2; z++) {
if (num == combineNumbers(a, b) * combineNumbers(c, d))
return true;
temp = c;
c = d;
d = temp;
}
temp = a;
a = b;
b = temp;
}
if (i == 3) {
temp = b;
b = c;
c = temp;
} else {
temp = b;
b = d;
d = temp;
}
}

return false;

}

static int combineNumbers(int x, int y) {
return Integer.parseInt(Integer.toString(x) + Integer.toString(y));
}

}


In Python:
for i in range(1000, 10000):
if isVampire(i):
print i


def combineNumbers(a, b):
return int(str(a) + str(b))

def isVampire(num):
a = str(num)[0]
b = str(num)[1]
c = str(num)[2]
d = str(num)[3]

for i in 3,4,5:
for y in 1,2:
for z in 1,2:
if num == combineNumbers(a,b) * combineNumbers(c,d):
return True
c, d = d, c
a, b = b, a
if i == 3:
b, c = c, b
else:
b, d = d, b
return False


In Lisp:
(loop for i from 1000 to 10000 do
(if (vampire? i)
(print i)))


(defun combine-numbers (a b)
(+ (* a 10) b))

(defun vampire? (number)
(let* ((num (write-to-string number))
(a (parse-integer (subseq num 0 1)))
(b (parse-integer (subseq num 1 2)))
(c (parse-integer (subseq num 2 3)))
(d (parse-integer (subseq num 3 4)))
(temp 0)
(result nil))
(loop for i in '(3 4 5) while (eq result nil) do
(progn (loop for y in '(1 2) while (eq result nil) do
(progn (loop for z in '(1 2) while (eq result nil) do
(if (eq number
(* (combine-numbers a b)
(combine-numbers c d)))
(setq result t)
(setq temp c
c d
d temp)))
(setq temp a
a b
b temp)))
(if (eq i 3)
(setq temp b
b c
c temp)
(setq temp b
b d
d temp))))
result))


The python solution is my favorite because of the simple swapping feature. My results:
1260
1395
1435
1530
1827
2187
6880