26
\$\begingroup\$

Convert a string containing digits as words into an integer, ignoring leading zeros.

Examples

  • "four two" -> 42.
  • "zero zero zero one" -> 1.

Assumptions

Submissions can assume that:

  1. The input string is comprised of space-separated digit words.
  2. All words are valid (in the range "zero".."nine") and lowercase. Behaviour for empty input is undefined.
  3. The input string always represents an unsigned number within the range of int and is never an empty string.

Scoring

Answers will be scored in bytes with fewer bytes being better.

\$\endgroup\$
13
  • 3
    \$\begingroup\$ Welcome to the site. There are a couple of things that we usually expect from questions that are missing here. The most important would be an objective scoring criterion which all challenges must have. \$\endgroup\$ – Wheat Wizard Sep 22 '19 at 21:06
  • 3
    \$\begingroup\$ Aside from that this question is very sparse on specification. You should specify exactly what is required of submissions without ambiguity. One sentence and an example just isn't up to our clarity standards for challenges. \$\endgroup\$ – Wheat Wizard Sep 22 '19 at 21:08
  • 3
    \$\begingroup\$ On top of what has been said already, we have a sandbox where users can post their challenges before posting them to main. That way you will miss less information when making posts. If you look at other recent posts on the site with a reasonably positive reception I think you will see that both your question and solution aren't quite in line with what we do here. \$\endgroup\$ – FryAmTheEggman Sep 22 '19 at 21:13
  • 3
    \$\begingroup\$ At the risk of being pedantic, I'd like to point out that the range "zero".."nine" is not fully specified. \$\endgroup\$ – Unrelated String Sep 22 '19 at 21:22
  • 4
    \$\begingroup\$ Annoyingly, the builtin Interpreter@"SemanticNumber" does exactly this in Mathematica—except that it fails on strings starting with zero zero . \$\endgroup\$ – Greg Martin Sep 23 '19 at 5:45

36 Answers 36

24
\$\begingroup\$

PHP, 74 bytes

foreach(explode(' ',$argn)as$w)$n.='793251_8640'[crc32($w)%20%11];echo+$n;

Try it online!

Tried to get a solution which doesn't copy existing answers. I get cyclic redundancy checksum polynomial of 32-bit lengths (crc32) for each word and then do a mod 20 and mod 11 on it to get mixed up unique values from 0 to 10 (missing 6) for each digit. Then using that unique value I find the actual digit.

| Word  | CRC32      | %20 | %11 | Equivalent digit |
|-------|------------|-----|-----|------------------|
| zero  | 2883514770 | 10  | 10  | 0                |
| one   | 2053932785 | 5   | 5   | 1                |
| two   | 298486374  | 14  | 3   | 2                |
| three | 1187371253 | 13  | 2   | 3                |
| four  | 2428593789 | 9   | 9   | 4                |
| five  | 1018350795 | 15  | 4   | 5                |
| six   | 1125590779 | 19  | 8   | 6                |
| seven | 2522131820 | 0   | 0   | 7                |
| eight | 1711947398 | 18  | 7   | 8                |
| nine  | 2065529981 | 1   | 1   | 9                |

Another 74 bytes CRC32 alternative using %493%10: Try it online!

Another 74 bytes CRC32 alternative using %2326%11: Try it online!


PHP, 74 bytes

foreach(explode(' ',$argn)as$w)$n.=strpos(d07bfe386c,md5($w)[21]);echo+$n;

Try it online!

Another alternative with same length, takes 22nd character in the md5 of the word (only character which gives a unique value for each word) and then uses that character to map to a digit.

\$\endgroup\$
1
10
\$\begingroup\$

Python 2,  71  70 bytes

-1 thanks to ovs (use find in place of index)

lambda s:int(''.join(`'rothuvsein'.find((w*3)[6])`for w in s.split()))

Try it online!

\$\endgroup\$
0
7
\$\begingroup\$

JavaScript (ES6),  70 67 66  62 bytes

Saved 3 bytes thanks to @ovs

s=>+s.replace(/\w+ ?/g,s=>'2839016547'[parseInt(s,36)%204%13])

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ '2839016547'[parseInt(s,36)%204%13] is 3 bytes shorter. \$\endgroup\$ – ovs Sep 22 '19 at 22:06
6
\$\begingroup\$

Jelly,  19  17 bytes

