Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

2 of 5
Added link to TIO
Tino
  • 121
  • 4

pure Bash, 116 bytes

Based on answers from iBug and Léa Gris

#!/bin/bash
test116()
{
n=1ドル;shopt -s extglob;while((n>9));do m=0;for x in ${n//?()/ };do ((m<x))&&m=$x;done;n=$[10#${n/$m/}*m];done;echo $n
}
for k in 9 27 757 1234 26364 432969 1234584 91273716; do printf '%d -> ' "$k"; test116 "$k"; done

Try it online!

Output

9 -> 9
27 -> 4
757 -> 5
1234 -> 8
26364 -> 8
432969 -> 0
1234584 -> 8
91273716 -> 6

Explained:

n=1ドル; # (*) get argument n
shopt -s extglob; # enable ${n//?()/ } below
while((n>9));do # loop until number is <=9
 m=0; # preset maximum to 0
 for x in ${n//?()/ };do # loop over the digits
 ((m<x))&&m=$x; # find max
 done;
 n=$[ # calculate new number
 10# # force base 10 as 0N becomes octal
 ${n/$m/} # remove first occurance of max
 *m]; # multiply m
done;
echo $n # output result

Notes:

  • Shebang #!/bin/bash+LF (12 byte) is not included in the count.
    • We are in bash, so this is already the default
  • If number can directly be passed in as n, 5 bytes (marked with (*) above) can be shoved away
    • Instead ./golf.sh 1234 it would look like n=1234 ./golf.sh
    • However, shell scripts usually get data passed in via argument
    • A read n; if number is passed in from STDIN would add 2 byte.
  • shopt -s extglob; can be left away, if this option is given on commandline
    • Like in n=1234 bash -Oextglob ./golf.sh
    • But extglob is not set by default, hence it is included in the count
  • 10# is needed as ${n/$m/} can leave a number with a leading 0
    • Without the 10# input 91273716 wrongly returns 8.
  • Tested on bash 5.0.17(1)-release from bash 5.0-6ubuntu1.1 from Ubuntu 20.04 LTS
Tino
  • 121
  • 4

AltStyle によって変換されたページ (->オリジナル) /