bits.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*
  2. Or MAYBE, just use Vec<bool> ?!
  3. While that would use more memory, it would certainly be faster!
  4. Is saving a few bytes (these days) worth it, really?
  5. The iterator would ... already be written for Vec<T>. :P
  6. (Buuut, not quite. I only want true values...)
  7. fn main() {
  8. let vector = vec![true, false, false, true];
  9. for z in vector.iter().enumerate().filter(|x| *x.1) {
  10. println!("{:?}", z);
  11. }
  12. for z in vector.iter().enumerate().filter(|x| *x.1) {
  13. println!("{:?}", z);
  14. }
  15. }
  16. This returns (0, true), (3, true)
  17. fn main() {
  18. let vector = vec![true, false, false, true];
  19. let d : Vec<usize> = vector.iter().enumerate().filter(|x| *x.1).map(|x| x.0).collect();
  20. println!("{:?}", &d);
  21. }
  22. This returns (0,3) ! This is what I was looking for!
  23. I'd rather have an iterator (like I have below), but I might
  24. have to compromise here.
  25. let d = vector.iter().enumerate().filter(|x| *x.1).map(|x| x.0);
  26. for dv in d {
  27. println!(" {}", dv);
  28. }
  29. There we go, map returns iterator. :D
  30. Enumerate creates (index, value),
  31. filter finds "true" items,
  32. map returns iterator (with index)!
  33. And we could handle any crazy size as well... :O
  34. */
  35. use std::ops::RangeBounds;
  36. use std::fmt;
  37. // use std::iter::{Map, Filter, Enumerate};
  38. #[derive(Clone)]
  39. pub struct GenBits(pub Vec<bool>);
  40. impl GenBits {
  41. pub fn new(size: usize) -> Self {
  42. GenBits(vec![false; size])
  43. }
  44. pub fn clear(&mut self) {
  45. for i in 0..self.0.len() {
  46. self.0[i] = false;
  47. }
  48. }
  49. pub fn fill(&mut self, value: bool) {
  50. for i in 0..self.0.len() {
  51. self.0[i] = value;
  52. }
  53. }
  54. pub fn set(&mut self, bit: usize, state: bool) {
  55. self.0[bit] = state;
  56. }
  57. pub fn get(&self, bit: usize) -> bool {
  58. self.0[bit]
  59. }
  60. pub fn set_bits<R: RangeBounds<usize> + IntoIterator<Item = usize>>(&mut self, bits: R) {
  61. for i in bits {
  62. self.0[i as usize] = true;
  63. }
  64. }
  65. pub fn count_set(&self) -> usize {
  66. self.0.iter().filter(|&x| *x).count()
  67. }
  68. // https://depth-first.com/articles/2020/06/22/returning-rust-iterators/
  69. #[deprecated = "Use iter() instead."]
  70. /// Returns the indexes of items that are true
  71. pub fn indexes(&self) -> impl Iterator<Item = usize> + '_ {
  72. self.0.iter().enumerate().filter(|x| *x.1).map(|x| x.0)
  73. }
  74. /// The "default" iterator for GenBits returns this.
  75. pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
  76. self.0.iter().enumerate().filter(|x| *x.1).map(|x| x.0)
  77. }
  78. /*
  79. pub fn iter(&self) -> std::slice::Iter<'_, bool> {
  80. self.0.iter()
  81. }
  82. */
  83. /// Display bits that are set.
  84. /// +1 is added to the display, so it matches the cell values (1..N)
  85. pub fn display(&self) -> String {
  86. self.0
  87. .iter()
  88. .enumerate()
  89. .filter(|x| *x.1)
  90. .map(|x| x.0)
  91. .map(|i| (i + 1).to_string())
  92. // .map(|i| i.to_string())
  93. .collect::<Vec<_>>()
  94. .join(",")
  95. }
  96. }
  97. impl fmt::Debug for GenBits {
  98. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  99. write!(f, "({})", self.0.iter().enumerate().filter(|x| *x.1).map(|x| x.0.to_string()).collect::<Vec<_>>().join(","))
  100. }
  101. }
  102. impl fmt::Display for GenBits {
  103. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  104. write!(f, "({})", self.0.iter().enumerate().filter(|x| *x.1).map(|x| x.0.to_string()).collect::<Vec<_>>().join(","))
  105. }
  106. }
  107. impl PartialEq for GenBits {
  108. fn eq(&self, other: &Self) -> bool {
  109. if self.0.len() != other.0.len() {
  110. return false;
  111. }
  112. for i in 0..self.0.len() {
  113. if self.0[i] != other.0[i] {
  114. return false;
  115. }
  116. }
  117. true
  118. }
  119. }
  120. #[cfg(test)]
  121. mod tests {
  122. // use crate::sudoku::*;
  123. use crate::bits::*;
  124. #[test]
  125. fn check_u16() {
  126. const SIZE: usize = 9;
  127. let mut p = GenBits::new(SIZE);
  128. p.clear();
  129. for i in 0..9 {
  130. let mut result = p.get(i);
  131. assert_eq!(result, false);
  132. p.set(i, true);
  133. result = p.get(i);
  134. assert_eq!(result, true);
  135. }
  136. p = GenBits::new(SIZE);
  137. p.set(3, true);
  138. p.set(5, true);
  139. p.set(6, true);
  140. assert_eq!(3, p.count_set());
  141. let values: Vec<usize> = p.iter().collect();
  142. assert_eq!(values, vec!(3, 5, 6));
  143. assert_eq!(3, p.count_set());
  144. p.set(0, true);
  145. assert_eq!(4, p.count_set());
  146. p = GenBits::new(SIZE);
  147. p.set_bits(0..6);
  148. for i in 0..6 {
  149. let result = p.get(i);
  150. assert_eq!(result, true);
  151. }
  152. assert_eq!(p.get(6), false);
  153. }
  154. #[test]
  155. fn check_u32() {
  156. const SIZE: usize = 29;
  157. let mut p = GenBits::new(SIZE);
  158. p.clear();
  159. for i in 0..29 {
  160. let mut result = p.get(i);
  161. assert_eq!(result, false);
  162. p.set(i, true);
  163. result = p.get(i);
  164. assert_eq!(result, true);
  165. }
  166. p = GenBits::new(SIZE);
  167. p.set(13, true);
  168. p.set(15, true);
  169. p.set(26, true);
  170. assert_eq!(3, p.count_set());
  171. let values: Vec<usize> = p.iter().collect();
  172. assert_eq!(values, vec!(13, 15, 26));
  173. assert_eq!(3, p.count_set());
  174. p.set(0, true);
  175. assert_eq!(4, p.count_set());
  176. p = GenBits::new(SIZE);
  177. p.set_bits(10..26);
  178. for i in 10..26 {
  179. let result = p.get(i);
  180. assert_eq!(result, true);
  181. }
  182. assert_eq!(p.get(9), false);
  183. assert_eq!(p.get(27), false);
  184. }
  185. }
  186. /*
  187. // -> Map<Filter<Enumerate<std::slice::Iter<'_, bool>>>>
  188. pub fn indexes(&self) -> std::slice::Iter<usize> {
  189. self.data.iter().enumerate().filter(|x| *x.1).map(|x| x.0)
  190. }
  191. */
  192. /*
  193. use bit_field::BitField;
  194. // If I wanted to do 4x4 or 5x5, I would need more bits. (u32).
  195. use num::Integer;
  196. use std::ops::RangeBounds;
  197. use std::fmt;
  198. #[derive(Copy, Clone, PartialEq)]
  199. pub struct GenBits<T: Integer + BitField>(pub T);
  200. impl<T: Integer + BitField> GenBits<T> {
  201. pub fn clear(&mut self) {
  202. self.0 = T::zero();
  203. }
  204. pub fn set(&mut self, bit: usize, value: bool) {
  205. self.0.set_bit(bit, value);
  206. }
  207. #[must_use]
  208. pub fn get(&self, bit: usize) -> bool {
  209. self.0.get_bit(bit)
  210. }
  211. pub fn set_bits<R: RangeBounds<u8> + IntoIterator<Item = u8>>(&mut self, bits: R) {
  212. for i in bits {
  213. self.set(i as usize, true);
  214. }
  215. }
  216. #[must_use]
  217. pub fn count_set(&self) -> u8 {
  218. let mut count: u8 = 0;
  219. for i in 0..T::BIT_LENGTH {
  220. if self.get(i) {
  221. count += 1;
  222. }
  223. }
  224. count
  225. }
  226. /// Display bits that are set.
  227. /// +1 is added to the display, so it matches the cell values (1..N)
  228. pub fn display(&self) -> String {
  229. self.iter()
  230. .map(|i| (i+1).to_string())
  231. // .map(|i| i.to_string())
  232. .collect::<Vec<_>>().join(",")
  233. }
  234. }
  235. impl<T: Integer + BitField + ToString> fmt::Debug for GenBits<T> {
  236. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  237. let result = self.iter()
  238. // .map(|i| (i+1).to_string())
  239. .map(|i| i.to_string())
  240. .collect::<Vec<_>>().join(",");
  241. if result.is_empty() {
  242. return write!(f, "{{}}")
  243. } else {
  244. return write!(f, "<{}>", result)
  245. }
  246. }
  247. }
  248. pub struct GenBitsIterator<'a, T: Integer + BitField> {
  249. pub possible: &'a GenBits<T>,
  250. pub index: usize,
  251. }
  252. impl<T: Integer + BitField> GenBits<T> {
  253. pub fn iter(&self) -> GenBitsIterator<T> {
  254. GenBitsIterator {
  255. possible: self,
  256. index: 0,
  257. }
  258. }
  259. }
  260. impl<'a, T: Integer + BitField> Iterator for GenBitsIterator<'a, T> {
  261. type Item = u8;
  262. fn next(&mut self) -> Option<u8> {
  263. while (self.index < T::BIT_LENGTH) && (!self.possible.get(self.index as usize)) {
  264. self.index += 1;
  265. }
  266. if self.index == T::BIT_LENGTH {
  267. None
  268. } else {
  269. self.index += 1;
  270. Some((self.index - 1) as u8)
  271. }
  272. }
  273. }
  274. #[cfg(test)]
  275. mod tests {
  276. // use crate::sudoku::*;
  277. use crate::bits::*;
  278. #[test]
  279. fn check_u16() {
  280. let mut p = GenBits::<u16>(0);
  281. p.clear();
  282. for i in 0..9 {
  283. let mut result = p.get(i);
  284. assert_eq!(result, false);
  285. p.set(i, true);
  286. result = p.get(i);
  287. assert_eq!(result, true);
  288. }
  289. p = GenBits::<u16>(0);
  290. p.set(3, true);
  291. p.set(5, true);
  292. p.set(6, true);
  293. assert_eq!(3, p.count_set());
  294. let values: Vec<u8> = p.iter().collect();
  295. assert_eq!(values, vec!(3, 5, 6));
  296. assert_eq!(3, p.count_set());
  297. p.set(0, true);
  298. assert_eq!(4, p.count_set());
  299. p = GenBits::<u16>(0);
  300. p.set_bits(0..6);
  301. for i in 0..6 {
  302. let result = p.get(i);
  303. assert_eq!(result, true);
  304. }
  305. assert_eq!(p.get(6), false);
  306. }
  307. #[test]
  308. fn check_u32() {
  309. let mut p = GenBits::<u32>(0);
  310. p.clear();
  311. for i in 0..29 {
  312. let mut result = p.get(i);
  313. assert_eq!(result, false);
  314. p.set(i, true);
  315. result = p.get(i);
  316. assert_eq!(result, true);
  317. }
  318. p = GenBits::<u32>(0);
  319. p.set(13, true);
  320. p.set(15, true);
  321. p.set(26, true);
  322. assert_eq!(3, p.count_set());
  323. let values: Vec<u8> = p.iter().collect();
  324. assert_eq!(values, vec!(13, 15, 26));
  325. assert_eq!(3, p.count_set());
  326. p.set(0, true);
  327. assert_eq!(4, p.count_set());
  328. p = GenBits::<u32>(0);
  329. p.set_bits(10..26);
  330. for i in 10..26 {
  331. let result = p.get(i);
  332. assert_eq!(result, true);
  333. }
  334. assert_eq!(p.get(9), false);
  335. assert_eq!(p.get(27), false);
  336. }
  337. }
  338. */