Created
May 7, 2020 13:27
-
-
Save macroxela/8a281c88039c5dfe3cb5fa489affb18e to your computer and use it in GitHub Desktop.
Given integers a & b, finds the largest permutation of digits in b that is smaller than a
This file contains 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 integers a with digits a1 a2 ... am and b with digits | |
#b1 b2 ... bn find the largest permuation of b's digits so | |
# b < a | |
################################################################ | |
from itertools import permutations | |
import math | |
################################################################ | |
def permSolver(a, b): | |
#Initialize variables to store permutations and solution | |
p = permutations(str(a)) | |
plist = [] #to store permutations in a more accessible way | |
sol = -1 | |
#Loop to change permutations in p into more accessible list | |
for i in p: | |
str_perm = "" | |
for j in i: | |
str_perm = str_perm + str(j) | |
str_perm = int(str_perm) | |
plist.append(str_perm) | |
#Loop to find largest permutation smaller than 2nd number | |
#Using max() to speed up process. Worst case still O(n) | |
for i in plist: | |
if max(plist) > b: | |
plist.remove(max(plist)) | |
else: | |
sol = max(plist) | |
break | |
return sol | |
################################################################ | |
def findMax(a, b): | |
a = str(a) #Turn into string for iteration | |
ans = -1 | |
p = permutations(str(a)) #Collect all permutations | |
for i in p: | |
num = int("".join(i)) #Turn permutation into integers | |
#Keeps largest number when smaller than b & no leading 0s | |
if num <= b and i[0] != '0': | |
ans = max(ans, num) | |
return ans | |
################################################################ | |
num1 = 1234 | |
num2 = 5678 | |
#solution = permSolver(num1, num2) | |
#print(solution) | |
sol = findMax(num1, num2) | |
print(sol) | |
#n, m = input().split() | |
''' | |
n = "1234" | |
m = "5678" | |
m = int(m) | |
perms = permutations(n) | |
ans = -1 | |
for p in perms: | |
num = int(''.join(p)) | |
print(num, " ", p) | |
if p[0] != '0' and num <= m: | |
ans = max(ans, num) | |
print(ans) | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment