Skip to content

Commit dea420e

Browse files
committed
fixes #825
1 parent 7b7e2a5 commit dea420e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

xml/chapter3/section3/subsection1.xml

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1541,6 +1541,50 @@ display(count_pairs(cycle));
15411541
would go into an infinite loop. Exercise<SPACE/><REF NAME="ex:make-cycle"/>
15421542
constructed such lists.
15431543
<LABEL NAME="ex:find-cycle"/>
1544+
<SOLUTION>
1545+
<SNIPPET>
1546+
<EXAMPLE>exercise_3_18_solution_example</EXAMPLE>
1547+
<JAVASCRIPT>
1548+
// solution provided by GitHub user clean99
1549+
1550+
function contains_cycle(x) {
1551+
let counted_pairs = null;
1552+
function is_counted_pair(counted_pairs, x) {
1553+
return is_null(counted_pairs)
1554+
? false
1555+
: head(counted_pairs) === x
1556+
? true
1557+
: is_counted_pair(tail(counted_pairs), x);
1558+
}
1559+
function detect_cycle(x) {
1560+
if (is_null(x)) {
1561+
return false;
1562+
} else if (is_counted_pair(counted_pairs, x)) {
1563+
return true;
1564+
} else {
1565+
counted_pairs = pair(x, counted_pairs);
1566+
return detect_cycle(tail(x));
1567+
}
1568+
}
1569+
return detect_cycle(x);
1570+
}
1571+
</JAVASCRIPT>
1572+
</SNIPPET>
1573+
<SNIPPET HIDE="yes">
1574+
<NAME>exercise_3_18_solution_example</NAME>
1575+
<JAVASCRIPT>
1576+
const three_list = list("a", "b", "c");
1577+
const cycle = list("g", "h", "i");
1578+
set_tail(tail(tail(cycle)), cycle);
1579+
1580+
// displays false
1581+
display(contains_cycle(three_list));
1582+
1583+
// displays true
1584+
display(contains_cycle(cycle));
1585+
</JAVASCRIPT>
1586+
</SNIPPET>
1587+
</SOLUTION>
15441588
</EXERCISE>
15451589

15461590
<EXERCISE>

0 commit comments

Comments
 (0)