Ḳµ7ị“*;nÄƲ]³Ṙ»i)Ḍ

A monadic Link accepting a list of characters which yields an integer.

Try it online!

Pretty much a port of my Python 2 answer.


Previous

ḲŒ¿€i@€“©¥q£½¤MÆÑ‘Ḍ

Try it online!

There is quite possibly a shorter way, but this is a way that first came to mind.

\$\endgroup\$
2
  • \$\begingroup\$ Removing zero from the enklact string to avoid decrementing, because not found is zero anyhow... clever! \$\endgroup\$ – Unrelated String Sep 22 '19 at 22:01
  • 1
    \$\begingroup\$ Ah I see you did the same method, nice. \$\endgroup\$ – Jonathan Allan Sep 22 '19 at 22:16
5
\$\begingroup\$

Perl 6, 35 32 bytes

{+uniparse 'SP'~S:g/<</,DIGIT /}

Try it online!

Explanation

{                              }  # Anonymous block
                S:g/<</,DIGIT /   # Insert ",DIGIT " at
                                  # left word boundaries
           'SP'~  # Prepend 'SP' for space
  uniparse  # Parse list of Unicode names into string
 +  # Convert to integer
\$\endgroup\$
5
\$\begingroup\$

05AB1E, 18 16 bytes

#ε6è}.•ƒ/ÿßÇf•Åβ

Try it online.

Explanation:

#                 # Split the (implicit) input-string on spaces
 ε  }             # Map each string to:
  6è              #  Get the character at 0-based index 6 (with automatic wraparound)
     .•ƒ/ÿßÇf•    # Push compressed string "rothuvsein"
              Åβ  # Convert the characters from custom base-"rothuvsein" to an integer
                  # (after which the top of the stack is output implicitly as result)

See this 05AB1E tip of mine (section How to compress strings not part of the dictionary?) to understand why .•ƒ/ÿßÇf• is "rothuvsein".

\$\endgroup\$
1
5
\$\begingroup\$

C (gcc), 89 bytes

i,n;f(char*w){for(i=n=0;n=*w%32?n^*w:(i+=n-2)&&!printf(L"8 0  72 3  59641"+n%17),*w++;);}

Try it online!

Thanks to @Ceilingcat smartest tricks :

- printf instead of putchar.   
- !printf instead of printf()&0. 
- And wide char !
\$\endgroup\$
0
5
\$\begingroup\$

Python 3, 107, 91, 77, 90, 74 bytes

-16 bytes by Sriotchilism O'Zaic

+13 bytes to remove leading zeroes

-16 bytes using find and a more clever indexing, but now it's basically a rip-off of the Python 2 version...

lambda s:int(''.join(str('rothuvsein'.find((w*3)[6]))for w in s.split()))

Try it online!

