# Make a minimal and maximal 2-digit number from digits of two 3-digit numbers

Let's solve this user's homework; I think it's an interesting exercise!

### Input

Two 3-digit natural numbers.

### Outputs

Two 2-digit numbers. In each of the output numbers, one digit is taken from one input number, and the other from the other number. The choice is independent. The first output number should be the minimal possible to create using these constraints, and the second one should be the maximal such number (or vice versa).

• Input numbers never have leading zeros; output numbers should also not have leading zeros.
• Input and output can be encoded as numbers, strings, lists of digits, etc.

Examples (in format input - output):

123, 912 - 11, 93
888, 906 - 68, 98
100, 100 - 10, 11
222, 222 - 22, 22
123, 222 - 12, 32
798, 132 - 17, 93

• output numbers should also not have leading zeros - but can an output be a single digit if the first digit is 0? Or can the output be just 0 if both digits are? Nov 10, 2020 at 12:54
• Can we take input as a single 6-character string? Nov 10, 2020 at 16:40
• Could you add 123, 222 as a test case? My first attempt solved all the current cases but failed on this one, printing 11 32 instead of 12 32. Nov 10, 2020 at 20:01
• @pxeger No, I guess this is too much. You have to have some separation between the numbers. Nov 10, 2020 at 21:07
• Suggest testcase: 798, 132. The output should take 1 digit from each number, not two digits from same number.
– tsh
Nov 11, 2020 at 2:38

# Husk, 15 14 13 9 bytes

§,▼▲f←ṁP*


Try it online!

Takes two input arrays, outputs pair (min,max).

-1 byte from Dominic Van Essen.

-1 more byte from Dominic Van Essen (after some more struggling).

-4 bytes taking arrays of digits as input.

## Explanation

§,▼▲f←ṁP*
* cartesian product pairs of the inputs
ṁP  map each to permuations, and flatten the list
f←    remove elements where first digit is falsy(<10)
§,        create pair with
▼▲      minimum and maximum

• 14 bytes with combin... Nov 10, 2020 at 15:57
• (after some more struggling...) 13 bytes... Nov 10, 2020 at 16:05

# 05AB1E, 11 10 bytes

â€Â9ÝKWsà‚


-1 byte thanks to @ovs.

Explanation:

â           # Take the cartesian product of the digits of the two (implicit) inputs
€Â         # Bifurcate each value within the list (short for Duplicate & Reverse copy)
9Ý       # Push the list [0,1,2,3,4,5,6,7,8,9]
K      # Remove those integers (so all integers with leading 0s)
W     # Take the minimum of this list (without popping the list itself)
s    # Swap so the list is at the top of the stack again
à   # Pop and push its maximum
‚  # And pair the minimum and maximum together
# (after which it is output implicitly as result)


# Brachylog, 15 bytes

{∋ᵐpcℕ₁₀}ᶠ⟨⌋≡⌉⟩


Try it online!

{∋ᵐpcℕ₁₀}ᶠ⟨⌋≡⌉⟩
{       }ᶠ      find all possible outputs:
∋ᵐ               select a digit from each number
p              permute them
c             merge them to a number
ℕ₁₀          that number is >= 10
with the list of all possible numbers:
⟨⌋≡⌉⟩ [minimum, maximum]


First time using ⟨⟩! :-⟩

# Jelly, 11 10 bytes

p;p@ḷ/ƇṢ.ị


Try it online!

## Explanation

p;p@ḷ/ƇṢ.ị
p            Cartesian product
;           Join with
@         Reverse arguments
p            Cartesian product
Ƈ      Filter by
/         Reduce by
ḷ            First argument
Ṣ     Sort
.ị   First and last element


-1 byte by using the .ị technique to get the first and last element, thanks to caird

• It’s helping you out golf me even more but 10 bytes Nov 10, 2020 at 14:20
• @cairdcoinheringaahing I just thought of exactly the same thing by looking at your answer! :D We can take this as a team effort. Nov 10, 2020 at 14:31

# Python 3, 81 bytes

lambda a,b:[m(k for i in a for j in b for k in(i+j,j+i)if'1'<k)for m in(min,max)]


Try it online!

