Created
March 6, 2016 17:55
-
-
Save badcc/7fcbf0ae5dd3e637d6ef to your computer and use it in GitHub Desktop.
Optimal respective add, mul, div (a, b, c) to reach target number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Given the target number n | |
| -- Starting with accumulator at 0 | |
| -- what is the optimal number of times | |
| -- you can add a, multiply by b, or divide by | |
| -- c to reach the target number? | |
| -- Output is in Java, but it can be any language that | |
| -- supports integer division. | |
| -- (or use // in Lua 5.3 <3) | |
| local MOD,floor = 1000000,math.floor | |
| local a,b,c,n = 1, 3, 2, 197 | |
| local q,d,o = {0},{0},{'0'} | |
| local opc = { '+'..a,'*'..b,'/'..c } | |
| while (#q > 0) do | |
| if (d[n+1]) then break end | |
| local cur = table.remove(q, 1) | |
| local new = { cur+a, cur*b, floor(cur/c) } | |
| for i = 1, 3 do | |
| local nmod = new[i] >= MOD | |
| if (nmod) then new[i] = new[i] % MOD end | |
| if (not d[new[i]+1]) then | |
| table.insert(q, new[i]) | |
| d[new[i]+1] = d[cur+1] + 1 | |
| local nop = o[cur+1] or '0' | |
| if (i > 1) then | |
| nop = ('(%s)'):format(nop) | |
| end | |
| nop = nop .. opc[i] | |
| if (nmod) then | |
| nop = ('(%s)%%%d'):format(nop,MOD) | |
| end | |
| o[new[i]+1]=nop | |
| end | |
| end | |
| end | |
| print('optimal ops ' .. d[n+1]) | |
| print('System.out.println('..o[n+1]..')') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment