Write a program or function that translates a numerical telephone number into text that makes it easy to say. When digits are repeated, they should be read as "double n" or "triple n".



A string of digits.

  • Assume all characters are digits from 0 to 9.
  • Assume the string contains at least one character.


Words, separated by spaces, of how these digits can be read out loud.

  • Translate digits to words:

    0 "oh"
    1 "one"
    2 "two"
    3 "three"
    4 "four"
    5 "five"
    6 "six"
    7 "seven"
    8 "eight"
    9 "nine"

  • When the same digit is repeated twice in a row, write "double number".

  • When the same digit is repeated thrice in a row, write "triple number".
  • When the same digit is repeated four or more times, write "double number" for the first two digits and evaluate the rest of the string.
  • There is exactly one space character between each word. A single leading or trailing space is acceptable.
  • Output is not case sensitive.


Source code with the least bytes.

Test Cases

input        output
0123         oh one two three
4554554      four double five four double five four
000          triple oh
00000        double oh triple oh
66667888     double six double six seven triple eight
19999999179  one double nine double nine triple nine one seven nine
  • 38
    \$\begingroup\$ Anyone interested in "speech golf" should note that "double six" takes longer to say than "six six". Of all the numerical possibilities here, only "triple seven" saves syllables. \$\endgroup\$
    – Purple P
    Commented Aug 13, 2019 at 4:40
  • 13
    \$\begingroup\$ @Purple P: And as I'm sure you know, 'double-u double-u double-u'>'world wide web'.. \$\endgroup\$
    – Chas Brown
    Commented Aug 13, 2019 at 4:43
  • 11
    \$\begingroup\$ I vote to change that letter to "dub". \$\endgroup\$ Commented Aug 13, 2019 at 4:45
  • 8
    \$\begingroup\$ I know this is only an intellectual exercise, but I have in front of me a gas bill with the number 0800 048 1000, and I would read that as "oh eight hundred oh four eight one thousand". The grouping of digits is significant to human readers, and some patterns such as "0800" are treated specially. \$\endgroup\$ Commented Aug 14, 2019 at 8:29
  • 3
    \$\begingroup\$ @PurpleP Anyone interested in clarity of speech, however, especially when speaking over the phone, might want to use "double 6" since it's clearer that the speaker means two sixes and didn't repeat the number 6 accidentally. People aren't robots :P \$\endgroup\$
    – user91988
    Commented Aug 14, 2019 at 20:47

21 Answers 21


8088 Assembly, IBM PC DOS, 164 159 156 155 bytes


00000000: d1ee 8a0c 03f1 53fd ac3a d075 0343 e2f7  ......S..:.u.C..
00000010: 85db 741c 5f8a d043 f6c3 0174 0a57 bd64  ..t._..C...t.W.d
00000020: 0155 83eb 0374 0957 bd5d 0155 4b4b 75f7  .U...t.W.].UKKu.
00000030: 8ad0 2c2f 7213 518a f0b0 24b1 31bf 6a01  ..,/r.Q...$.1.j.
00000040: fcf2 aefe ce75 fa59 57e2 bc5a 85d2 740c  .....u.YW..Z..t.
00000050: b409 cd21 b220 b402 cd21 ebef c364 6f75  ...!. ...!...dou
00000060: 626c 6524 7472 6970 6c65 246f 6824 6f6e  ble$triple$oh$on
00000070: 6524 7477 6f24 7468 7265 6524 666f 7572  e$two$three$four
00000080: 2466 6976 6524 7369 7824 7365 7665 6e24  $five$six$seven$
00000090: 6569 6768 7424 6e69 6e65 24              eight$nine$

Build and test executable using xxd -r from above, or download PHONE.COM.

Unassembled listing:

