Guest User

Untitled

a guest
Jun 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #![deny(overflowing_literals)]
  2.  
  3. type Input = u32;
  4.  
  5. const BOUND: Input = 1_000_000;
  6. const _ENSURE_NO_OVERFLOW: Input = BOUND * 3;
  7.  
  8. #[derive(Debug, PartialEq, Eq)]
  9. enum CountStepsError {
  10. Zero,
  11. OutOfBound,
  12. }
  13.  
  14. fn count_steps(target: Input) -> Result<usize, CountStepsError> {
  15. use std::cmp::Ordering::*;
  16. use CountStepsError::*;
  17.  
  18. if target == 0 {
  19. return Err(Zero);
  20. }
  21.  
  22. if target >= BOUND {
  23. return Err(OutOfBound);
  24. }
  25.  
  26. if target == 1 {
  27. return Ok(0);
  28. }
  29.  
  30. let mut prev = vec![1];
  31. let mut steps = 0;
  32.  
  33. loop {
  34. steps += 1;
  35. let mut buf = Vec::with_capacity(prev.len() * 3);
  36.  
  37. for &x in &prev {
  38. let x_1 = x + 1;
  39. match x_1.cmp(&target) {
  40. Greater => unreachable!(),
  41. Equal => return Ok(steps),
  42. Less => {
  43. buf.push(x_1);
  44. }
  45. }
  46.  
  47. let x2 = x * 2;
  48. match x2.cmp(&target) {
  49. Greater => (),
  50. Equal => return Ok(steps),
  51. Less => {
  52. buf.push(x2);
  53.  
  54. let x3 = x * 3;
  55. match x3.cmp(&target) {
  56. Greater => (),
  57. Equal => return Ok(steps),
  58. Less => {
  59. buf.push(x3);
  60. }
  61. }
  62. }
  63. }
  64. }
  65.  
  66. buf.sort_unstable();
  67. buf.dedup();
  68. prev = buf;
  69. }
  70. }
  71.  
  72. #[test]
  73. fn some_variants() {
  74. assert_eq!(count_steps(1), Ok(0));
  75. assert_eq!(count_steps(9), Ok(2));
  76. assert_eq!(count_steps(15), Ok(4));
  77. assert_eq!(count_steps(82), Ok(5));
  78. assert_eq!(count_steps(768), Ok(9));
  79. }
  80.  
  81. #[test]
  82. fn check_error() {
  83. use CountStepsError::*;
  84.  
  85. assert_eq!(count_steps(0), Err(Zero));
  86. assert_eq!(count_steps(BOUND), Err(OutOfBound));
  87. }
Add Comment
Please, Sign In to add comment