a!b=(foldl1[s|i<-a,j<-b,s<-[[i,j],[j,i]],s>"1"])<$>[min,max]  Try it online! This is the same approach as Jitse's Python answer. # C (gcc), 233 $$\\cdots\$$ 189 185 Saved 4 bytes thanks to gastropner!!! Saved 9 13 bytes thanks to ceilingcat!!! #define d(a,i)for(qsort(a,i=3,1,L"\xf06be0f\xd02917beǃ");a[--i]<49;); s;j;i;f(a,b)char*a,*b;{d(a,i)d(b,j)s=a;i=a[i]<b[j]?s=b,a[i]:b[j];j=*a;*b++=j>*b?j=*b,*a:*b;*a++=i;*a=s;*b=j;}  Try it online! Inputs two $$\3\$$-digit strings and returns the min and the max as $$\2\$$-digit substrings in the first $$\2\$$ digits of the first and second input string respectively. • The number of pointers in this program make me worried Nov 10, 2020 at 17:34 • @Razetime Why? That's how you deal with strings (and arrays) in C. Nov 10, 2020 at 17:43 • 208 bytes Nov 10, 2020 at 23:36 • @gastropner Very nice - thanks! :D Nov 10, 2020 at 23:59 • @ceilingcat Crashes with L"\xf06be0f\xd02917beǃ" but s=*b-*a; works brilliantly - thanks! :D Nov 11, 2020 at 22:00 # Retina, 38 bytes Lw$(.).*,.*(.)
$1$2¶$2$1
A0.
O
,,G


Try it online! Link includes test cases. Explanation:

Lw$(.).*,.*(.)$1$2¶$2$1  Take the cartesian product of the inputs and their reverses. A0.  Remove entries with leading zeros. O  Sort. ,,G  Take the first and last result. # Jelly, 12 11 bytes p;U$Ḍ>Ƈ9Ṣ.ị


Try it online!

Input as a list of digits (which the Footer does for you)

-1 byte thanks to Unrelated String

## How it works

p;U$Ḍ>Ƈ9Ṣ.ị - Main link. Takes x on the left and y on the right p - Cartesian product of the digits. Call this list X$        - Group the previous two commands into a monad f(X):
U         -   Reverse each pair in X
;          -   And append it to X
Ḍ       - Convert each pair back to an integer
Ƈ     - Keep those which:
>      -   Are greater than:
9    -   9
Ṣ   - Sort
.ị - Take the first and last elements

• @UnrelatedString Yep, that's a nice golf! Nov 10, 2020 at 15:39
• You can save a byte if you drop Ḍ and change >Ƈ9 to ḷ/Ƈ (filter for the first digit being truthy). Something like ḢƇ doesn't seem to work as it modifies the list.
– Lynn
Nov 10, 2020 at 17:15
• @Lynn At that point, it's basically the same as xigoi's answer, so I'll leave it as is Nov 10, 2020 at 17:17

# Python 2, 70 bytes

lambda*l:[m(m(set(l[i])-{'0'})+m(l[~i])for i in(0,1))for m in min,max]


Try it online!

Python 3, 70 bytes

lambda a,b:[m(m({*a}-{'0'})+m(b),m({*b}-{'0'})+m(a))for m in(min,max)]


Try it online!

These could be shorter if we can take a list of digits as numbers.

• These could be shorter if we can take a list of digits as numbers. - Input and output can be encoded as numbers, strings, lists of digits, etc. Nov 11, 2020 at 8:30

# JavaScript (ES6), 80 bytes

Expects a pair of 3-digit strings. Returns a pair of 2-digit integers.

a=>[(g=n=>(a+[,a]).match(~~(n/10)+'\\d*,\\d*'+n%10)?n:g(n+d%7-2))(d=10),g(d=99)]


Try it online!

### How?

We use a+[,a] to concatenate a[] with itself, with a comma in between. For instance, ['123', '912'] is turned into '123,912,123,912'. (We only need the first 3 entries, but the 4th one is harmless.)

We use the recursive function g to look for some 2-digit integer n such that the above string matches ~~(n/10)+'\\d*,\\d*'+n%10. That is to say:

• $$\\lfloor n/10\rfloor\$$ (the 'left' digit of $$\n\$$)
• followed by some optional digits
• followed by a comma
• followed by some other optional digits
• followed by $$\n\bmod 10\$$ (the 'right' digit of $$\n\$$)

We add $$\(d\bmod 7)-2\$$ to $$\n\$$ between each recursive call, where $$\d\$$ is also the starting point:

