Number conversion

JavaScript (ES6), 98 bytes

Takes input as (a)(b). Can be very slow if there's no solution, but it should eventually return \$-1\$ (at least in theory).

a=>h=(b,k=0)=>(g=(v,n)=>n--?[...v+''].some(x=>g(+x+v,n)|g(v-x,n)):v==b)(a,k)?k:k<a+[b]?h(b,k+1):-1

Try it online!


05AB1E, 38 37 bytes

3Ýo*Êß8LIå*i®ë¹¸[DIå#¼Ùvy©v®y+®y-}})}¾

Can definitely be golfed a bit more..

Thanks to @tsh for the condition of the first if-statement.

Try it online or verify a few more test cases.

Explanation:

3Ý             # Push the list [0,1,2,3]
  o            # For each value, take 2 to the power that value: [1,2,4,8]
   *           # Multiply each by the first (implicit) input
    Êß         # Check that the second (implicit) input is NOT in this list
8L             # Push the list [1,2,3,4,5,6,7,8]
  Iå           # Check that the second input is in this list
*i             # If both are truthy:
  ®            #  Push -1
 ë             # Else:
  ¹¸           #  Push the first input again, and wrap it into a list
    [          #  Start an infinite loop:
     D         #  Duplicate the list at the top of the stack
      Iå       #  If the second input is in this list:
        #      #   Stop the infinite loop
      ¼        #  Increase the counter variable by 1
      v        #  Loop over each number `y` in the list:
       y©      #   Store the current number `y` in variable `®` (without popping)
         v     #   Inner loop over each digit `y2` of `y`
          ®y+  #    Add digit `y2` to integer `®`
          ®y-  #    Subtract digit `y2` from integer `®`
      }}       #  After the nested loop:
        )      #  Wrap all values on the stack into a list for the next iteration
    }¾         # After the infinite loop: push the counter variable
               # (and output the top of the stack implicitly as result)

Jelly, 33 29 bytes

0ịD;N$+Ɗ;@€)ẎL<¥Ƈȷ7Ʋ=⁴¬ȦƊ¿ẈṪ’

Try it online!

A full program that takes [[a]] as the left argument and b as the right argument.

More efficient version (36 bytes)

Tags:

Code Golf