D1 EE       SHR  SI, 1              ; point SI to DOS PSP (80H) for input string
8A 0C       MOV  CL, BYTE PTR[SI]   ; load input string length into CX
03 F1       ADD  SI, CX             ; move SI to end of input 
53          PUSH BX                 ; push a 0 to signal end of output stack 
FD          STD                     ; set LODS direction to reverse 
AC          LODSB                   ; load next char from [SI] into AL, advance SI 
3A D0       CMP  DL, AL             ; is it same as previous char? 
75 03       JNZ  NEW_CHAR           ; if not, it's a different char 
43          INC  BX                 ; otherwise it's a run, so increment run length
E2 F7       LOOP CHAR_LOOP          ; move on to next char 
85 DB       TEST BX, BX             ; is there a run greater than 0? 
74 1C       JZ   GET_WORD           ; if not, look up digit name 
5F          POP  DI                 ; get name for the current digit 
8A D0       MOV  DL, AL             ; save current char in DL 
43          INC  BX                 ; adjust run count (BX=1 means run of 2, etc)
F6 C3 01    TEST BL, 1              ; is odd? if so, it's a triple
74 0A       JZ   IS_DBL             ; is even, so is a double 
57          PUSH DI                 ; push number string ("one", etc) to stack
BD 0164     MOV  BP, OFFSET T       ; load "triple" string 
55          PUSH BP                 ; push to stack 
83 EB 03    SUB  BX, 3              ; decrement run count by 3 
74 09       JZ   GET_WORD           ; if end of run, move to next input char 
57          PUSH DI                 ; push number string to stack
BD 015D     MOV  BP, OFFSET D       ; load "double" string 
55          PUSH BP                 ; push to stack 
4B          DEC  BX                 ; decrement by 2
4B          DEC  BX
75 F7       JNZ  IS_DBL             ; if not end of run, loop double again 
8A D0       MOV  DL, AL             ; save current char into DL
2C 2F       SUB  AL, '0'-1          ; convert ASCII char to 1-based index 
72 13       JB   NOT_FOUND          ; if not a valid char, move to next
51          PUSH CX                 ; save outer loop counter 
8A F0       MOV  DH, AL             ; DH is the index to find, use as scan loop counter
B0 24       MOV  AL, '$'            ; word string is $ delimited
B1 31       MOV  CL, 031H           ; search through length of word data (49 bytes)
BF 016A     MOV  DI, OFFSET W       ; reset word data pointer to beginning
FC          CLD                     ; set DF to scan forward for SCAS 
F2/ AE      REPNZ SCASB             ; search until delimiter '$' is found in [DI]
FE CE       DEC  DH                 ; delimiter found, decrement counter 
75 FA       JNZ  SCAN_LOOP          ; if counter reached 0, index has been found 
59          POP  CX                 ; restore outer loop position
57          PUSH DI                 ; push string on stack 
E2 BC       LOOP CHAR_LOOP          ; move to next char in input 
5A          POP  DX                 ; get string from top of stack 
85 D2       TEST DX, DX             ; it is the last? 
74 0C       JZ   EXIT               ; if so, exit 
B4 09       MOV  AH, 09H            ; DOS display string function 
CD 21       INT  21H                ; write string to console 
B2 20       MOV  DL, ' '            ; load space delimiter 
B4 02       MOV  AH, 02H            ; DOS display char function 
CD 21       INT  21H                ; write char to console 
EB EF       JMP  OUTPUT_STACK       ; continue looping 
C3          RET                     ; return to DOS 
D   DB "double$" 
T   DB "triple"
W   DB "$oh$","one$","two$","three$","four$","five$","six$","seven$","eight$","nine$" 


The input string is read right to left to make it easier to find a triple. The output is pushed onto the x86 stack to simplify reversing out the display order and also facilitate rearranging the "double" and "triple" words to precede the digit's name.

If the next digit is different than the last, the name is looked up in the list of words and pushed on to the stack. Since there's no formal concept of an "indexed array of variable-length strings" in machine code, the list of words is scanned i (the word's index) number of times for the string delimiter ($) to find the corresponding word. Helpfully, x86 does have a pair of short instructions (REPNZ SCASB which is similar to memchr() in C), that simplifies this (thanks CISC!).

If the digit is the same as the previous one, the counter for the length of a "run" is incremented and continues looping leftward on the input. Once the run is over, the digit's name is taken from the stack since it will need to placed after the "double" or "triple" for each grouping. If the length of the run is odd (and run length is > 1), the digit's name followed by the string "triple" is pushed to the stack and the run length is reduced by 3. Since the run length will now be even, the step is repeated for "double" until the run length is 0.

When the input string has reached the end, the stack is dumped out with each saved string written to the screen in reverse order.


A standalone PC DOS executable, input from command line output to console.

enter image description here

