algoxcc 0.1.2

A solver for an exact cover with colors problem
Documentation
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Structure [Problem] for defining a problem and
//! functions for pre-validations

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

use super::option::Option;
use super::param_error::ParamError;

/// Validate options, primary and secondary items in a problem
///
/// ## Errors
///
/// If all input values are valid the function returns Ok. If not
/// it returns a [ParamError] with possible messages:
/// - Duplicate primary item
/// - Duplicate secondary item
/// - Item both primary and secondary
/// - Multiple options with label
///
/// ## Examples
///
/// ```
/// use algoxcc::{Option, problem_validate};
///
/// // valid
/// let options = vec![
///     Option::new_validated("o1", &vec!["p1"], &vec![]),
///     Option::new_validated("o2", &vec!["p2"], &vec![("s1","")]),
/// ];
/// let result = problem_validate(&vec!["p1", "p2"], &vec!["s1", "s2"], &options);
/// assert!(result.is_ok());
///
/// // invalid
/// let result = problem_validate(&vec!["p1", "p1"], &vec!["s1", "s2"], &options);
/// assert!(result.is_err());
///
/// // with error message
/// let error = result.unwrap_err();
/// assert_eq!(error.message, "Duplicate primary item p1");
/// ```
pub fn problem_validate(
    primary_items: &Vec<&str>,
    secondary_items: &Vec<&str>,
    options: &Vec<Option>,
) -> Result<(), ParamError> {
    let mut unique_items: HashSet<&str> = HashSet::new();
    for item in primary_items {
        if !unique_items.insert(item) {
            let message = format!("Duplicate primary item {}", &item);
            return Err(ParamError::new(message));
        }
    }
    unique_items.clear();
    for item in secondary_items {
        if !unique_items.insert(item) {
            let message = format!("Duplicate secondary item {}", &item);
            return Err(ParamError::new(message));
        }
        if primary_items.contains(&item) {
            let message = format!("Item {} both primary and secondary", &item);
            return Err(ParamError::new(message));
        }
    }
    let mut opt_count = HashMap::new();
    for o in options {
        let count = opt_count.entry(&o.label).or_insert(0);
        *count += 1;
    }
    for o in options {
        if opt_count.get(&o.label).unwrap() > &1 {
            let message = format!("Multiple options with label {}", &o.label);
            return Err(ParamError::new(message));
        }
    }
    Ok(())
}

/// Validate new item in items
///
/// ## Errors
///
/// If all input values are valid the function returns Ok. If not
/// it returns a [ParamError]:
/// - Item overlap with existing item
///
/// ## Examples
///
/// ```
/// use algoxcc::new_item_validate;
///
/// // valid
/// let result = new_item_validate(&vec!["p1", "p2"], "p3");
/// assert!(result.is_ok());
///
/// // invalid
/// let result = new_item_validate(&vec!["p1", "p2"], "p1");
/// assert!(result.is_err());
///
/// // with error message
/// let error = result.unwrap_err();
/// assert_eq!(error.message, "Item p1 overlap with existing item");
/// ```
pub fn new_item_validate(items: &Vec<&str>, new: &str) -> Result<(), ParamError> {
    if items.contains(&new) {
        let message = format!("Item {} overlap with existing item", new);
        return Err(ParamError::new(message));
    }
    Ok(())
}

/// Validate new option
///
/// ## Errors
///
/// If all input values are valid the function returns Ok. If not
/// it returns a [ParamError]:
/// - Option label overlap with existing option
///
/// ## Examples
///
/// ```
/// use algoxcc::{Option, new_option_validate};
///
/// // valid
/// let options = vec![
///     Option::new_validated("o1", &vec!["p1"], &vec![]),
///     Option::new_validated("o2", &vec!["p2"], &vec![("s1","")]),
/// ];
/// let valid = Option::new_validated("o3", &vec!["p1"], &vec![]);
/// let result = new_option_validate(&options, &valid);
/// assert!(result.is_ok());
///
/// // invalid
/// let invalid = Option::new_validated("o1", &vec!["p1"], &vec![]);
/// let result = new_option_validate(&options, &invalid);
/// assert!(result.is_err());
///
/// // with error message
/// let error = result.unwrap_err();
/// assert_eq!(error.message, "Option label o1 overlap with existing option");
/// ```
pub fn new_option_validate(options: &Vec<Option>, new: &Option) -> Result<(), ParamError> {
    if options
        .iter()
        .map(|o| &o.label)
        .collect::<Vec<&String>>()
        .contains(&&new.label)
    {
        let message = format!("Option label {} overlap with existing option", &new.label);
        return Err(ParamError::new(message));
    }
    Ok(())
}

