Over at SteamCode, Scott LaBounty suggests that writing a program to compute the happy numbers less than n makes a good interview question. According to Wikipedia:
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers).
For example, 7 is a happy number, as 72=49, 42+92=16+81=97, 92+72=81+49=130, 12+32+02=1+9+0=10, and 12+02=1+0=1. But 17 is not a happy number, as 12+72=1+49=50, 52+02=25+0=25, 22+52=4+25=29, 22+92=4+81=85, 82+52=64+25=89, 82+92=64+81=145, 12+42+52=1+16+25=42, 42+22=16+4=20, 22+02=4+0=4, 42=16, 12+62=1+36=37, 32+72=9+49=58, and 52+82=25+64=89, which forms a loop.
Your task is to write a function to identify the happy numbers less than a given limit; you should work at the level of a programming interview, taking no more than about fifteen minutes, and giving a short explanation of your work to the interviewer. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In today’s exercise we continue the examination of matrix operations that we began previously. Our goal is to be able to solve a system of equations; along the way we will see two methods for decomposing matrices.
We begin with some terminology. All the matrices we will be looking at are square, meaning that they have the same number of rows and columns. A lower-triangular matrix L has all entries Lij = 0 for i < j; thus, all entries above the main northwest-to-southeast diagonal are zero. An upper-triangular matrix U has all entries Uij = 0 for i > j; thus, all entries below the main northwest-to-southeast diagonal are zero. A lower- or upper-triangular matrix is unit lower- or upper-triangular if all the entries along the main diagonal are 1. A permutation matrix P has exactly one 1 in each row and column and 0 elsewhere; it is called a permutation matrix because multiplying a vector X by a permutation matrix has the effect of permuting the elements of X. The identity matrix I has 1 in each entry along the main diagonal and 0 elsewhere. A matrix M is singular if it has no inverse, that is, there is no matrix M-1 such that M M-1 = I.
An LU decomposition of a matrix A finds two matrices L, which is unit lower-triangular, and U, which is upper-triangular, such that A = L U. The algorithm is called Gaussian elimination, and works from top to bottom. First, multiples of the first equation are subtracted from the other equations so that the first variable is removed from those equations. Then multiples of the second equation are subtracted from the remaining equations so that the second variable is removed from those equations. Then the third equation, and the fourth, and so on, until all the equations have been processed and the matrix is in upper-triangular form. Here is an example of the LU decomposition of matrix A into its factors L × U:
There are two problems with LU decomposition: First, the algorithm leads to a divide-by-zero error on singular matrices. Second, it is prone to numerical instability for small divisors. The solution is to rearrange, or permute, the equations so that the pivot element is always the largest remaining element, greatly reducing the likelihood of numerical instability.
An improved decomposition is the LUP decomposition, which finds for an input matrix A three matrices L, U, and a permutation matrix P such that P A = L U. Rather than actually moving equations, the permutation matrix records the rearrangements. For example, here is the LUP decomposition of the matrix A given by P × A = L × U:
Given the LUP decomposition, it is simple to solve a system of linear equations. Forward substitution solves the lower-triangular system by calculating the first variable, which is part of an equation with one unknown, then substitutes that into the second equation, reducing it from two unknowns to one unknown, and so on. Then back substitution runs backward, calculating the final values of the variables in the original matrix. Here’s an example, where we wish to solve for the vector X given A X = B:
The LUP decomposition P A = L U is
,
the result of forward substitution L Y = P B is
, giving
,
and the result of the back substitution U X = Y is
, giving
,
which is the solution.
Your task is to write functions that perform LU-decomposition and LUP-decomposition and solve systems of linear equations. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
;; /api/add2
(:api-args (a number?) (b number?))
(+ a b)
Where both a and b are validated as number?. It would be nice if we can validate any type of scheme values, as long as the value can be created via the request input. (define-struct foo (bar baz))
We want to do the following: (:api-args (foo foo?)) ;; takes in the foo struct
And let web API handle the rest. This is achieved via converters.number?). And when you want to use the converter in the api-args expression, you specify the <test?> function in the parameter position in one of the following forms:
(<name> <test?> <default>) ;; this form means this parameter is an optional parameter, and if no values are passed in it will return the default value.
(<name> <test?>) ;; this form means the parameter is a required parameter – if no value passed in it will error. Any value passed in will be validated and converted (if it fails the conversion it will error)
<name> ;; this form means the parameter does not have any validation – any value will be passed verbatim.
Because the <test?> function is used as the mapping to the actual underlying converter object, we will call the underlying converter object as the "<test?> converter". i.e., the actual converter mapped by number? is called the "number? converter" (the quotes are dropped going forward). api-args expression to validate your own objects. To do so, you can define either a scalar or a struct converter as of bzlib/shp:1:3. foo and bar key, but a struct value for the baz key:
{ foo : 1 , bar : "test me" , baz : { abc : 1 , def : 2 } }
So we will use a scalar converter for both foo and bar field (number? and string? respectively), and we will use a struct converter for the baz field that takes in an abc and def fields as number?.
&foo=1&bar=test%20me&baz.abc=1&baz.def=2
The baz JSON object is flattened into baz.abc and baz.def key/value pairs. This flattening can be done for arbitrary levels.define-scalar-converter! syntax.
(define-scalar-converter! <test?>
(<type?> <transform-from-type?>) ...)
For example – the following is the definition of the number? converter:
(define-scalar-converter! number? (string? string->number)) It roughly means the following:
(lambda (x)
(cond ((number? x) x)
((string? x)
(let ((x (string->number x)))
(if x
x
(error 'invalid-conversion "~s" x))))
(else (error 'invalid-type "~s" x))))
If the passed in value is already the desired type, we just let it pass through. Otherwise we test to see if it is one of the known types (or error out), and try to convert the value. If the converter succeeds, return the value, otherwise, throw an exception. url? from net/url.
(define-scalar-converter! url?
(string? string->url)
(bytes? (compose string->url bytes->string/utf-8))
define-struct-converter! syntax.
(define-struct-converter! name ((field converter?) ...))
For example – the following defines a struct converter for the foo struct above:
(define-struct-converter! foo ((bar number?) (baz string?)))
provide/contract, but instead of contract expressions, each field is accompanied by a converter instead. number? and integer?, you should first define the number? converter and then define the integer? converter.bzlib/shp is that shp scripts should be used for presentations and the application logics should reside in regular PLT Scheme/Racket module/packages, converters are best defined in the respective modules. bzlib/shp 0.4 so it can now handle ad hoc defintions as well. So if you want to define converters in the required script you can do so, but remember that if it seems like these definition should be shared they might need to eventually migrate into their respective modules. In two previous exercises, we looked at the programs behind the tables of contents pages in chronological order and permuted by keywords. In today’s exercise, we complete this trio of exercises by writing the program that creates the themed table of contents page. Like the others, it is based on the praxis.info file, which was described previously. We won’t give the output format here, except to say that it is similar to the others, but with an additional header section for the list of themes.
Your task is to write a program that extracts needed data from the praxis.info file and writes the themed table of contents. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.