Skip to content

Commit 3845699

Browse files
authored
fixes #825 (#1020)
1 parent 272478a commit 3845699

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
@@ -1592,6 +1592,50 @@ display(count_pairs(cycle));
15921592
would go into an infinite loop. Exercise<SPACE/><REF NAME="ex:make-cycle"/>
15931593
constructed such lists.
15941594
<LABEL NAME="ex:find-cycle"/>
1595+
<SOLUTION>
1596+
<SNIPPET>
1597+
<EXAMPLE>exercise_3_18_solution_example</EXAMPLE>
1598+
<JAVASCRIPT>
1599+
// solution provided by GitHub user clean99
1600+
1601+
function contains_cycle(x) {
1602+
let counted_pairs = null;
1603+
function is_counted_pair(counted_pairs, x) {
1604+
return is_null(counted_pairs)
1605+
? false
1606+
: head(counted_pairs) === x
1607+
? true
1608+
: is_counted_pair(tail(counted_pairs), x);
1609+
}
1610+
function detect_cycle(x) {
1611+
if (is_null(x)) {
1612+
return false;
1613+
} else if (is_counted_pair(counted_pairs, x)) {
1614+
return true;
1615+
} else {
1616+
counted_pairs = pair(x, counted_pairs);
1617+
return detect_cycle(tail(x));
1618+
}
1619+
}
1620+
return detect_cycle(x);
1621+
}
1622+
</JAVASCRIPT>
1623+
</SNIPPET>
1624+
<SNIPPET HIDE="yes">
1625+
<NAME>exercise_3_18_solution_example</NAME>
1626+
<JAVASCRIPT>
1627+
const three_list = list("a", "b", "c");
1628+
const cycle = list("g", "h", "i");
1629+
set_tail(tail(tail(cycle)), cycle);
1630+
1631+
// displays false
1632+
display(contains_cycle(three_list));
1633+
1634+
// displays true
1635+
display(contains_cycle(cycle));
1636+
</JAVASCRIPT>
1637+
</SNIPPET>
1638+
</SOLUTION>
15951639
</EXERCISE>
15961640

15971641
<EXERCISE>

0 commit comments

Comments
 (0)