Download and test PHONE.COM.

  • \$\begingroup\$ repne scasb is memchr (or strchr if you know there's going to be a hit), not strstr. \$\endgroup\$ Commented Aug 15, 2019 at 23:49
  • \$\begingroup\$ Is CH=0 on process entry guaranteed by a standard, or is that just what some DOS version happens to do? I notice you assume that mov cl, byte[si] is equivalent to movzx cx, byte [si]. I wonder if using a different reg, like AH, for the count with dec ah / jnz instead of loop would save anything from not having to push/pop CX. Probably not, and you don't have any 16-bit regs left that would allow 1-byte dec. \$\endgroup\$ Commented Aug 15, 2019 at 23:56
  • 1
    \$\begingroup\$ @PeterCordes, for the CH=0 I go by fysnet.net/yourhelp.htm, which for any reasonable release of DOS is always zero'd, same with BX. Good thought about the zero-extend mov, though technically I don't think movzx is available on the 808x (keeping the target platform an IBM PC 5150 and all). I fiddled around with all of the registers as best I could to save the bytes, but if you see something I likely missed, please let me know! \$\endgroup\$
    – 640KB
    Commented Aug 16, 2019 at 0:04
  • 1
    \$\begingroup\$ It's more accurate to call it memchr IMO. The "string instruction" naming misleads people into thinking they work on implicit-length C strings, but really they work on explicit-length strings like std::string or buffers. Like memcpy, memset (movs/stos), memchr/memrchr (repne scas with DF=0 or 1), and memcmp (repe cmps). The only C equivalent for repe scas is strspn because I don't think there's a mem function for that. You can even describe stosw or stosd as wmemset for example. \$\endgroup\$ Commented Aug 16, 2019 at 0:06
  • 1
    \$\begingroup\$ movzx costs an extra opcode byte, and yes it was only introduced with 386. It was just easier to type to describe the fact that you're doing a low-byte-merge and assuming it's correctly zero extended. If you do know CX or at least CH=0, then yes for golfing always go with mov to CL. But outside of golfing, x86's go-to byte-load instructions are movzx and movsx: they avoid any false dependencies or other partial-register shenanigans. On modern CPUs with a dword destination, they're as fast as dword mov loads. \$\endgroup\$ Commented Aug 16, 2019 at 0:09

05AB1E, 53 52 51 50 49 bytes


Try it online!


γ                      # split input in groups of consecutive equal digits
 ε              ]      # for each group
  €T                   #  add a 10 before each digit (66 -> [10, 6, 10, 6])
    2äθ                #  keep only the second half of that list
       ¬MÊi     ]      #  if the first element is not the maximum
           ¨           #   drop the last element
            ₃1ǝ        #   replace the second element with 95
               R       #   reverse the list
˜                      # flatten
 “...“                 # compressed string: "oh one two ... nine double triple"
      #                # split on spaces
       sè              # index (wraps around, so 95 yields "triple")
         ¸»            # join with spaces
  • 1
    \$\begingroup\$ Oh, M also looks inside lists when determining the maximum integer on the stack? Didn't knew that. Sounds like something to remember. :) \$\endgroup\$ Commented Aug 14, 2019 at 6:13

05AB1E, 61 56 53 52 51 bytes

γvyDg;LàäRv… ‹¶½¿#yg蓊瀵‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“#yè])áðý

-9 bytes thanks to @Grimy.

Try it online or verify all test cases.