• $$\d=10\rightarrow (d\bmod7)-2=1\$$, so we go from $$\n=10\$$ to $$\n=99\$$ (looking for the lowest valid integer)
• $$\d=99\rightarrow (d\bmod7)-2=-1\$$, so we go from $$\n=99\$$ to $$\n=10\$$ (looking for the highest valid integer)

# Desmos, 9+68+147+30+49+64+27+27+8+8+51=488 9+68+93+30+49+28+9+9+8+8+33+31+27=402 bytes

Before you even go on I just want to say that I tried my hardest to golf this, but in the middle of doing this I already knew this was far from a competing answer. But by that time though, I was too far in, so I decided to continue. Upvote for effort? Or not.

## Expression 1: 9 bytes

g=[0,1,2]


## Expression 2: 68 bytes

f(n)=\operatorname{floor}(\frac{\operatorname{mod}(n,10^g10)}{10^g})


## Expression 3: 147 93 bytes

h(a,b)=\left\{sp=0:j(\min(s[k(s)+1],p[k(p)+1]),q(s)+q(p)),d(j(\min(s),\min(p)))\right\}


## Expression 4: 30 bytes

q(a)=\left\{k(a)=0:a,0\right\}


## Expression 5: 49 bytes

k(a)=\operatorname{total}(\left\{a=0:1,0\right\})


## Expression 6: 64 28 bytes

l(a,b)=d(j(\max(s),\max(p)))


## Expression 7: 27 9 bytes

s=d(f(a))


## Expression 8: 27 9 bytes

p=d(f(b))


## Expression 9: 8 bytes

w=h(a,b)


## Expression 10: 8 bytes

z=l(a,b)


## Expression 11: 51 33 bytes

m(a,b)=j(10w+w,10z+z)


## Expression 12: 31 bytes

j(a,b)=\operatorname{join}(a,b)


## Expression 13: 27 bytes

d(a)=\operatorname{sort}(a)


Try It On Desmos The function $$\m(a,b)\$$ is the function where you need to input the two numbers in.

Prettified version: Try It On Desmos!

# CJam, 19 bytes

