I found some code (written by one of my students) which works, and passes all the tests in the test suite, but I have trouble believing that it works.
Given two sets of 4 strings each, such that the intersection of the two sets might be empty or inhabited, the student found the matches and differences like this.
Do small sets always zip in some predicable order which makes this code accidentally work?
What does (c1,c2)
.zipped do?
// Card is a type aliased to Set[String], and every Card is guaranteed exactly 4 elements.
def completeTriptych(c1: Card, c2: Card): Card = {
(c1, c2).zipped.foldLeft(Set[String]())({
(acc, cards) =>
if (cards._1 == cards._2)
acc + cards._1
else {
acc + features.find(_.contains(cards._1)).get
.find(el => el != cards._1 && el != cards._2).get
}
})
}
features
is a Set[Set[String]]
a set of 4 Sets, each of the leaf sets contains 4 strings, exactly one of which is contained in c1, and one of which is contained in c2.
Here is an example?
(Set("red","oval","stripped","two"),
Set("green","squiggle","filled","one")).zipped.toList
This surprisingly returns List((red,green), (oval,squiggle), (stripped,filled), (two,one))
,
i.e., zipping element 1 with element 1, element 2 with element 2, etc…