/// eXact Cover with Colors problem
///
/// ## Errors
///
/// If there's a problem with any of the input values
/// it returns a [ParamError]
///
/// ## Examples
///
/// ```
/// use algoxcc::{Option, Problem, problem_validate, new_item_validate};
///
/// // create problem with validation
/// let primary_items = vec!["p1", "p2"];
/// let secondary_items = vec!["s1", "s2"];
/// let options = vec![
///     Option::new_validated("o1", &vec!["p1"], &vec![]),
///     Option::new_validated("o2", &vec!["p2"], &vec![("s1","")]),
/// ];
/// let result = Problem::new(&primary_items, &secondary_items, &options);
/// assert!(result.is_ok());
/// let mut problem = result.unwrap();
///
/// // add primary and secondary items with validation
/// let result = problem.add_primary_item("p3");
/// assert!(result.is_ok());
/// let result = problem.add_secondary_item("s3");
/// assert!(result.is_ok());
///
/// // handle errors adding items
/// let result = problem.add_secondary_item("s1");
/// assert!(result.is_err());
/// let error = result.unwrap_err();
/// assert_eq!(error.message, "Item s1 overlap with existing item");
///
/// // handle errors in creation
/// let secondary_items = vec!["p1", "s2"];
/// let result = Problem::new(&primary_items, &secondary_items, &options);
/// assert!(result.is_err());
/// let error = result.unwrap_err();
/// assert_eq!(error.message, "Item p1 both primary and secondary");
///
/// // use function to do pre validations
/// let primary_items = vec!["p1", "p2"];
/// let secondary_items = vec!["s1", "s2"];
/// let options = vec![
///     Option::new_validated("o1", &vec!["p1"], &vec![]),
///     Option::new_validated("o2", &vec!["p2"], &vec![("s1","")]),
/// ];
/// let result = problem_validate(&primary_items, &secondary_items, &options);
/// assert!(result.is_ok());
///
/// // and create without validation
/// let mut problem = Problem::new_validated(&primary_items, &secondary_items, &options);
///
/// // doing the same when adding items
/// let new_primary = "p3";
/// let result = new_item_validate(&primary_items, &new_primary);
/// assert!(result.is_ok());
///
/// // and add item without validation
/// problem.add_primary_valid(&new_primary);
///
/// ```
#[derive(Debug, Eq, PartialEq, Clone, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct Problem {
    pub primary_items: Vec<String>,
    pub secondary_items: Vec<String>,
    pub options: Vec<Option>,
}
impl Problem {
    /// New problem with validation of options and items
    pub fn new(
        primary_items: &Vec<&str>,
        secondary_items: &Vec<&str>,
        options: &Vec<Option>,
    ) -> Result<Self, ParamError> {
        // validate input
        problem_validate(&primary_items, &secondary_items, &options)?;
        Ok(Self {
            primary_items: primary_items.into_iter().map(|s| s.to_string()).collect(),
            secondary_items: secondary_items.into_iter().map(|s| s.to_string()).collect(),
            options: options.into_iter().map(|o| o.clone()).collect(),
        })
    }
    /// New problem without validation
    pub fn new_validated(
        primary_items: &Vec<&str>,
        secondary_items: &Vec<&str>,
        options: &Vec<Option>,
    ) -> Self {
        Self {
            primary_items: primary_items.into_iter().map(|s| s.to_string()).collect(),
            secondary_items: secondary_items.into_iter().map(|s| s.to_string()).collect(),
            options: options.into_iter().map(|o| o.clone()).collect(),
        }
    }
    /// Add primary item if valid
    pub fn add_primary_item(&mut self, primary_item: &str) -> Result<(), ParamError> {
        new_item_validate(
            &self.primary_items.iter().map(|s| s.as_str()).collect(),
            &primary_item,
        )?;
        self.primary_items.push(primary_item.to_string());
        Ok(())
    }
    /// Add primary item without validation
    pub fn add_primary_valid(&mut self, primary_item: &str) {
        self.primary_items.push(primary_item.to_string());
    }
    /// Add secondary item if valid
    pub fn add_secondary_item(&mut self, secondary_item: &str) -> Result<(), ParamError> {
        new_item_validate(
            &self.secondary_items.iter().map(|s| s.as_str()).collect(),
            &secondary_item,
        )?;
        self.secondary_items.push(secondary_item.to_string());
        Ok(())
    }
    /// Add secondary item without validation
    pub fn add_secondary_valid(&mut self, secondary_item: &str) {
        self.secondary_items.push(secondary_item.to_string());
    }
    /// Add option if valid
    pub fn add_option(&mut self, option: &Option) -> Result<(), ParamError> {
        new_option_validate(&self.options, &option)?;
        self.options.push(option.clone());
        Ok(())
    }
    /// Add option without validation
    pub fn add_option_valid(&mut self, option: &Option) {
        self.options.push(option.clone());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(char: &str) -> String {
        char.to_string()
    }

    #[test]
    fn test_new_problem() {
        let mut p1 = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "s2"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        )
        .unwrap();
        assert_eq!(p1.primary_items, ["p1", "p2"]);
        assert_eq!(p1.secondary_items, ["s1", "s2"]);
        assert_eq!(p1.options.len(), 1);
        assert_eq!(p1.options[0].label, "o1");
        assert_eq!(p1.options[0].primary_items, ["p1", "p2"]);
        assert_eq!(p1.options[0].secondary_items, [(s("s1"), s(""))]);
        p1.add_primary_item("p3").unwrap();
        assert_eq!(p1.primary_items, ["p1", "p2", "p3"]);
        p1.add_secondary_item("s3").unwrap();
        assert_eq!(p1.secondary_items, ["s1", "s2", "s3"]);
        p1.add_option(&Option::new("o2", &vec!["p3"], &vec![]).unwrap())
            .unwrap();
        assert_eq!(p1.options.len(), 2);
        assert_eq!(p1.options[1].label, "o2");
        assert_eq!(p1.options[1].primary_items, ["p3"]);
        assert_eq!(p1.options[1].secondary_items, []);
        let result = serde_json::to_string(&p1);
        assert!(result.is_ok());
        let json = result.unwrap();
        assert_eq!(
            json,
            r#"{"primary_items":["p1","p2","p3"],"secondary_items":["s1","s2","s3"],"options":[{"label":"o1","primary_items":["p1","p2"],"secondary_items":[["s1",""]]},{"label":"o2","primary_items":["p3"],"secondary_items":[]}]}"#
        );
    }

