Skip to content

Commit d27372a

Browse files
committed
Refactor solution
1 parent 05ea361 commit d27372a

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

dominoes/src/lib.rs

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ impl Dominoes {
5959
}
6060
let results: Vec<Option<Self>> = neighbours
6161
.into_iter()
62+
// Recurse the list of dominoes until there is no more
63+
// left to play
6264
.map(|neighbour| {
6365
let mut next_domino = available[neighbour];
6466
if current_dom.1 != next_domino.0 {
@@ -68,23 +70,25 @@ impl Dominoes {
6870
available,
6971
allocated,
7072
} = Self::play_domino(&next_domino, &available, &allocated);
71-
let tmp = Self::sequence_helper(next_domino, available, allocated);
72-
tmp
73+
Self::sequence_helper(next_domino, available, allocated)
7374
})
74-
.collect();
75-
let new_results: Vec<Option<Self>> = results
76-
.iter()
77-
.cloned()
75+
// Remove non-solutions
7876
.filter(|result| match result {
7977
Some(value) => value.available.is_empty(),
8078
None => false,
8179
})
8280
.collect();
83-
match new_results.get(0) {
81+
// Return the first solution
82+
match results.get(0) {
8483
None => None,
8584
Some(value) => Some(value.clone().unwrap()),
8685
}
8786
}
87+
/**
88+
* Returns a list of neighbours for the given domino.
89+
* Assumes that the given domino has already been removed
90+
* from the list of candidates.
91+
*/
8892
fn find_neighbours(available: &[Domino], dots: usize) -> Vec<usize> {
8993
let mut matches = vec![];
9094
for (index, domino) in available.iter().enumerate() {
@@ -96,29 +100,26 @@ impl Dominoes {
96100
matches
97101
}
98102
/**
99-
* Returns a list of neighbours for the given domino.
100-
* Assumes that the given domino has already been removed
101-
* from the list of candidates.
103+
* Moves the given domino from available to allocated resource.
102104
*/
103105
fn play_domino(domino: &Domino, available: &[Domino], allocated: &[Domino]) -> Self {
104-
let mut new_allocated = allocated.to_vec();
105-
new_allocated.push(*domino);
106+
let mut allocated = allocated.to_vec();
107+
allocated.push(*domino);
106108
let reversed_dom = Self::reverse_domino(*domino);
107109
let position = available
108110
.iter()
109111
.position(|&dom| dom == *domino || dom == reversed_dom)
110112
.unwrap();
111-
let new_available = available
113+
let available = available
112114
.iter()
113115
.enumerate()
114116
.filter_map(|(index, &value)| if index != position { Some(value) } else { None })
115117
.collect();
116118
Dominoes {
117-
available: new_available,
118-
allocated: new_allocated,
119+
available,
120+
allocated,
119121
}
120122
}
121-
122123
fn start_and_end_dots_are_equal(&self) -> bool {
123124
let allocation = self.allocated.to_vec();
124125
let first_dom = allocation.first().unwrap();

0 commit comments

Comments
 (0)