SICP Exercise 3.69 triples
Exercise 3.69. Write a procedure triples that takes three infinite streams, S, T, and U, and produces the stream of triples (Si,Tj,Uk) such that i < j < k. Use triples to generate the stream of all Pythagorean triples of positive integers, i.e., the triples (i,j,k) such that i < j and i2 + j2 = k2.
SOLUTION
The infinite streams S, T and U are represented as follows:
S0 T0 U0
S1 T1 U1
S2 T2 U2
S3 T3 U3
S4 T4 U4
. . .
. . .
. . .
All triples (Si, Tj, Uk) such that i < j < k can be produced by combining the following:
1. (S0, T1, U2)
2. S0 combined with all the pairs produced using the streams (T1, T2, T3, ...) and
(U1, U2, U3, ...) such that for every pair (Tj, Uk), j < k. We need to exclude the
first element from this combined stream because the first element will be
(S0, T1, U2) which is already accounted for.
3. triples called recursively on the streams (S1, S2, ...) (T1, T2, ...) and (U1, U2, ...)
The code and tests are here.
SOLUTION
The infinite streams S, T and U are represented as follows:
S0 T0 U0
S1 T1 U1
S2 T2 U2
S3 T3 U3
S4 T4 U4
. . .
. . .
. . .
All triples (Si, Tj, Uk) such that i < j < k can be produced by combining the following:
1. (S0, T1, U2)
2. S0 combined with all the pairs produced using the streams (T1, T2, T3, ...) and
(U1, U2, U3, ...) such that for every pair (Tj, Uk), j < k. We need to exclude the
first element from this combined stream because the first element will be
(S0, T1, U2) which is already accounted for.
3. triples called recursively on the streams (S1, S2, ...) (T1, T2, ...) and (U1, U2, ...)
Comments
Post a Comment