\$\endgroup\$
9
  • 5
    \$\begingroup\$ It's shorter if you just use the first two characters \$\endgroup\$ – Wheat Wizard Sep 22 '19 at 21:19
  • \$\begingroup\$ Nice one! That way, I can even drop the delimiter completely :) \$\endgroup\$ – movatica Sep 22 '19 at 21:23
  • 1
    \$\begingroup\$ With the updates to the challenge this is no longer valid since it includes leading zeros. :( \$\endgroup\$ – Wheat Wizard Sep 22 '19 at 21:25
  • 2
    \$\begingroup\$ Here is a slightly better fix \$\endgroup\$ – Wheat Wizard Sep 22 '19 at 21:34
  • 1
    \$\begingroup\$ @movatica Your fix is incorrect. The lstrip method strips every character in the string which is given as it's argument, so "eight two" becomes "ight two", as "e" gets stripped. Also, "zero zero zero" should print out "0", not give out an error. \$\endgroup\$ – NemPlayer Sep 22 '19 at 21:36
4
\$\begingroup\$

05AB1E, 17 16 bytes

•D±¾©xWÄ0•I#HèTβ

Try it online!

Perfect tie with the other 05AB1E answer, but using a completely different approach.

•D±¾©xWÄ0•               # compressed integer 960027003010580400
          I#             # split the input on spaces
            H            # convert each word from hex (eg "one" => 6526)
             è           # index (with wrap-around) into the digits of the large integer
              Tβ         # convert from base 10 to integer
\$\endgroup\$
3
\$\begingroup\$

Retina 0.8.2, 46 45 bytes

\w+
¶$&$&$&
%7=T`r\ot\huvs\ein`d`.
\D

^0+\B

Try it online! Link includes test cases. Explanation:

\w+
¶$&$&$&

Put each word on its own line and triplicate it.

%7=T`r\ot\huvs\ein`d`.

Transliterate the 7th character of each line using @UnrelatedString's string.

\D

Delete all remaining non-digit characters.

^0+\B

Delete leading zeros (but leave at least one digit).

Previous 46-byte more traditional solution:

T`z\wuxg`E
on
1
th
3
fi
5
se
7
ni
9
\D

^0+\B

Try it online! Link includes test cases. Explanation:

T`z\wuxg`E

The words zero, two, four, six and eight uniquely contain the letters zwuxg. Transliterate those to the even digits.

on
1
th
3
fi
5
se
7
ni
9

For the odd digits, just match the first two letters of each word individually.

\D

Delete all remaining non-digit characters.

^0+\B

Delete leading zeros (but leave at least one digit).

\$\endgroup\$
3
\$\begingroup\$

x86 machine code, 46 bytes

Hexdump:

57 53 33 c0 33 ff f6 01 0f 75 15 6a 0a 5b 99 f7
f3 6b ff 0a 03 fa 33 c0 38 01 75 0f 97 5b 5f c3
69 c0 26 2b aa 6e 32 01 c1 e8 02 41 eb d8

It's a fastcall function - receives a pointer to the string in ecx, and returns the result in eax.

The hashing function multiplies by a magic number 1856645926, does a XOR with input byte, and shifts right by 2 bits.

Saving and restoring noclobber registers (edi and ebx) took 4 bytes, but I didn't find a more efficient way to implement this. Storing the constant 10 in ebx was particularly annoying!

Disassembly with corresponding code bytes:

57                   push        edi  ; edi = result
53                   push        ebx  ; we use ebx to store the constant 10
33 C0                xor         eax,eax  
33 FF                xor         edi,edi  
    myloop:
F6 01 0F             test        byte ptr [ecx],0Fh  ; check for end of word
75 15                jne         myhash
6A 0A                push        0Ah  
5B                   pop         ebx  
99                   cdq              ; prepare 64-bit dividend in edx:eax
F7 F3                div         eax,ebx  ; find the remainder of division by 10
6B FF 0A             imul        edi,edi,0Ah
03 FA                add         edi,edx  ; update the result
33 C0                xor         eax,eax  ; reset the hash temporary variable
38 01                cmp         byte ptr [ecx],al  ; check for end of input (here al=0)
75 0F                jne         mycontinue
97                   xchg        eax,edi  ; set the return register
5B                   pop         ebx  ; restore registers
5F                   pop         edi  ; restore registers
C3                   ret  
    myhash:
69 C0 26 2B AA 6E    imul        eax,eax,6EAA2B26h  ; hashing...
32 01                xor         al,byte ptr [ecx]  ; hashing...
C1 E8 02             shr         eax,2  ; hashing...
    mycontinue:
41                   inc         ecx  ; next input byte
EB D8                jmp         myloop

Equivalent C code:

int doit(const char* s)
{
    int result = 0;
    unsigned temp = 0;
    while (true)
    {
        int c = *s++;
        if ((c & 15) == 0)
        {
            temp %= 10;
            result = result * 10 + temp;
            temp = 0;
            if (c == 0)
                break;
            else
                continue;
        }
        temp *= 1856645926;
        temp ^= c;
        temp >>= 2;
    }
    return result;
}
\$\endgroup\$
3
  • \$\begingroup\$ How did you find the magic numbers? \$\endgroup\$ – Sparkler Sep 25 '19 at 1:22
  • \$\begingroup\$ I did a search using my C code - tried all 32-bit numbers and all shifts. There are only a few possibilities - the code found only one in the range up to 2000000000. \$\endgroup\$ – anatolyg Sep 25 '19 at 9:39
  • \$\begingroup\$ you can use edx instead of edi (push edx before the idiv, pop eax after it, imul with ebx, add eax to edx) to save one byte. \$\endgroup\$ – peter ferrie Sep 28 '19 at 6:42
3
\$\begingroup\$

ARM Thumb-2 (manual rothuvsein, no div, no libc) 70 bytes

Machine code:

b5f0 2100 2420 f000 f816 0032 18c5 3b03
bf18 f1c3 0303 5cc4 a004 f000 f80c 240a
fb01 3104 1c68 2a00 d1ec bdf0 6f72 6874
7675 6573 6e69 f07f 0300 1c5b 5cc6 b10e
42a6 d1fa 4770

Assembly:

        .syntax unified
        .arch armv6t2
        .thumb
        .globl _strtoint
        .thumb_func
_strtoint:
        push    {r4-r7, lr}
        movs    r1, #0
.Lstrtoint_loop:
        movs    r4, #' '
        bl      _strfind
        movs    r2, r6
        adds    r5, r0, r3
        subs    r3, #3
        it      ne
        rsbne   r3, #3
        ldrb    r4, [r0, r3]
        adr     r0, .Lrothuvsein
        bl      _strfind
        movs    r4, #10
        mla     r1, r1, r4, r3
        adds    r0, r5, #1
        cmp     r2, #0
        bne     .Lstrtoint_loop
.Lstrtoint_loop_end:
        pop     {r4-r7, pc}

        @ naturally 4-byte aligned
        @ note: this is not null terminated - we blindly assume a match
.Lrothuvsein:
        .ascii "rothuvsein"
        @ naturally 2-byte aligned
        .thumb_func
_strfind:
        movs    r3, #-1
.Lstrfind_loop:
        adds    r3, r3, #1
        ldrb    r6, [r0, r3]
        cbz     r6, .Lstrfind_loop_end
        cmp     r6, r4
        bne     .Lstrfind_loop
.Lstrfind_loop_end:
        bx      lr

Explanation

Yet another port of the rothuvsein method, but this seems to be the first one in assembly. It is also done manually without the support of libc or fancy useless CISC instructions like repne scasb. Just plain, barebones RISC. That means that it is longer than other assembly languages.

Unlike my previous entries, I am a little more flexible with the calling convention.

While the input string (null terminated) is in r0 just like it would be in C, the output is a 32-bit integer in r1 instead of the traditional r0.

It can still be wrapped in C like so, since r1 is still used for 64-bit integers:

extern uint64_t _strtoint(const char *str);
uint32_t strtoint(const char *str)
{
    return (uint32_t)(_strtoint(str) >> 32);
}

Regardless of whether I care about the calling convention, I am going to have to do something with the link register so I can call my subroutine, so might as well push the callee-saved registers and remain mostly in line with the calling convention.

        .globl _strtoint
        .thumb_func
_strtoint:
        push    {r4-r7, lr}

Initialize our accumulator/output variable to 0.

        movs    r1, #0

Call our internal subroutine to find the end of the word.

r3 will have the length of the word, and r6 will have the last byte read. I will explain _strfind later.

.Lstrtoint_loop:
        movs    r4, #' '
        bl      _strfind

We save a copy of the last byte read for later to tell if we reached the null terminator.

        movs    r2, r6

Put the pointer to the string (advanced to the space) in r5.

        adds    r5, r0, r3

Here is the trickiest part: One does not simply str+str+str in assembly. We need to find the index.

Specifically, if we plot it out:

oneoneone
      ^
fourfourfour
      ^
sevensevenseven
      ^

We can turn it into this:

switch (strlen(str)) {
case 3: return str[0];
case 4: return str[2];
case 5: return str[1];
}

It can be done as 6 % strlen(str), but that is division. I can do better.

I could do a lookup table, but there is a better solution than that:

Remember that r3 is essentially strlen(str).

We can do this:

        subs    r3, #3
        it      ne
        rsbne   r3, #3 @ note: rsb = Reverse SuBtract

The equivalent C:

if ((len -= 3) != 0)
{
    len = 3 - len;
}

This works perfectly:

3 - 3       = 0
3 - (4 - 3) = 2
3 - (5 - 3) = 1

Now, we load the byte from the string at our offset...

        ldrb    r4, [r0, r3]

...then call _strfind with the rothuvsein lookup table to find it.

        adr     r0, .Lrothuvsein
        bl      _strfind

Now, we add the length to our accumulator times 10;

        movs    r4, #10
        mla     r1, r1, r4, r3 @ r1 = r1 * 10 + len

Take the copy of the string we made in r5, advance it past the space, and put it in r0 for the next iteration.

        adds    r0, r5, #1

Then, loop if we are not at a null terminator:

        cmp     r2, #0
        bne     .Lstrtoint_loop

Finally, return in r1 by popping the link register holding the return address into the program counter (along with restoring the other registers I saved).

.Lstrtoint_loop_end:
        pop     {r4-r7, pc}
_strfind subroutine

_strfind is the real workhorse here.

C users will find it similar to strcspn or strchr.

It is called with the null terminated string to search in r0 and the byte to find in r4.

It will return the index of the match (or null terminator) in r3 and the last byte read in r6.

First, initialize our counter at -1.

_strfind:
        movs    r3, #-1

On each iteration, increment the counter..

.Lstrfind_loop:
        adds    r3, r3, #1

Then, load str[counter] into r6

        ldrb    r6, [r0, r3]

Then loop unless r6 is \0 or if it matches r4.

        cbz     r6, .Lstrfind_loop_end
        cmp     r6, r4
        bne     .Lstrfind_loop

When we find it, return back to _strtoint.

.Lstrfind_loop_end:
        bx      lr
\$\endgroup\$
2
\$\begingroup\$

C++ (gcc), 478 218 142 bytes

-(a lot) thanks to Jo King

int f(string s){char c[]="N02K8>IE;6";int i=0,n=0;while(s[i]){n=n*10-1;while((s[i]^s[i+1])+47!=c[++n%10]);while(s[i++]!=' '&&s[i]);}return n;}

Try it online!

\$\endgroup\$
1
2
\$\begingroup\$

Japt, 13 bytes

¸mg6 ì`Ψuv 

Try it

Looks like everyone else beat me to the same idea - could've saved myself the hassle of writing a script to brute force the optimal string for compression, only to find that, up to index 1,000,000 (it was early, I hadn't had my caffeine yet!), "rothuvsein" is the only possible string!

¸mg6 ì`...     :Implicit input of string
¸              :Split on spaces
 m             :Map
  g6           :  Character at index 6 (0-based, with wrapping)
     ì         :Convert from digit array in base
      `...     :  Compressed string "rothuvsein"

The compressed string contains the characters at codepoints 206, 168, 117, 118, 160 & 136.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ ...did you really try up to 1000000? The lcm of the lengths of the digit names is 60, so there's no point trying beyond that (60 is equivalent to 0, 61 to 1, etc). \$\endgroup\$ – Grimmy Sep 23 '19 at 13:08
  • 1
    \$\begingroup\$ @Grimy, it was early, I hadn't had my caffeine yet! Plugging a million into the script I wrote to generate all possibilities was as easy as any other number and saved me doing the maths on the LCM. \$\endgroup\$ – Shaggy Sep 23 '19 at 13:22
2
\$\begingroup\$

Ruby, 63 bytes, 52 bytes, 50 bytes

p $*.map{|d|'rothuvsein'.index (d*3)[6]}.join.to_i

-2 thanks to value ink's tip

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! In Ruby, $* is an alias for ARGV, so feel free to use that to save extra bytes. \$\endgroup\$ – Value Ink Sep 23 '19 at 21:11
2
\$\begingroup\$

T-SQL, 110 bytes

SELECT 0+STRING_AGG(CHARINDEX(LEFT(value,2),'_ontwthfofisiseeini')/2,'')
FROM STRING_SPLIT((SELECT*FROM i),' ')

Line break is for readability only.

Input is taken via table \$i\$, per our IO rules. I could have saved 14 bytes by pre-populating a string variable, but that's only allowed if the language has no other input methods.

Explanation:

  1. STRING_SPLIT takes the input string and separates it at the spaces
  2. CHARINDEX takes the first 2 characters and returns the (1-based) position in the string '_ontwthfofisiseeini'. 'ze' for zero is not in the string and returns 0 for "not found". The underscore ensures we only get multiples of two.
  3. Divide by 2 to get the final numeral
  4. STRING_AGG smashes the digits back together with no separator
  5. 0+ forces an implicit conversion to INT and drops any leading zeros. 1* would also work.
\$\endgroup\$
2
\$\begingroup\$

Kotlin, 83 bytes

fun String.d()=split(' ').fold(""){a,b->a+"rothuvsein".indexOf((b+b+b)[6])}.toInt()

+1 byte if you wanna support longs with toLong()

Same rothuvsein trick as the others, saving some precious bytes thanks to kotlin's nice toInt() and fold(). I just can't shake the feeling that some more bytes can be shaved off though...

\$\endgroup\$
2
\$\begingroup\$

Python 3, 85 bytes

I put two versions of my explanation just for fun :)

Split the input i into words and loop over it using list comprehension. For all the words find the location of the first 2 letters in a lookup table ("zeontwthfofisiseeini"), making sure to divide by two - with // for floor division, finally use "".join( to combine into a string and int( to convert to integer and remove leading zero(s).

lambda i:int("".join([str("zeontwthfofisiseeini".find(x[:2])//2)for x in i.split()]))

Try it online!

  • lambda i: lambda function instead of using a def function
  • [for x in] use list comprehension to check through the input
  • i.split split the input at spaces (default delimiter)
  • "zeontwthfofisiseeini".find(x[:2]) find the location of the first two characters of x in a lookup list
  • //2 floor divide output of .find because it's checking the first 2 chars
  • str() convert position to string
  • "".join() combine output of list comprehension to a string
  • int() convert string to int and remove leading zero(s)

Also, this is accidentally similar to this answer but I made mine before looking at the other answers.

\$\endgroup\$
2
\$\begingroup\$

Jelly, 20 18 17 16 bytes

Ḳ7ị“"c tẠ;Ḅ»iƲ€Ḍ

Try it online!

-2 bytes from running "rothuvsein" through user202729's string compressor.

-1 byte from stealing Jonathan Allan's zero-free enklact string, and putting it in a marginally differently structured program.

-1 byte because I actually kind of understand Jelly's dictionary-based string compression now

Ḳ                   Split the input on spaces,
             Ʋ€     for each word
            i       find the first 1-based index (defaulting to 0)
   “"c tẠ;Ḅ»        in "othuvseine"
 7ị                 of the element at modular index 7,
               Ḍ    and convert from decimal digits to integer.

I must admit, I'm disappointed I couldn't get a length reduction from othuvseinfeld.

\$\endgroup\$
0
1
\$\begingroup\$

Perl 6, 45 bytes

+*.words>>.&{+(1...*.uniname.comb(.uc))}.chrs

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Clean, 88 bytes

import StdEnv,Text
$s=toInt{#i\\n<-split" "s,c<-:"rothuvsein"&i<-['0'..]|c==(n+n+n).[6]}

Try it online!

Heavily based on Jonathan Allan's answer.
Uses a comprehension for indexing instead of indexOf / elemIndex.

\$\endgroup\$
1
\$\begingroup\$

J, 38 bytes

('b\e~mjPxw['i.[:u:70+1#.15|3&u:)&>@;:

Try it online!

\$\endgroup\$
1
\$\begingroup\$

VBA, 160 bytes

Function e(s)
s = Split(s, " ")
For i = LBound(s) To UBound(s)
s(i) = Int((InStr("ontwthfofisiseeini", Left(s(i), 2)) + 1) / 2)
Next
e = Val(Join(s, ""))
End Function

Matches the first two characters in a string, zero excluded.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ (1/3) Great approach here, but it looks like you failed to count the newlines as bytes, and that you can get the bytecount way down if you use some tricks. Namely, there is no need to decaler the " " in the Split as that is the default value, Lbound(s) will always be zero and you can drop (...)+1 if you add a space to the beginning of the InStr data. Asside from that, you are better off using either a string or variant to handle holding the data coming out of the InStr statement as you dont need to use (i) or Join(s,""). Oh and Int(a/b) is the same as a\b. \$\endgroup\$ – Taylor Scott Jan 3 '20 at 12:49
  • 1
    \$\begingroup\$ (2/3) Using these, and a for each loop you can get your function down to 101 bytes as Function G(x):For Each c In Split(x):G=10*G+InStr(" ontwthfofisiseeini",Left(c,2))\2:Next:End Function or 101 bytes as a sub thet implicitly prints the output to the debug window as Sub F(x):For Each c In Split(x):v=10*v+InStr(" ontwthfofisiseeini",Left(c,2))\2:Next:Debug.?v:End Sub. If you restrict your answer you can even get it to 81 bytes as a Excel VBA immediate window function as For Each c In Split([A1]):v=10*v+InStr(" ontwthfofisiseeini",Left(c,2))\2:Next:?v. \$\endgroup\$ – Taylor Scott Jan 3 '20 at 12:50
  • 1
    \$\begingroup\$ (3/3) I highly recommend that you go take a look at our Tips for golfing in VBA Page for more info on these approaches. Cheers \$\endgroup\$ – Taylor Scott Jan 3 '20 at 12:50
1
\$\begingroup\$

Charcoal, 19 bytes

I⍘⭆⪪S §ι⁶rothuvsein

Try it online! Link is to verbose version of code. Port of @KevinCruijssen's 05AB1E answer. Explanation:

    S               Input string
   ⪪                Split on spaces
  ⭆                 Map over words and join
       ι            Current word
      §             Cyclically indexed
        ⁶           Literal `6`
 ⍘       rothuvsein Custom base conversion
I                   Cast to string for implicit print
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 48 bytes

+-join($args|%{'rothuvsein'.indexof(($_*3)[6])})

Try it online!

Uses the same rothuvsein trick as others, thanks to Jonathan Allan. Expects input arguments via splatting, which on TIO manifests as separate command-line arguments.

\$\endgroup\$
1
\$\begingroup\$

sed -re, 78 bytes

s/three/3/g;s/five/5/g;s/\w\w(\w)\w*/\1/g;s/ //g;y/eouxvgnr/12467890/;s/^0*//
\$\endgroup\$
1
\$\begingroup\$

Windows Batch, 169 bytes

@setlocal enabledelayedexpansion
@set z=zeontwthfofisiseeini
:a
@set b=%1
@for /l %%c in (0,2,18)do @if "!b:~0,2!"=="!z:~%%c,2!" set/aa=a*10+%%c/2&shift&goto a
@echo %a%
\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), 27 bytes

10/"rothuvsein"?(*|7#)'" "\

Try it online!

Another port of Kevin Cruijssen's 05AB1E answer.

  • " "\ split input on spaces
  • (*|7#)' take the last character of each word (repeated to be of length seven)
  • "rothuvsein"? find index of character in "rothuvsein" (i.e. the seventh character of "zero" repeated is "r", which is at index 0)
  • 10/ convert from a list of digits to a decimal number
\$\endgroup\$
1
\$\begingroup\$

Scala, 66 64 62 bytes

_.split(" ").map("rothuvsein"indexOf _.*(3)(6)).mkString.toInt

Try it online! This is the "rothuvsein" approach in Scala. The 7th character of each (repeated) number string is extracted via (numberString*3)(6). The position of this character in "rothuvsein" is then used as the correct numerical digit. The toInt conversion does the rest (e.g., dealing with leading zeros).

2 times 2 bytes saved thanks to @user by

  1. an even more abused use of syntactic sugar :)
  2. simply using toInt conversion rather than BigInt constructor
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice answer! You can get 64 bytes with an underscore and more infix syntax. \$\endgroup\$ – user Dec 28 '20 at 21:52
  • 1
    \$\begingroup\$ Make that 62 if you use toInt instead of BigInt. \$\endgroup\$ – user Dec 28 '20 at 21:57
1
+100
\$\begingroup\$

APL (Dyalog Extended), 26 bytes

10⊥'rothuvsein'⍳7⊢/⍤⍴¨≠⍛⊆⍨

Try it online!

A simple function which checks the first two letters of each word.

-30 bytes from Adám using Kevin Cruijssen's idea.

Explanation(old)

     {⍕2÷⍨1-⍨(2↑⍵)(⍸⍷)'zeontwthfofisiseeinite'} inner fn: 
             (2↑⍵)                              take first two letters
                  (⍸⍷)'zeontwthfofisiseeinite'} find index of the letters in hardcoded string
       2÷⍨1-⍨                                   subtract 1, divide by 2
      ⍕                                         stringify
{⍎⊃,/{⍕2÷⍨1-⍨(2↑⍵)(⍸⍷)'zeontwthfofisiseeinite'}¨' '(≠⊆⊢)⍵} ⍵ → input
                                                ' '(≠⊆⊢)⍵  split input on spaces
   ,/                                                      join output of inner fn
 ⍎⊃                                                        execute it
\$\endgroup\$
2
  • \$\begingroup\$ 42 \$\endgroup\$ – Adám Dec 28 '20 at 10:34
  • \$\begingroup\$ 26 using this algorithm. \$\endgroup\$ – Adám Dec 28 '20 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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