Skip to content

Commit 272478a

Browse files
authored
fixes #824 (#1019)
1 parent ddb4f9e commit 272478a

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

xml/chapter3/section3/subsection1.xml

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,6 +1522,56 @@ display(count_pairs(cycle));
15221522
distinct pairs in any structure. (Hint: Traverse the structure, maintaining
15231523
an auxiliary data structure that is used to keep track of which pairs have
15241524
already been counted.)
1525+
<SOLUTION>
1526+
<SNIPPET>
1527+
<EXAMPLE>exercise_3_17_solution_example</EXAMPLE>
1528+
<JAVASCRIPT>
1529+
// solution provided by GitHub user clean99
1530+
1531+
function count_pairs(x) {
1532+
let counted_pairs = null;
1533+
function is_counted_pair(current_counted_pairs, x) {
1534+
return is_null(current_counted_pairs)
1535+
? false
1536+
: head(current_counted_pairs) === x
1537+
? true
1538+
: is_counted_pair(tail(current_counted_pairs), x);
1539+
}
1540+
function count(x) {
1541+
if(! is_pair(x) || is_counted_pair(counted_pairs, x)) {
1542+
return 0;
1543+
} else {
1544+
counted_pairs = pair(x, counted_pairs);
1545+
return count(head(x)) +
1546+
count(tail(x)) +
1547+
1;
1548+
}
1549+
}
1550+
return count(x);
1551+
}
1552+
</JAVASCRIPT>
1553+
</SNIPPET>
1554+
<SNIPPET HIDE="yes">
1555+
<NAME>exercise_3_17_solution_example</NAME>
1556+
<JAVASCRIPT>
1557+
const three_list = list("a", "b", "c");
1558+
const one = pair("d", "e");
1559+
const two = pair(one, one);
1560+
const four_list = pair(two, "f");
1561+
const seven_list = pair(two, two);
1562+
const cycle = list("g", "h", "i");
1563+
set_tail(tail(tail(cycle)), cycle);
1564+
1565+
// return 3; return 3; return 3;
1566+
display(count_pairs(three_list));
1567+
display(count_pairs(four_list));
1568+
display(count_pairs(seven_list));
1569+
1570+
// return 3
1571+
display(count_pairs(cycle));
1572+
</JAVASCRIPT>
1573+
</SNIPPET>
1574+
</SOLUTION>
15251575
</EXERCISE>
15261576

15271577
<EXERCISE>

0 commit comments

Comments
 (0)