γ               # Split the (implicit) input into substrings of equal adjacent characters
                #  i.e. "199999991779" → ["1","9999999","1","77","9"]
 v              # Loop over each substring `y`:
   Dg           #  Get the length of a copy of the substring
     ;          #  Halve it
      L         #  Create a list in the range [1, length/2], where odd lengths are
                #  automatically truncated/floored
                #   i.e. "1" (length=1) → 0.5 → [1,0]
                #   i.e. "9999999" (length=7) → 3.5 → [1,2,3]
       à        #  Pop and push the maximum of this list
  y     ä       #  Divide the string into that many parts
                #   → ["1"]
                #   → ["999","99","99"]
         R      #  Reverse the list
                #   → ["99","99","999"]
  v             # Inner loop over each item `y`:
   … ‹¶½¿       #  Push dictionary word: "  double triple"
         #      #  Split it on spaces: ["","","double","triple"]
          yg    #  Get the length of the current item `y`
            è   #  And use it to (0-based) index into the list
                #  Push dictionary string "oh two three four five six seven eight nine"
     #          #  Split it on spaces: ["oh","two","three",...,"nine"]
      yè        #  Use `y` to index into the string-list (with automatic wrap-around,
                #  so since there are 10 words, it basically indexes with a single digit
                #  due to an implicit modulo-10)
                #   i.e. "77" → "seven"
 ]              # Close both loops
  )             # Wrap all values on the stack into a list
   á            # Only keep letters, which removes the empty strings from the list
    ðý          # And join the list on spaces
                # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why … ‹¶½¿ is " double triple" and “Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“ is "oh two three four five six seven eight nine".

  • 1
    \$\begingroup\$ @Grimy Ah, of course.. I added the if(length>=4) before adding the rest, but of course it isn't necessary for integers of size 1,2,3, because the ;Å2¨3ª£ will leave the strings intact (merely wrapped in a list we flatten after the map anyway). Thanks for noticing! And looking forward seeing your answer with Åγ. I indeed had the feeling the first part could be done a lot shorter somehow. \$\endgroup\$ Commented Aug 13, 2019 at 11:49
  • 1
    \$\begingroup\$ Dg;LàäR is still a byte shorter than āɨšJõK, and much more similar to what you originally had. \$\endgroup\$
    – Grimmy
    Commented Aug 13, 2019 at 15:02
  • 1
    \$\begingroup\$ @Grimy Ah, that's indeed closed to what I initially had indeed, I like it. :) Thanks again! \$\endgroup\$ Commented Aug 13, 2019 at 15:27
  • 1
    \$\begingroup\$ @Grimy Been able to find one more golf myself which I forgot about.. á instead of õK at the end. :) \$\endgroup\$ Commented Aug 13, 2019 at 15:33
  • 1
    \$\begingroup\$ Nice find with á! Here's a 51 and another one. 50 feels possible. \$\endgroup\$
    – Grimmy
    Commented Aug 13, 2019 at 16:06

QuadR, 137 bytesSBCS

Title case with a leading space.

{⍺←(,¨⎕D)⎕R('OhOneTwoThreeFourFiveSixSevenEightNine'(∊⊂⊣)⎕A)⋄' '∊w←⍺,⊃⍵:⍬⋄1=≢⍵:⍺⍵⋄3=≢⍵:'Triple',w⋄'Double',w,∇2↓⍵}⍵M

Try it online!

ϵnlist (flatten)
¯2↑¨ take the last two characters (padding on left with a space) of each characters
@ at positions where
(∊∘⎕A) characters are members of the uppercase Alphabet
 in the result of the below PCRE Replace operation…

(.) any character
\1 followed by itself
* zero or more times, is replaced by the result of the following…

{…}⍵M "dfn"; is the Match of the above pattern