q~m*_Wf%+:iA,-$(\W=  Try it online! Takes input as two strings and outputs two integers. q~ e# Push inputs "888" "906" m* e# Cartesian product ["89" "80" "86" "89" "80" "86" "89" "80" "86"] _Wf% e# Make a reversed copy ["89" "80" "86" "89" "80" "86" "89" "80" "86"] ["98" "08" "68" "98" "08" "68" "98" "08" "68"] +:i e# Join and parse to integers [89 80 86 89 80 86 89 80 86 98 8 68 98 8 68 98 8 68] A,- e# Remove the numbers from 0 to 9 [89 80 86 89 80 86 89 80 86 98 68 98 68 98 68]$       e# Sort                             [68 68 68 80 80 80 86 86 86 89 89 89 98 98 98]
(\     e# Uncon from left                  68 [68 68 80 80 80 86 86 86 89 89 89 98 98 98]
W=   e# Get the last element             68 98


# Charcoal, 30 bytes

Ｆ²⊞υＳ⟦⌊Ｅυ⁺⌊⁻ι0⌊§υ¬κ⌈Ｅ⟦υ⮌υ⟧⭆ι⌈λ


Try it online! Link is to verbose version of code. Explanation:

Ｆ²⊞υＳ


Input the two numbers as a pair of strings.

⟦


Separate the two outputs.

⌊Ｅυ⁺⌊⁻ι0⌊§υ¬κ


For each string, string take the minimum digit with 0 excluded and the minimum digit of the other string, then take the minimum result.

⌈Ｅ⟦υ⮌υ⟧⭆ι⌈λ


Of the pair and its reverse, take the maximum digit of each string, then take the maximum result.

# MathGolf, 33 32 bytes

─■myG‼<≥xα─6ö6‼≥<3≥\;]─gÅ£(_╓\╙α


Input as a paired list of digits.

Sometimes this language is so frustrating to work with.. :/ It has a cartesian builtin, but it only works on single lists (creating pairs of itself). It also has a convenient ‼ builtin to apply two commands separately to the stack, but this isn't implemented (yet?) for the minimum/maximum builtins (otherwise the _╓\╙α could have been ‼╓╙α)..

Try it online.

Explanation:

─           # Flatten the list of list of digits
■          # Take the cartesian product of this flattened list
m         # Map over each pair:
y        #  And join them together to a single integer
# (note: since we're joining integers, the m implicitly converts them to
# integers as well, removing potential leading 0s)
G       # Push 12
‼      # Apply the following two commands separated on the stack:
<     #  Slice to only keep the first 12 items in the list
≥    #  Slice to remove the first 12 items from the list and keep the remainder
x   # Reverse the second list
α─ # Merge the lists together again (wrap in a pair; flatten)
6ö          # Loop 6 times, using the following 7 commands as body:
6         #  Push 6
‼        #  Apply the following two commands separated on the stack:
≥       #   Slice to remove the first 6 items from the list and keep the remainder
<      #   Slice to only keep the first 6 items in the list
3≥    #  Slice to remove the first 3 items of this sextet
\   #  Swap the top two lists on the stack so the remainder is at the top
;         # After the loop: discard the top of the stack (the final remainder)
]        # Wrap all triplets into a list
─       # And flatten it


We now have all possible pairs (including their reversed pairs).

g           # Filter this list of pairs by,
Å          # using the following 2 commands as body:
£         #  Get the length of this integer
(        #  Decrease it by 1
#  (so 0 for single digit numbers; 1 for intended two-digit numbers)
_       # Duplicate this list of pairs
╓      # Pop and get its minimum
\     # Swap so the duplicated list is at the top
╙    # Pop and get its maximum
α   # And pair them together
# (after which the entire stack joined together is output implicitly)


# Scala, 78 bytes

a=>b=>{val z=for(x<-a;y<-b;c<-Seq(""+x+y,""+y+x)if"09"<c)yield c;z.min->z.max}


Try it online!

Apparently, just storing it in a variable is shorter than folding over all the permutations. Accepts two strings (curried) and returns a 2-tuple of strings.

# Scala, 109 bytes

a=>b=>((-1>>>1,0)/:(for(x<-a;y<-b;c<-Seq(""+x+y,""+y+x)if"09"<c)yield c.toInt)){(t,|)=>(t._1 min|,t._2 max|)}


Try it online!

# Zsh, 90 bytes

for d (${(o)=${(s::)@}})((e&~a&&(a=e,b=d),${z=$d},f=e,e=d))
<<<${z/0/$a}${z/[^0]/$b}\ $d$f


Try it online!

${(o)=${(s::)@}} sorts the digits, which we loop over. By the end of the loop, we have the following parameters set:

• z: The smallest digit
• a: The smallest non-zero digit
• b: The second-smallest non-zero digit
• d,e: The largest digit
• f: The second-largest digit.

If z is zero, then the first number is $a$z. If z is non-zero, then the first number is $z$b.

# Perl 5, 98 94 bytes

sub{@i="@_"=~/./g;(sort grep!/^0/,map{/./;$i[$&].$i[$'],$i[$'].$i[$&]}<{0,1,2}{4,5,6}>)[0,-1]}


Try it online!

• glob"{0,1,2}{4,5,6}" can be changed to <{0,1,2}{4,5,6}> Nov 10, 2020 at 21:44
• @NahuelFouilleul – Thanks! Saved four bytes with that tip. Nov 10, 2020 at 22:19

# Japt, 13 bytes

I/O as an array of digit arrays.

rï cá fÎÍé ¯2


Try it

rï cá fÎÍé ¯2     :Implicit input of array
r                 :Reduce by
ï                :  Cartesian product
c              :Flat map
á             :  Permutations
f           :Filter by
Î          :  First element (0 is falsey)
Í         :Sort
é        :Rotate right
¯2     :Slice to second element


# APL+WIN, 30 bytes.

Index origin = 0. Prompts for input numbers as strings:

(⌊/n~⍳10),⌈/n←,⍎¨(⌽¨n),n←⎕∘.,⎕


Try it online! Thanks to Dyalog Classic

• I think you need ⍳10 instead of ⍳9 to filter out all single digit numbers. Nov 11, 2020 at 0:08
• @Bubbler Thanks, Corrected. Missed the edit when switching index origin to filter zeros Nov 11, 2020 at 7:28

# Ruby, 777470 53 bytes

-17 bytes thanks to Dingus!!

->x,y{((x-).product(y)+(y-).product(x)).minmax}


Try it online!

q l=[minimum,maximum]<*>[filter(>"1")$mapM id=<<[l,reverse l]]  Try it online! # Wolfram Language (Mathematica), 77 bytes MinMax@Select[FromDigits/@Join@@Permutations/@Tuples[IntegerDigits/@#],#>9&]&  Try it online! # Japt, 17 bytes ïV cVïU)Íf¨A é v2  Try it ïV - pair each digits Í - sort f¨A - remove if <10 é - rotate array v2 - return first 2 elements ( Max , Min )  • Thanks to @Shaggy for spotting an error, fixed by adding cVïU • @Shaggy thanks, I didn't pay attention Nov 10, 2020 at 19:55 • I had this for 13, with I/O as an array of digit arrays. Was about to post when I spotted yours. Nov 10, 2020 at 19:57 • I like the use of permutations and fg ! I think it's a slightly different approach.. You may post your answer and get my vote bud Nov 10, 2020 at 21:21 # Perl 5-MList::Util=min,max -p, 89 bytes s/.\K/,/g;s/ /}{/ for($b=reverse),$_;$_=min(@a=grep$_>9,glob("{$_}"),glob"{$b}").$".max@a


Try it online!

• 78 bytes Nov 10, 2020 at 22:20

# Bash, 126 153 158 bytes

for n in {10..99}; {
t=$[n/10] o=$[n%10]
([[ $1 =~$t && $2 =~$o ]]||[[ $2 =~$t && $1 =~$o ]])&&A+=($n) } echo$A-\${A[-1]}



Try it online!

# JavaScript (Node.js), 76 bytes

(a,b)=>[(e=a.map(c=>b.map(d=>[c+d,d+c])).flat(3).sort()).find(x=>x>9),e]


Try it online!

Input as two lists of character, output as two strings.

# C (gcc),  147 144  141 bytes

#define g(x,d)x%q!=d&x/q%q!=d&x/100!=d
v,d=1,q=10;f(a,b){for(v=q;g(a,v/q)|g(b,v%q)&&g(b,v/q)|g(a,v%q)||printf("%d ",v)&&(v=99,d=-d)<0;v+=d);}


Try it online!

### How?

The macro g(x,d) checks whether the digit d appears in the 3-digit integer x by testing $$\x\bmod 10\$$, $$\\lfloor x/10\rfloor\bmod 10\$$ and $$\\lfloor x/100\rfloor\$$. It returns a falsy value if successful.

We look for the first v such that $$\\lfloor v/10\rfloor\$$ appears in a and $$\v \bmod 10\$$ appears in b, or the other way around. We do it once by going from $$\v=10\$$ to $$\v=99\$$ and once by going from $$\v=99\$$ to $$\v=10\$$, to get the lowest and highest valid integers respectively.

# R, 138134128(thanks pajonk)121 117 bytes

k=t(t(expand.grid(strsplit(scan(,""),""))));class(k)=class(1);a=c(A<-k[,1],B<-k[,2]);b=c(B,A);range(10*a[a>0]+b[a>0])


Try it online!

Another solution that takes input as a list of digits, allowed per the rules:

# R, 110(thanks pajonk)10399 93 bytes

i=scan();k=expand.grid(i[1:3],i[4:6]);a=c(A<-k[,1],B<-k[,2]);b=c(B,A);range(10*a[a>0]+b[a>0])


Try it online!

• Second approach a little shorter: Try it online! Nov 12, 2020 at 11:59
• @pajonk Thanks! Works for both, of course.
– John
Nov 12, 2020 at 13:49
• Still, the double transposition in k=... is not necessary, I think. Nov 13, 2020 at 11:21
• @pajonk It is with the first approach (which is more general), but you're right it's not needed for the second.
– John
Nov 13, 2020 at 13:38

# C (MinGW), 150 146 bytes

-4 bytes thanks to ceilingcat

The TiO link needs -lm but MinGW does not.

M,m,x,y,c,t=10;f(a,b){for(M=0,m=99;a;a/=t)for(c=b;c;c/=t)M=fmax(fmax(x=a%t*t+c%t,M),y=c%t*t+a%t),m=y<m&y>9?y:m,m=x<m&x>9?x:m;printf("%d %d",m,M);}


Try it online!

• Suggest M=fmax(fmax(x=a%t*t+c%t,M),y=c%t*t+a%t) instead of x=a%t*t+c%t,y=c%t*t+a%t,M=x>M?x:M,M=y>M?y:M (may need to pass -lm` to the compiler) Nov 13, 2020 at 5:02