Advertisement
Guest User

Untitled

a guest
Dec 7th, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.71 KB | None | 0 0
  1. /// Check if the given sequence of tokens can reach the target value
  2. /// when combined by multiplication or addition (always processed left-to-right)
  3. /// If 'can_concat' is true, also check concatenation as one of the valid operations
  4. fn is_solveable(target: u64, tokens: &[u64], can_concat: bool) -> bool {
  5.     match tokens.len() {
  6.         // At the end of the list: did it reach the target?
  7.         i if i < 2 => target == tokens[0],
  8.         // Try each operator and recurse
  9.         _ => {
  10.             let (&last, rest) = tokens.split_last().unwrap();
  11.             // Stop early if target is already greater than the last element of the list
  12.             // Try addition first
  13.             (target > last) && is_solveable(target - last, rest, can_concat)
  14.             // Try multiplication. Short-circuit if target is not a multiple of the last element
  15.                 || (target % last == 0 && is_solveable(target / last, rest, can_concat))
  16.             // Try concatenation if its enabled
  17.                 || (can_concat && try_concat(target, tokens))
  18.         }
  19.     }
  20. }
  21.  
  22. /// Check if its possible for a solution to exist where the last element
  23. /// is concatenated onto the result of the other values
  24. /// Short-circuit if the target value doesn't end with the last element (as a string)
  25. /// Or if the target value _matches_ the last element
  26. fn try_concat(target: u64, tokens: &[u64]) -> bool {
  27.     let (&last, rest) = tokens.split_last().unwrap();
  28.     let target = target.to_string();
  29.     let last = last.to_string();
  30.     match target.strip_suffix(&last) {
  31.         Some(prefix) => {
  32.             (!prefix.is_empty()) && is_solveable(prefix.parse::<u64>().unwrap(), rest, true)
  33.         }
  34.         None => false,
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement