polycube_packing/polycube_packing.rs
1//! The following program finds all ways to pack 25 [Y pentacubes] into
2//! a $5\times5\times5$ box. (Exercise 340 in Section 7.2.2.1 of Knuth's
3//! [_The Art of Computer Programming_ **4B** (2022)][taocp4b], Part 2,
4//! illustrates the 29 pentacubes.) We formulate this task as an exact
5//! cover problem, with one item for each of the $125$ positions to cover,
6//! and one option for each [legal placement] of a piece. The program can
7//! be readily adapted to fill an arbitrary shape with a given set of
8//! polycubes.
9//!
10//! Chapter 8 of R. Honsberger's book [_Mathematical Gems II_][mgems] (1976)
11//! provides a good introduction to the techniques for solving polycube packing
12//! puzzles.
13//!
14//! [Y pentacube]: https://en.wikipedia.org/wiki/Polycube
15//! [taocp4b]: https://www-cs-faculty.stanford.edu/~knuth/taocp.html#vol4
16//! [legal placement]: `is_in_bounds`
17//! [mgems]: https://bookstore.ams.org/dol-2
18
19use exact_covers::{DlSolver, Solver};
20use smallvec::SmallVec;
21use std::collections::HashSet;
22use std::iter;
23
24/// A point in the cubic lattice.
25type Position = (i8, i8, i8);
26
27/// A solid object formed by joining $1\times 1\times 1$ cubies face to face.
28#[derive(Debug, Eq, PartialEq, Hash, Clone)]
29struct Polycube(
30 /// The positions occupied by the polycube.
31 SmallVec<Position, { Self::INLINE_CAP }>,
32);
33
34impl Polycube {
35 /// If the number of cubies in this polycube exceeds this threshold,
36 /// the buffer containing their positions is allocated on the heap.
37 const INLINE_CAP: usize = 5; // In this way the array of positions takes 15 bytes,
38 // which is one less than the space required
39 // for a 64-bit pointer and a capacity field.
40
41 /// Creates a polycube with one or more cubies, without copying any data.
42 ///
43 /// This is the `const` version of [`Polycube::from`].
44 pub const fn from_const(positions: [Position; Self::INLINE_CAP]) -> Self {
45 Self(SmallVec::from_buf(positions))
46 }
47
48 /// Applies a transformation to the polycube.
49 pub fn transform(&self, f: impl FnMut(Position) -> Position) -> Self {
50 Self(self.0.iter().copied().map(f).collect())
51 }
52
53 /// Returns the translate of the polycube whose cubie coordinates are
54 /// nonnegative and as small as possible.
55 ///
56 /// This shape is called the _aspect_ of the polycube. Section 1.3 of
57 /// the book [_Tilings and Patterns_][tap] by B. Grünbaum, G. C. Shephard
58 /// (W. H. Freeman, 1987) discusses the number of distinct aspects
59 /// of the tiles in particular classes of tessellations.
60 ///
61 /// [tap]: https://dl.acm.org/doi/10.5555/19304
62 pub fn aspect(&self) -> Self {
63 let x_min = self.0.iter().map(|(x, _, _)| x).min().unwrap();
64 let y_min = self.0.iter().map(|(_, y, _)| y).min().unwrap();
65 let z_min = self.0.iter().map(|(_, _, z)| z).min().unwrap();
66 self.transform(|(x, y, z)| (x - x_min, y - y_min, z - z_min))
67 }
68
69 /// Constructs the set of aspects corresponding to all 3D-rotations of
70 /// the polycube.
71 ///
72 /// D. E. Knuth called these the _base placements_ of a polycube in
73 /// exercise 7.2.2.1–266 of [_The Art of Computer Programming_ **4B**,
74 /// Part 2][taocp] (Addison-Wesley, 2022).
75 ///
76 /// [taocp]: https://www-cs-faculty.stanford.edu/~knuth/taocp.html#vol4
77 pub fn base_placements(&self) -> HashSet<Polycube> {
78 // The group of symmetries of a polycube is isomorphic to a subgroup of
79 // the 24 3D-rotations of a cube, which is generated by the following
80 // two elementary transformations:
81 // 1. $90^\circ$ rotation about the $z$-axis, $(x,y,z)\mapsto(y,x_\text{max}-x,z)$.
82 // 2. Reflection about the $x=y=z$ diagonal: $(x,y,z)\mapsto(y,z,x)$.
83 // To see why, use the fact that the rotational symmetries of a cube
84 // form a group that is isomorphic to the symmetric group $S_4$ on 4
85 // elements. (Notice that the rotations of a cube permute its diagonals.)
86 // In this way transformations 1 and 2 correspond respectively to
87 // the permutations $\pi=(1234)$ and $\sigma=(142)$ under some
88 // appropriate naming of the cube vertices. And $\{\pi,\sigma\}$ is
89 // a generator of $S_4$.
90 let mut placements = HashSet::with_capacity(24);
91 let mut to_visit = Vec::with_capacity(8);
92 to_visit.push(self.aspect());
93 while let Some(shape) = to_visit.pop() {
94 let x_max = shape.0.iter().map(|(x, _, _)| x).max().unwrap();
95 let rotation = shape.transform(|(x, y, z)| (y, x_max - x, z));
96 if !placements.contains(&rotation) {
97 to_visit.push(rotation);
98 }
99
100 let reflection = shape.transform(|(x, y, z)| (y, z, x));
101 if !placements.contains(&reflection) {
102 to_visit.push(reflection);
103 }
104
105 placements.insert(shape);
106 }
107 placements
108 }
109
110 /// Returns the number of cubies in the polycube.
111 pub fn cubie_count(&self) -> usize {
112 self.0.len()
113 }
114}
115
116impl From<&[Position]> for Polycube {
117 /// Creates a polycube with one or more cubies.
118 fn from(positions: &[Position]) -> Self {
119 assert!(!positions.is_empty(), "a polycube has one or more cubies");
120 Self(SmallVec::from_slice(positions))
121 }
122}
123
124impl From<Vec<Position>> for Polycube {
125 /// Creates a polycube with one or more cubies.
126 fn from(positions: Vec<Position>) -> Self {
127 assert!(!positions.is_empty(), "a polycube has one or more cubies");
128 Self(positions.into())
129 }
130}
131
132/// The Y pentacube, with the vector normal to its bottom face—the face that is
133/// farthest-apart from the pentacube's center of mass—pointing downwards and
134/// the cubie not in the long bar appearing in the up-west position.
135const Y: Polycube = Polycube::from_const([(0, 2, 0), (1, 0, 0), (1, 1, 0), (1, 2, 0), (1, 3, 0)]);
136
137/// Returns `true` if and only if the given polycube lies inside the
138/// $l\times m\times n$ cuboid cornered at the origin.
139fn is_in_bounds(polycube: &Polycube, l: i8, m: i8, n: i8) -> bool {
140 let x_min = *polycube.0.iter().map(|(x, _, _)| x).min().unwrap();
141 let y_min = *polycube.0.iter().map(|(_, y, _)| y).min().unwrap();
142 let z_min = *polycube.0.iter().map(|(_, _, z)| z).min().unwrap();
143 let x_max = *polycube.0.iter().map(|(x, _, _)| x).max().unwrap();
144 let y_max = *polycube.0.iter().map(|(_, y, _)| y).max().unwrap();
145 let z_max = *polycube.0.iter().map(|(_, _, z)| z).max().unwrap();
146 0 <= x_min && x_max < l && 0 <= y_min && y_max < m && 0 <= z_min && z_max < n
147}
148
149fn main() {
150 // Define the items of the exact cover problem, namely the $lmn$ cells of
151 // the $l\times m\times n$ cuboid.
152 let (l, m, n) = (5i8, 5i8, 5i8);
153 let positions = (0..l)
154 .flat_map(|x| iter::repeat(x).zip(0..m))
155 .flat_map(|y| iter::repeat(y).zip(0..n))
156 .map(|((x, y), z)| (x, y, z))
157 .collect::<Vec<_>>();
158
159 let mut solver: DlSolver<Position, ()> = DlSolver::new(&positions, &[]);
160 // For each base placement $P$ of the Y pentacube, and for each offset
161 // $(x_0,y_0,z_0)$ such that the piece $P'=P+(x_0,y_0,z_0)$ lies within the
162 // $l\times m\times n$ cuboid cornered at the origin, define an option whose
163 // primary items are the cells of $P'$. We break symmetry by constraining
164 // a particular cubie of the first pentacube to be at $L_\infty$ distance
165 // $\le2$ from the origin.
166 let placements = Y.base_placements();
167 let mut first = true;
168 for placement in placements {
169 for (x_0, y_0, z_0) in &positions {
170 if first && (*x_0 > 2 || *y_0 > 2 || *z_0 > 2) {
171 continue;
172 }
173 let shifted = placement.transform(|(x, y, z)| (x + x_0, y + y_0, z + z_0));
174 if is_in_bounds(&shifted, l, m, n) {
175 solver.add_option(&shifted.0, []);
176 }
177 }
178 first = false;
179 }
180
181 let mut count = 0;
182 let mut polycube = Vec::with_capacity(Y.cubie_count());
183 solver.solve(|mut solution| {
184 // Print the solution, which consists of a set of 25 pentacubes.
185 print!("[");
186 while solution.next(&mut polycube) {
187 print!("[");
188 if let Some((&last, elements)) = polycube.split_last() {
189 for &cubie in elements {
190 print!("[{},{},{}],", cubie.0, cubie.1, cubie.2);
191 }
192 print!("[{},{},{}]", last.0, last.1, last.2);
193 }
194 print!("],");
195 }
196 println!("]");
197 count += 1;
198 });
199 println!("found {count} packings");
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 #[test]
207 fn y_base_placements() {
208 let placements = Y.base_placements();
209 assert_eq!(placements.len(), 24, "the Y pentacube has 24 3D-rotations");
210 for placement in &placements {
211 assert_eq!(
212 placement,
213 &placement.aspect(),
214 "a base placement is an aspect"
215 );
216 }
217 }
218}