('OhOneTwoThreeFourFiveSixSevenEightNine'()⎕A) apply the following anonymous tacit function with the long string and the uppercase Alphabet as left arguments:

 membership (of letters in the long string in the uppercase alphabet)

 partitions (with a new partition beginning whenever is-a-member

 the left argument (i.e. the long string)

()⎕R PCRE Replace the following patterns with those words:

⎕D the digits 0 through 9

 treat each as a separate pattern

⍺← assign this replacement function to (for alphabetise)


⊃⍵ the first character of the match

, as a string

 apply to it

w← assign this to w (for word)

' '∊: if space is a member thereof (i.e. if the match was empty):

 return nothing (becomes the empty string)


1=≢⍵: if one equals the tally of characters in the match (i.e. its length):

⍺⍵ alphabetise that digit


3=≢⍵: if three equals the tally of characters in the match (i.e. its length):

'Triple',w prepend "Triple" to the word


2↓⍵ drop to digits from the match

 recurse on that

w, prepend the word

'Double', prepend "Double"


JavaScript (ES6),  161 160 152  144 bytes

The output includes a single leading space.

s=>[n=>' '+'oh/one/two/three/four/five/six/seven/eight/nine'.split`/`[n],'$1 double$2','triple$2'].map(r=>s=s.replace(/(\S*)( \S+)\2|\d/g,r))&&s

Try it online!

or See the formatted source code


The conversion is processed in three steps:

  1. replace each digit with the corresponding English word, preceded by a space
  2. replace each pattern "X X" with "double X"
  3. replace each pattern "double X X" with "triple X"

To save bytes, we use the same regular expression for all steps:

/(\S*)( \S+)\2|\d/g

which works as follows:

(\S*)  -> 1st capturing group: any word, or nothing at all
( \S+) -> 2nd capturing group: a space, followed by a word
\2     -> a copy of the 2nd capturing group
|\d    -> or try to capture a digit instead (for step 1)

At step 1, we use a callback function that picks the correct word from a lookup table:

  • "799999"" seven nine nine nine nine nine"

At step 2, we replace with "$1 double$2":

  • " (seven)( nine)( nine)"" seven double nine"
  • "( nine)( nine) nine"" double nine nine"

At step 3, we replace with "triple$2":

  • " (double)( nine)( nine)"" triple nine"

Wolfram Language (Mathematica), 115 bytes

{Switch[L=Tr[1^{##}],1," ",3," triple ",_," double "],If[#<1,"oh",IntegerName@#],If[L>3,#0@##3,""]}&@@@Split@#<>""&

Try it online!

Takes a list of digits as input. Output includes a leading space.


Stax, 56 bytes


Run and debug it


Python 2, 171 169 168 bytes

while s:c=s[0];n=(s[1:2]==c)+(s[:3]==c*3!=s[1:4]);print'   eellpbiurotd'[-n:0:-2]+'oh one two three four five six seven eight nine'.split()[int(c)],;s=s[1+n:]

Try it online!

-1 byte, thanks to Jitse

  • \$\begingroup\$ Beat me again! Save 1 byte like so \$\endgroup\$
    – Jitse
    Commented Aug 13, 2019 at 9:14
  • \$\begingroup\$ @Jitse, that doesn't work for 1312 ;) \$\endgroup\$
    – TFeld
    Commented Aug 13, 2019 at 9:43
  • \$\begingroup\$ Ah, you're right! \$\endgroup\$
    – Jitse
    Commented Aug 13, 2019 at 9:45
  • \$\begingroup\$ How about this one then: ['','double ','triple '][n] to ' eellpbiurotd'[-n:0:-2] for 168 bytes: Try it online! \$\endgroup\$
    – Jitse
    Commented Aug 13, 2019 at 9:52
  • \$\begingroup\$ Alternatively, also 168 bytes \$\endgroup\$
    – Jitse
    Commented Aug 13, 2019 at 10:13

Perl 5 -p, 111 bytes

s/(\d)\1/ double$1/g;s/\w+(\d)\1/triple$1/g;s/\d/' '.qw(oh one two three four five six seven eigth nine)[$&]/ge

Try it online!


s/(\d)\1/ double$1/g; # Replace non-overlapping double digits with " double<digit>"
s/\w+(\d)\1/triple$1/g; # Replace remaining double digits preceded by "double" with "triple<digit>"
s/\d/' '.qw(oh one two three four five six seven eigth nine)[$&]/ge # Replace digits with " <word>"
  • 1
    \$\begingroup\$ Shaved a few bytes off: 106 \$\endgroup\$
    – Xcali
    Commented Aug 14, 2019 at 4:43

Scala, 213 bytes

Got it. Somehow the recursive version I was trying to build was strongly more verbose-y than this one (still recursive though, but only in one case). Function f takes as an input string the phone number and outputs its phonetics with a trailing whitespace.

var u="oh one two three four five six seven eight nine" split " "
"(.)\\1*".r.replaceAllIn(s,x=>{var o=x.matched
var k=u(o(0)-48)+" "
o.length match{case 3=>"triple "+k
case 1=>k
case _=>"double "+k+f(o drop 2)}})

Try it online!
Edit : -8b thanks to DrY Wit!

Scala, 215 bytes

And here comes the leading whitespace version, two bytes longer for some reason (even with massive refactoring).

var u="oh one two three four five six seven eight nine" split " "
"(.)\\1*".r.replaceAllIn(s,x=>{var o=x.matched
var k=u(o(0)-48)
" , double , triple ".split(",")(if(o.length>3){k+=f(o drop 2);1}else o.length-1)+k})

Try it online!

  • 2
    \$\begingroup\$ You can save 8 bytes by replacing (o(0)+"").toInt with o(0)-48. \$\endgroup\$
    – Dr Y Wit
    Commented Aug 14, 2019 at 3:40
  • \$\begingroup\$ Oof well done @DrYWit thanks! \$\endgroup\$ Commented Aug 14, 2019 at 6:28

PHP, 174 169 166 159 bytes

for(;$s=strspn($argn,$d=$argn[$i],$i++);$s==3?($i+=2)+print'triple ':$s<2?:++$i+print'double ',print[oh,one,two,three,four,five,six,seven,eight,nine][$d].' ');

Try it online!

For each digit at index of $i starting from 0:

  • If span of the same digit starting from location of $i is equal to 3, prints 'triple ' and adds 2 to $i so next iteration will have 2 digits jumped over.
  • If span of the same digit starting from location of $i is equal to or more than 2 but is not 3, prints 'double ' and adds 1 to $i so next iteration will have 1 digit jumped over.
  • Prints word for the digit and a space.
  • $i++.

Retina 0.8.2, 105 bytes

= =

Try it online! Outputs a leading space. Explanation: I originally tried a regex that automatically matches 2 or 3 digits but @Arnauld's approach of turned out to be golfier. Explanation:


Match pairs of identical digits and replace the first with a =. Then repeat, so that for an odd number the second last digit is also replaced with a =.


Space the digits (and =s) out.

= =

Handle the case of three identical digits.


Replace all remaining characters with words.


Jelly, 59 bytes


Try it online!

A monadic link that takes a string of digit characters as its argument and returns a Jelly string of space-separated words. When called as a full-program, outputs implicitly.


T-SQL 2017, 238 bytes

Added some linebreaks to make it readable

WHILE''<left(@,1)SELECT @=stuff(@,1,iif(p<4,p,2),'')+
iif(p=1,' ',iif(p=3,' triple ',' double '))
+trim(substring('oh  one  two  threefour five six  seveneightnine',left(@,1)*5,5))

Try it online


C++, 382 bytes

It's not superclever, but someone needed to write a C++ version. The recursive function R goes through the input string and counts repeated values. If there are more than 3 repeats, it pretends there were 2 repeats, then rewinds and tries again.

A few more source chars could probably be squeezed out with #define major, but I'm sure a better algo could squeeze out more.

#include <iostream>
#include <sstream>
using namespace std;
void R(ostream& s,const char*r,char p='x',int c=0){if(*r==p)R(s,r+1,p,c+1);else
{if(c>1){if(c>= 4){s<<"double ";r-=(c-2);}else if(c==3)s<< "triple ";else if(c==2)s<< "double ";
}if(c >0)s<<n[p-'0']<<" ";if(!*r)return;R(s,r+1,*r,1);}}

void check(const char* in, const char* out)
    std::stringstream ss;
    if (out == ss.str()) std::cout << "PASS: "; else std::cout << "FAIL! ";
    std::cout << in << "\n< " << out << "\n> " << ss.str() << std::endl;

int main(int c,char**argv)
    if (argv[1] == std::string("test"))
        check("0123"         ,"oh one two three ");
        check("4554554"      ,"four double five four double five four ");
        check("000"          ,"triple oh ");
        check("00000"        ,"double oh triple oh ");
        check("66667888"     ,"double six double six seven triple eight ");
        check("19999999179"  ,"one double nine double nine triple nine one seven nine ");
        char* v = argv[1];
        std::cout << std::endl;

and verification of test cases:

pa-dev01$ ./a.out test
PASS: 0123
< oh one two three
> oh one two three
PASS: 4554554
< four double five four double five four
> four double five four double five four
PASS: 000
< triple oh
> triple oh
PASS: 00000
< double oh triple oh
> double oh triple oh
PASS: 66667888
< double six double six seven triple eight
> double six double six seven triple eight
PASS: 19999999179
< one double nine double nine triple nine one seven nine
> one double nine double nine triple nine one seven nine
  • 1
    \$\begingroup\$ Does the golfed part actually need #include <sstream>? Or could you move that down after the golfed part for the test function? I think typing std::ostream&s would take less space than using namespace std;, unless there are other places where you'd need a std::. \$\endgroup\$ Commented Aug 16, 2019 at 0:35
  • \$\begingroup\$ 253 bytes \$\endgroup\$
    – ceilingcat
    Commented Sep 6, 2019 at 22:35

Perl 6, 96 93 bytes

{S:g/(.)$0?[$0{}<!$0>]?/{(<triple double>X$)[3-$/.comb]}{+$/??uniname(~$0).words[1]!!'oh'} /}

Try it online!

This is an anonymous code block that takes a number and returns a string with the numbers in uppercase, e.g. 0123 => oh ONE TWO THREE with a single trailing space.

This was deleted for a while until I found out how to use captures in a lookahead, but it should be fixed now.


Red, 242 bytes

func[s][b:[copy t skip t]parse s[any[change[b t ahead not t](rejoin["triple "t])|
change b(rejoin["double "t])| skip]]foreach c s[prin either i:
find"0123456789"c[rejoin[pick[:oh:one:two:three:four:five:six:seven:eight:nine]index? i" "]][c]]]

Try it online!


Scala, 253 bytes

def g(s:String):String={val t="oh one two three four five six seven eight nine".split(" ")(s(0)-48)
s.length match{case 3=>"triple "+t;case 2=>"double "+t;case 1=>t;case _=>"double "+t+" "+g(s drop 2)}}
s=>"(.)\\1*".r.findAllIn(s).map(g(_)) mkString " "

Try it online!


Oracle SQL, 578 bytes (in formatted form)

Solution is not concise by any means so posting it in formatted way.

with r(s) as
(select x from t
  union all
 select case
           when length(regexp_substr(s, '(.)(\1)+')) = 3 
           then regexp_replace(s, '^...')
           else regexp_replace(s, '^(.)\1|^.')
   from r
  where s is not null)
select listagg(decode(length(r),  2, 'double ',  3, 'triple ') ||
               decode(substr(r, 1, 1), 0, 'oh', to_char(to_date(substr(r, 1, 1), 'j'), 'jsp')), ' ')
               within group (order by rownum)
  from (select regexp_replace(s, lag(s) over (order by length(s)) || '$') r
          from r order by length(s) desc);

Test in SQL*Plus

SQL> create table t(x) as select /*'45547777777774'*/ '1999999910079' from dual;

Table created.

SQL> set pages 0
SQL> with r(s) as
  2  (select x from t
  3    union all
  4   select case
  5             when length(regexp_substr(s, '(.)(\1)+')) = 3
  6             then regexp_replace(s, '^...')
  7             else regexp_replace(s, '^(.)\1|^.')
  8          end
  9     from r
 10    where s is not null)
 11  select listagg(decode(length(r),  2, 'double ',  3, 'triple ') ||
 12                 decode(substr(r, 1, 1), 0, 'oh', to_char(to_date(substr(r, 1, 1), 'j'), 'jsp')), ' ')
 13                 within group (order by rownum)
 14    from (select regexp_replace(s, lag(s) over (order by length(s)) || '$') r
 15            from r order by length(s) desc);
one double nine double nine triple nine one double oh seven nine

The main trick is that digits converted into words using Oracle format models instead of hard-coded literals "one" ... "nine".

  • \$\begingroup\$ any chance of this getting golfed ? it seems you can remove a bunch of spaces. I also imagine you can rewrite WHERE s is not null to WHERE s>'' \$\endgroup\$ Commented Aug 14, 2019 at 14:04
  • 1
    \$\begingroup\$ You can save a few characters by replacing what’s after union all with select regexp_replace(s,case when length(regexp_substr(s, '(.)(\1)+')) = 3 then '^...' else '^(.)\1|^.' end) from r. \$\endgroup\$
    – Steve Kass
    Commented Aug 15, 2019 at 16:41

JavaScript, 142 bytes

s=>s.replace(/(.)(\1\1(?!\1)|\1|)/g,t=>(t[2]?' triple ':t[1]?' double ':' ')+'oh one two three four five six seven eight nine'.split` `[t[0]])

Try it online!


(Roblox) Lua 5.1, 166 bytes

for I,N in('111 triple 11 double 1 '):gmatch'(%d+)(%D+)'do for i,n in('0oh1one2two3three4four5five6six7seven8eight9nine'):gmatch'(.)(%l+)'do s=s:gsub(i*I,N..n)end end

Ensure s is a predefined string value populated only with digits; that will be the variable to be modified. The result will include a leading space [\u20] character.

  • \$\begingroup\$ Welcome to the site! As Lua can take input via standard methods, it's against the rules to require s to already have the input. Aside from that, you've got a good first post! I would recommend you include a link to an online testing site e.g. tio.run/#lua so that others can test your solution \$\endgroup\$ Commented Aug 13, 2019 at 9:30
  • \$\begingroup\$ Hi. The variant of Lua I was testing on (Rbx.Lua) doesn't contain input methods, although the sandbox has print, warn, and error output methods. \$\endgroup\$ Commented Aug 14, 2019 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.