problemreductions/models/misc/
subset_sum.rs1use crate::registry::{FieldInfo, ProblemSchemaEntry};
11use crate::traits::Problem;
12use num_bigint::{BigUint, ToBigUint};
13use num_traits::Zero;
14use serde::{Deserialize, Serialize};
15
16inventory::submit! {
17 ProblemSchemaEntry {
18 name: "SubsetSum",
19 display_name: "Subset Sum",
20 aliases: &[],
21 dimensions: &[],
22 category: crate::registry::ProblemCategory::Misc,
23 module_path: module_path!(),
24 description: "Find a subset of positive integers that sums to exactly a target value",
25 fields: &[
26 FieldInfo { name: "sizes", type_name: "Vec<BigUint>", description: "Positive integer sizes s(a) for each element" },
27 FieldInfo { name: "target", type_name: "BigUint", description: "Target sum B" },
28 ],
29 }
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct SubsetSum {
55 #[serde(with = "super::biguint_serde::decimal_biguint_vec")]
56 sizes: Vec<BigUint>,
57 #[serde(with = "super::biguint_serde::decimal_biguint")]
58 target: BigUint,
59}
60
61impl SubsetSum {
62 pub fn new<S, T>(sizes: Vec<S>, target: T) -> Self
68 where
69 S: ToBigUint,
70 T: ToBigUint,
71 {
72 let sizes: Vec<BigUint> = sizes
73 .into_iter()
74 .map(|s| s.to_biguint().expect("All sizes must be positive (> 0)"))
75 .collect();
76 assert!(
77 sizes.iter().all(|s| !s.is_zero()),
78 "All sizes must be positive (> 0)"
79 );
80 let target = target
81 .to_biguint()
82 .expect("SubsetSum target must be nonnegative");
83 Self { sizes, target }
84 }
85
86 pub(crate) fn new_unchecked(sizes: Vec<BigUint>, target: BigUint) -> Self {
91 Self { sizes, target }
92 }
93
94 pub fn sizes(&self) -> &[BigUint] {
96 &self.sizes
97 }
98
99 pub fn target(&self) -> &BigUint {
101 &self.target
102 }
103
104 pub fn num_elements(&self) -> usize {
106 self.sizes.len()
107 }
108}
109
110impl Problem for SubsetSum {
111 const NAME: &'static str = "SubsetSum";
112 type Solution = Vec<bool>;
113 type Value = crate::types::Or;
114
115 crate::problem_parameters![("num_elements", num_elements),];
116
117 fn variant() -> Vec<(&'static str, &'static str)> {
118 crate::variant_params![]
119 }
120
121 fn evaluate(
122 &self,
123 config: &Self::Solution,
124 ) -> Result<crate::types::Or, crate::traits::EvaluationError> {
125 Ok({
126 crate::types::Or({
127 if config.len() != self.num_elements() {
128 return Err(crate::traits::EvaluationError::InvalidConfiguration(
129 "subset-selection length does not match the elements".into(),
130 ));
131 }
132 let mut total = BigUint::zero();
133 for (i, &x) in config.iter().enumerate() {
134 if x {
135 total += &self.sizes[i];
136 }
137 }
138 total == self.target
139 })
140 })
141 }
142}
143
144impl crate::solvers::BruteForceProblem for SubsetSum {
145 fn dimensions(&self) -> Vec<usize> {
146 vec![2; self.num_elements()]
147 }
148}
149
150crate::declare_variants! {
151 default SubsetSum => "2^(num_elements / 2)",
152}
153
154crate::register_brute_force! {
155 SubsetSum decode |_, indices: Vec<usize>| crate::config::config_to_bits(&indices),
156}
157
158#[cfg(feature = "example-db")]
159pub(crate) fn canonical_model_example_specs() -> Vec<crate::example_db::specs::ModelExampleSpec> {
160 vec![crate::example_db::specs::ModelExampleSpec {
162 id: "subset_sum",
163 instance: Box::new(SubsetSum::new(vec![3u32, 7, 1, 8, 2, 4], 11u32)),
164 optimal_config: serde_json::json!(vec![true, false, false, true, false, false]),
165 optimal_value: serde_json::json!(true),
166 }]
167}
168
169#[cfg(test)]
170#[path = "../../unit_tests/models/misc/subset_sum.rs"]
171mod tests;