    #[test]
    fn test_new_problem_from_json() {
        let valid_json = r#"{"primary_items":["p1","p2","p3"],"secondary_items":["s1","s2","s3"],"options":[{"label":"o1","primary_items":["p1","p2"],"secondary_items":[["s1",""]]},{"label":"o2","primary_items":["p3"],"secondary_items":[]}]}"#;
        let result = serde_json::from_str::<Problem>(valid_json);
        assert!(result.is_ok());
        let problem = result.unwrap();
        assert_eq!(problem.primary_items, ["p1", "p2", "p3"]);
        let invalid_json = r#"{"unknown_items":["p1","p2","p3"],"secondary_items":["s1","s2","s3"],"options":[{"label":"o1","primary_items":["p1","p2"],"secondary_items":[["s1",""]]},{"label":"o2","primary_items":["p3"],"secondary_items":[]}]}"#;
        let result = serde_json::from_str::<Problem>(invalid_json);
        assert!(result.is_err());
    }

    #[test]
    fn test_new_problem_items_overlap() {
        let result = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "p1"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        );
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Item p1 both primary and secondary".to_string())
        );
    }

    #[test]
    fn test_new_problem_duplicate_primary() {
        let result = Problem::new(
            &vec!["p1", "p1"],
            &vec!["s1", "s2"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        );
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Duplicate primary item p1".to_string())
        );
    }

    #[test]
    fn test_new_problem_duplicate_secondary() {
        let result = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "s1"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        );
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Duplicate secondary item s1".to_string())
        );
    }

    #[test]
    fn test_new_problem_options_overlap() {
        let result = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "s2"],
            &vec![
                Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap(),
                Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap(),
            ],
        );
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Multiple options with label o1".to_string())
        );
    }

    #[test]
    fn test_add_primary_overlap() {
        let mut problem = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "s2"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        )
        .unwrap();
        let result = problem.add_primary_item("p1");
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Item p1 overlap with existing item".to_string())
        );
    }

    #[test]
    fn test_add_secondary_overlap() {
        let mut problem = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "s2"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        )
        .unwrap();
        let result = problem.add_secondary_item("s1");
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Item s1 overlap with existing item".to_string())
        );
    }

    #[test]
    fn test_add_option_overlap() {
        let mut problem = Problem::new(
            &vec!["p1", "p2"],
            &vec!["s1", "s2"],
            &vec![Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap()],
        )
        .unwrap();
        let result =
            problem.add_option(&Option::new("o1", &vec!["p1", "p2"], &vec![("s1", "")]).unwrap());
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(
            error,
            ParamError::new("Option label o1 overlap with existing option".to_string())
        );
    }
}