1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! Configurations related to the the search order.

use super::{Config, Coord, Symmetry};
use auto_enums::auto_enum;
use std::{borrow::Cow, cmp::Ordering};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// The order to find a new unknown cell.
///
/// It will always search all generations of one cell
/// before going to another cell.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum SearchOrder {
    /// Searches all cells of one row before going to the next row.
    ///
    /// ```plaintext
    /// 123
    /// 456
    /// 789
    /// ```
    RowFirst,

    /// Searches all cells of one column before going to the next column.
    ///
    /// ```plaintext
    /// 147
    /// 258
    /// 369
    /// ```
    ColumnFirst,

    /// Diagonal.
    ///
    /// ```plaintext
    /// 136
    /// 258
    /// 479
    /// ```
    ///
    /// This search order requires the world to be square.
    Diagonal,

    /// Specify the search order by a vector of coordinates.
    ///
    /// This vector should cover every cell in the search range,
    /// and should not have any duplication, otherwise rlifesrc
    /// would give a wrong result.
    FromVec(Vec<Coord>),
}

impl Config {
    /// Automatically determines the search order if `search_order` is `None`.
    pub(crate) fn auto_search_order(&self) -> Cow<'_, SearchOrder> {
        if let Some(search_order) = &self.search_order {
            Cow::Borrowed(search_order)
        } else {
            let (width, height) = match self.symmetry {
                Symmetry::D2Row => (self.width, (self.height + 1) / 2),
                Symmetry::D2Col => ((self.width + 1) / 2, self.height),
                _ => (self.width, self.height),
            };
            let search_order = match width.cmp(&height) {
                Ordering::Greater => SearchOrder::ColumnFirst,
                Ordering::Less => SearchOrder::RowFirst,
                Ordering::Equal => {
                    if self.diagonal_width.is_some()
                        && 2 * self.diagonal_width.unwrap() <= self.width
                    {
                        SearchOrder::Diagonal
                    } else if self.dx.abs() >= self.dy.abs() {
                        SearchOrder::ColumnFirst
                    } else {
                        SearchOrder::RowFirst
                    }
                }
            };
            Cow::Owned(search_order)
        }
    }

    /// Generates an iterator over cells coordinates from the search order.
    #[auto_enum(Iterator)]
    pub(crate) fn search_order_iter(
        &self,
        search_order: &SearchOrder,
    ) -> impl Iterator<Item = Coord> {
        let width = self.width;
        let height = self.height;
        let period = self.period;
        let x_start = if self.symmetry >= Symmetry::D2Col {
            self.width / 2
        } else {
            0
        };
        let y_start = if self.symmetry >= Symmetry::D2Row {
            self.height / 2
        } else {
            0
        };
        match search_order {
            SearchOrder::ColumnFirst => (0..width).rev().flat_map(move |x| {
                (y_start..height)
                    .rev()
                    .flat_map(move |y| (0..period).rev().map(move |t| (x, y, t)))
            }),
            SearchOrder::RowFirst => (0..height).rev().flat_map(move |y| {
                (x_start..width)
                    .rev()
                    .flat_map(move |x| (0..period).rev().map(move |t| (x, y, t)))
            }),
            #[nested]
            SearchOrder::Diagonal => {
                if self.symmetry >= Symmetry::D2Diag {
                    (0..width)
                        .rev()
                        .flat_map(move |d| {
                            ((width + d + 1) / 2..width).rev().flat_map(move |x| {
                                (0..period).rev().map(move |t| (x, width + d - x, t))
                            })
                        })
                        .chain((0..width).rev().flat_map(move |d| {
                            ((d + 1) / 2..=d)
                                .rev()
                                .flat_map(move |x| (0..period).rev().map(move |t| (x, d - x, t)))
                        }))
                } else {
                    (0..width)
                        .rev()
                        .flat_map(move |d| {
                            (d + 1..width).rev().flat_map(move |x| {
                                (0..period).rev().map(move |t| (x, width + d - x, t))
                            })
                        })
                        .chain((0..width).rev().flat_map(move |d| {
                            (0..=d)
                                .rev()
                                .flat_map(move |x| (0..period).rev().map(move |t| (x, d - x, t)))
                        }))
                }
            }
            SearchOrder::FromVec(vec) => vec.clone().into_iter().rev(),
        }
    }

    /// Generates a closure to determine whether a cell is in the front.
    ///
    /// Return `None` when we should not force the front to be nonempty,
    /// or there isn't a well-defined 'front'.
    pub(crate) fn fn_is_front(
        &self,
        rule_is_b0: bool,
        rule_gen: usize,
        rule_symmetry: Symmetry,
        search_order: &SearchOrder,
    ) -> Option<Box<dyn Fn(Coord) -> bool>> {
        let dx = self.dx;
        let dy = self.dy;
        let width = self.width;
        let height = self.height;
        let max_t = if rule_is_b0 { rule_gen as i32 } else { 1 };
        if !self.known_cells.is_empty() {
            return None;
        }

        match search_order {
            SearchOrder::RowFirst => {
                if self.symmetry <= Symmetry::D2Col
                    && self.transform.is_in(Symmetry::D2Col)
                    && self.diagonal_width.is_none()
                {
                    if dx == 0 && dy >= 0 {
                        if rule_symmetry >= Symmetry::D2Col {
                            Some(Box::new(move |(x, y, t)| {
                                y == (dy - 1).max(0) && t < max_t && x <= width / 2
                            }))
                        } else {
                            Some(Box::new(move |(_, y, t)| y == (dy - 1).max(0) && t < max_t))
                        }
                    } else if rule_symmetry >= Symmetry::D2Col && dx == 0 {
                        Some(Box::new(move |(x, y, _)| y == 0 && x <= width / 2))
                    } else {
                        Some(Box::new(|(_, y, _)| y == 0))
                    }
                } else {
                    None
                }
            }
            SearchOrder::ColumnFirst => {
                if self.symmetry <= Symmetry::D2Row
                    && self.transform.is_in(Symmetry::D2Row)
                    && self.diagonal_width.is_none()
                {
                    if dx >= 0 && dy == 0 {
                        if rule_symmetry >= Symmetry::D2Row {
                            Some(Box::new(move |(x, y, t)| {
                                x == (dx - 1).max(0) && t < max_t && y <= height / 2
                            }))
                        } else {
                            Some(Box::new(move |(x, _, t)| x == (dx - 1).max(0) && t < max_t))
                        }
                    } else if rule_symmetry >= Symmetry::D2Row && dy == 0 {
                        Some(Box::new(move |(x, y, _)| x == 0 && y <= height / 2))
                    } else {
                        Some(Box::new(|(x, _, _)| x == 0))
                    }
                } else {
                    None
                }
            }
            SearchOrder::Diagonal => {
                if self.symmetry <= Symmetry::D2Diag && self.transform.is_in(Symmetry::D2Diag) {
                    if dx >= 0 && dx == dy {
                        if rule_symmetry >= Symmetry::D2Diag && self.width == self.height {
                            Some(Box::new(move |(x, _, t)| x == (dx - 1).max(0) && t < max_t))
                        } else {
                            Some(Box::new(move |(x, y, t)| {
                                (x == (dx - 1).max(0) || y == (dy - 1).max(0)) && t < max_t
                            }))
                        }
                    } else if rule_symmetry >= Symmetry::D2Diag
                        && dx == dy
                        && self.width == self.height
                    {
                        Some(Box::new(|(x, _, _)| x == 0))
                    } else {
                        Some(Box::new(|(x, y, _)| x == 0 || y == 0))
                    }
                } else {
                    None
                }
            }
            SearchOrder::FromVec(_) => None,
        }
    }
}