First you can see that the actual value of the initial number doesn't matter to us since we can move the sticks freely. We just have to keep the number of sticks in the initial number (s
) and the number of digits (n
). So first we calculate the number of sticks in the initial number.
Because the number of digits should remain the same we can assign the digit that need the least amount of sticks to every required digits. Digit 1 requires only two sticks so we initialize the number with n
1 s. This way we are sure that we have fulfilled the number of digits requirement.
After initializing the number with 1 s we should remove 2*n
sticks from s
.
s -= 2*n
Because each 1 requires two sticks and we have used n ones.
Now to maximize the number we have to try and use 9 s as much as possible. Each 9 requires 6 sticks and we have already used 2 sticks for each digit so to make a 9 digit we need 4 other sticks.
There is two exception that we should be careful about:
We shouldn't have any extra sticks. So in each step we should calculate if we use all the other digits with the number that takes the most sticks, do any sticks remain or not? 8 takes the most digits, and it need 7 sticks. So in order to make an 8 digit we need 5 extra sticks. If in any step the remaining sticks s
is equal to remaining digits times 5, we should use 8 for the rest of the digits.
If there are less sticks remaining than 4 ( amount of sticks needed to make a 1 to 9 ), we should take the best decision with respect to the remaining digits and remaining sticks.
Below is a python implementation:
def solve ( s, # number of sticks
n ): #number of digits
s -= 2*n # use n 1 digits
result = ["1"]*n
for i in range(n):
if s == 0: # no sticks remained
break
if s == 5*(n-i): # we should use 8 from now on or else there will be extra sticks
result[i] = "8"
s -= 5
elif s < 4: # not enough sticks to make a 9
if i == n-1: # this is the last digit make the most of if
if s == 3: # maximum digit is 5 with 5 sticks
result[i] = "5"
s -= 3
elif s == 2: # maximum digit is 4 with 4 sticks
result[i] = "4"
s -= 2
elif s == 1: # maximum digit is 7 with 3 sticks
result[i] = "7"
s -= 1
else:
result[i] = "7"
s -= 1 # maximum digit is 7 with less than 6 sticks
else:
result[i] = "9"
s -= 4
print "".join(result)
needed_stick = {"0":6, "1":2, "2":5, "3":5, "4":4, "5":5, "6":6, "7":3, "8":7, "9":6}
initial_number = raw_input("Initial number: ")
s = sum( needed_stick[c] for c in initial_number )
n = len( initial_number )
solve(s,n)
Output:
Initial number: 512
977
Initial number: 079
997
Initial number: 88888888888888
88888888888888
Initial number: 8881
9995