Skip to content

Commit

Permalink
fixes #824 (#1019)
Browse files Browse the repository at this point in the history
martin-henz authored Jul 7, 2024
1 parent ddb4f9e commit 272478a
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions xml/chapter3/section3/subsection1.xml
Original file line number Diff line number Diff line change
@@ -1522,6 +1522,56 @@ display(count_pairs(cycle));
distinct pairs in any structure. (Hint: Traverse the structure, maintaining
an auxiliary data structure that is used to keep track of which pairs have
already been counted.)
<SOLUTION>
<SNIPPET>
<EXAMPLE>exercise_3_17_solution_example</EXAMPLE>
<JAVASCRIPT>
// solution provided by GitHub user clean99

function count_pairs(x) {
let counted_pairs = null;
function is_counted_pair(current_counted_pairs, x) {
return is_null(current_counted_pairs)
? false
: head(current_counted_pairs) === x
? true
: is_counted_pair(tail(current_counted_pairs), x);
}
function count(x) {
if(! is_pair(x) || is_counted_pair(counted_pairs, x)) {
return 0;
} else {
counted_pairs = pair(x, counted_pairs);
return count(head(x)) +
count(tail(x)) +
1;
}
}
return count(x);
}
</JAVASCRIPT>
</SNIPPET>
<SNIPPET HIDE="yes">
<NAME>exercise_3_17_solution_example</NAME>
<JAVASCRIPT>
const three_list = list("a", "b", "c");
const one = pair("d", "e");
const two = pair(one, one);
const four_list = pair(two, "f");
const seven_list = pair(two, two);
const cycle = list("g", "h", "i");
set_tail(tail(tail(cycle)), cycle);

// return 3; return 3; return 3;
display(count_pairs(three_list));
display(count_pairs(four_list));
display(count_pairs(seven_list));

// return 3
display(count_pairs(cycle));
</JAVASCRIPT>
</SNIPPET>
</SOLUTION>
</EXERCISE>

<EXERCISE>

0 comments on commit 272478a

Please sign in to comment.