41
\$\begingroup\$

You will be given a string. It will contain 9 unique integers from 0-9. You must return the missing integer. The string will look like this:

123456789
 > 0

134567890
 > 2

867953120
 > 4
\$\endgroup\$
9
  • 5
    \$\begingroup\$ @riker That seems to be about finding a number missing in a sequence. This seems to be about finding a digit missing from a set. \$\endgroup\$
    – DJMcMayhem
    Mar 27, 2017 at 19:48
  • 12
    \$\begingroup\$ @Riker I wouldn't think it's a duplicate, given that the linked challenge has a strictly incrementing sequence (of potentially multi-digit numbers), whereas here it's in arbitrary order. \$\endgroup\$ Mar 27, 2017 at 19:50
  • 3
    \$\begingroup\$ Hi Josh! Since no one else has mentioned it so far, I'll direct you to the Sandbox where you can post future challenge ideas and get meaningful feedback before posting to main. That would have helped iron out any details (like STDIN/STDOUT) and resolved the duplicate dilemma before you received downvotes here. \$\endgroup\$ Mar 27, 2017 at 20:23
  • 1
    \$\begingroup\$ It's such a shame that 9-x%9 works for any digit except 0. Maybe someone more clever than me will find a way to make it work. \$\endgroup\$
    – Bijan
    Mar 28, 2017 at 0:45
  • 3
    \$\begingroup\$ Several answers take an integer as function input. Is that allowed? \$\endgroup\$
    – Dennis
    Mar 28, 2017 at 0:52

91 Answers 91

1
\$\begingroup\$

TI BASIC, 23 bytes

45-sum(seq(expr(sub(Ans,I,1)),I,1,9

Turns the input string in Ans into a list containg the digits and then sums the list so that the number can be derived from subtracting the sum from 45. The byte count is affected by the 2 byte tokens expr(, sub(, and Str1. A full program could prompt for Str1 for 5 additional bytes.

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

BRASCA, 16 bytes

477SSm8[a+A{]x-n

Try it online!

Explanation

<implicit input>     - Push STDIN to stack
477SSm               - Push 477 (the sum of all digits' ASCII codes) to the bottom
      8[    ]        - Loop 9 times:
        a+A          -   Put loop counter in register, add the top two digits, then take it back out.
           {         -   Decrement the loop counter
             x-      - Remove the loop counter, then subtract the sum of all digits from 477
               n     - Output the result as a number
\$\endgroup\$
1
\$\begingroup\$

AWK, 18 bytes

{$0=/0/?9-$0%9:0}1

AWK live editor

Explanation: If 0 exists in the input, return 9 - modulo 9 of the input, otherwise return 0. Implicit print.

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

Pxem, Filename: 28 bytes + Content: 0 bytes = 28 bytes.

  • Filename (Unprintables are escaped): \011.t.w0.i.-.+.m\001.-.c.t.a\055.-.n
  • Content: empty.

Try it online! (with pxem.posixism)

With comments

XX.z
# push 9; heap=pop
.a\011.tXX.z
# while empty || pop!=0; do
.a.wXX.z
  # push 48; push getchar
  .a0.iXX.z
  # push abs(pop-pop); if size>=2; then push pop+pop; fi
  .a.-.+XX.z
  # push heap; push 1; push abs(pop-pop)
  .a.m\001.-XX.z
  # dup; heap=pop
  .a.c.tXX.z
# done
.a.aXX.z
# push 48; push abs(pop-pop); printf "%d", pop
.a\055.-.n
\$\endgroup\$
1
\$\begingroup\$

CSASM v2.3, 129 bytes

func main:
lda 0
sta $1
in ""
conv ~arr:char
pop $a
push "0123456789"
.lbl a
push $a
ldelem $1
sub
inc $1
push $1
push 9
sub
brtrue a
print
ret
end

Commented and ungolfed:

func main:
    ; Initialize $1 to 0
    lda 0
    sta $1

    ; Get the input, convert it to an array of <char>s, then store it in $a
    in ""
    conv ~arr:char
    pop $a

    push "0123456789"
    .lbl loop
        ; Get the <char> in $a at index $1
        push $a
        ldelem $1

        ; Remove it from the <str> currently on the stack and push the updated <str>
        sub

        ; Increment $1 and stop looping if $1 == 9
        inc $1
        push $1
        push 9
        sub
        brtrue loop

    ; The string will now only contain the remaining digit.  Print it
    print
    ret
end
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 4 bytes

žhsм

Try it online!

žhsм  # full program
   м  # remove all characters of...
  s   # implicit input...
   м  # from...
žh    # "0123456789"
      # implicit output

s can also be I or ¹ and h can be m with no change in functionality.

\$\endgroup\$
2
  • \$\begingroup\$ The APL answer wasn't #1... Dennis' jelly answer was \$\endgroup\$
    – lyxal
    Jun 22, 2021 at 10:20
  • \$\begingroup\$ oof ok guess i didn't look far enough :/ \$\endgroup\$
    – Makonede
    Jun 26, 2021 at 20:52
1
\$\begingroup\$

Mascarpone, 82 53 bytes

[9876543210]$v[v'$>,<]v*'#<^v'.>1#########^0123456789

Try It Online!

Explanation

[9876543210]$      // push the string '[9876543210' (we can ignore the '[')
v                  // push the current interpreter
 [      ]v*        // define an operation (under the current interpreter)
  v'$>,<           // "bind a symbol from stdin to 'Pop ToS'"
           '#<^    // bind this operation to '#' and install it to the environment
v'.>1              // push an interpreter that defaults to "Output ToS"
     #########     // bind 9 symbols from stdin to "Pop ToS"
              ^    // install this interpreter to the environment
0123456789         // one of these will output ToS, the rest will only pop
                   // the symbols to output are on the stack from line 1
\$\endgroup\$
1
\$\begingroup\$

MATL, 6 bytes

4Y2jX-

Try it at MATL Online

Explanation

4Y2     % Pre-defined literal for '0123456789'
j       % Grab input as a string
X-      % Compute the set difference between the two, yields the characters in 
        % '0123456789' that are missing in the input
        % Implicitly display the result
\$\endgroup\$
1
\$\begingroup\$

Factor + math.unicode, 25 24 bytes

[ "0123456789"swap ∖ ]

Try it online!

Set difference () with "0123456789".

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

x86‑64 assembly machine code, 17 B

input

  • address of string buffer in 64‑bit register rsi
  • string buffer consists of exactly 9 ASCII-encoded Western-Arabic digits

code listing

  1                      missing_integer:
  2 00000000 6A09           push 9          ; rsp ≔ rsp − 8  rsp↑ ≔ 9
  3 00000002 59             pop rcx         ; rcx ≔ rsp↑     rsp ≔ rsp + 8
  4 00000003 31C0           xor eax, eax    ; eax ≔ 0
  5 00000005 BADD010000     mov edx, 477    ; edx ≔ 477
  6                      .digit_sum:
  7 0000000A AC             lodsb           ;  al ≔ rsi↑     rsi ≔ rsi + 1
  8 0000000B 29C2           sub edx, eax    ; edx ≔ edx − eax
  9 0000000D E2FB           loop .digit_sum ; ecx ≔ ecx − 1   ZF ≔ ecx = 0
 10                                         ; if ¬ZF then goto digit_sum
 11 0000000F 92             xchg eax, edx   ; shorter than `mov eax, edx`
 12 00000010 C3             ret

output

  • the “missing” integer in ax
\$\endgroup\$
7
  • 1
    \$\begingroup\$ mov dl, 477%256 \$\endgroup\$
    – l4m2
    Jan 12, 2023 at 4:57
  • \$\begingroup\$ @l4m2 I don’t understand. The algorithm relies on the value 477, not 221. \$\endgroup\$ Jan 12, 2023 at 11:44
  • \$\begingroup\$ You only need dl, or if you want to return whole eax, movzx eax, dl is only 2 bytes more, mov saves 3 bytes \$\endgroup\$
    – l4m2
    Jan 12, 2023 at 12:04
  • \$\begingroup\$ @l4m2 I’m sorry, I don’t see it. Could you submit a full/complete answer/solution? \$\endgroup\$ Jan 12, 2023 at 14:40
  • 1
    \$\begingroup\$ Was push 9/pop rcx/mov dl,221/lodsb/sub edx,eax/loop $-3/movzx eax,dl/ret \$\endgroup\$
    – l4m2
    Jan 12, 2023 at 16:04
1
\$\begingroup\$

jq -R, 15 bytes

explode|477-add

Try it online!

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

Nibbles, 2.5 bytes (5 nibbles)

`r-_$
`r-_$
`r      # get the first integer found in
        # the string of
  - $   # remove the command-line arg 
   _    # from the string in STDIN
        # (but if there is no STDIN,
        # from all printable ASCII)

Input string is provided as a command-line argument.
If STDIN is empty, Nibbles assigns a default value of 'the list of printable ascii characters in a more useful order". The first (and only) integer present in this list after the input string is removed should be the missing digit from the input string.

enter image description here

(Note that since Nibbles will check to see if there's anything in STDIN, in the screenshot above I've pressed 'ctrl-D' to terminate STDIN with no input)

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

x86‑64 assembly machine code, 13 B

f:      use64
6A09    push 9
59      pop rcx
6A01    push 1
5A      pop rdx
a:
AC      lodsb
30C2    xor dl, al
E2FB    loop a
92      xchg eax, edx
C3      ret

read string from [rsi] and return rax

\$\endgroup\$
2
  • \$\begingroup\$ Just to clarify: In contrast to my previous (longer) solution this function returns the ordinal value of the respective ASCII character. I understood You must return the missing integer. that necessarily an integer value was expected. \$\endgroup\$ Jan 13, 2023 at 15:39
  • \$\begingroup\$ @KaiBurghardt Then change push 1 into push 49 \$\endgroup\$
    – l4m2
    Jan 13, 2023 at 15:54
1
\$\begingroup\$

GolfScript, 6 bytes

10,`^~

Try it online!

There's a shorter, 4-byte solution if input can be taken in the form of an array of integers:

10,^

Try it online!

Explanation

10,`^~

10,     # create an array of integers from 0-9
   `    # convert it into a string
    ^   # setwise difference
      ~ # dump array onto the stack

The 4-byter just removes the need for a string because it takes input as an array and the difference doesn't include any [ characters, removing the need for the ~

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

Ruby, 25 bytes

->x{'0123456789'.tr x,''}

Not terribly competitive, I'm afraid

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

Lambdabot Haskell, 14 bytes

(['0'..'9']\\)

After realizing I could just make a list with the String "0123456789" instead of the integers [0,1,2,3,4,5,6,7,8,9], the step for converting the string to integers could be skipped.

Type is now String -> String (takes a string and returns a string with the correct number). Call like:

(['0'..'9']\\)"149263708"         -- Outputs "5"

Previous:

([0..9]\\).map digitToInt

Uses set difference, unlike the other Haskell answer, type String -> Int

Call like

([0..9]\\).map digitToInt$"123467890"  -- Outputs 5
\$\endgroup\$
0
\$\begingroup\$

Pip, 5 bytes

5 bytes seems to be the number for all golfing languages that aren't Jelly.

,tDCa

Takes input as a command-line argument. Try it online!

Explanation

,t     Range(10)
  DC   From each element, delete all characters...
    a  ...that are in 1st cmdline arg
       Concatenate and print (implicit)

The result is actually a list like ["";"";"";"";4;"";"";"";"";""] (which is what you get if you put RP at the front of the code). Lists by default are concatenated together before printing, so all you will see is 4.

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

C (clang), 31 bytes

f(x){return x?f(x/10)-x%10:45;}

Strictly speaking, f(x) returns the sum of the missing digits. This lets me knock off a digit, get the sum of the missing digits, then add it back on.

Try it online!

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

Octave, 20 19 14 bytes

@(a)477-a*~~a'

Try it online!

Developed independently but the same as some other answers.

a'          transpose of array `a`
~~a'        convert all elements of a' to 1
a*~~a'      matrix multiplication of `a` with a column vector of 1s
            that is equivalent to sum(a)
477-a*~~a'  subtract from [477=sum('0123456789')-48]
\$\endgroup\$
0
\$\begingroup\$

Java 7, 61 54 bytes

long d(int n){return(15-Long.valueOf(n+"",16)%15)%15;}

Based on @Neil's JavaScript (ES6) answer (just like JavaScript, Java uses remainder for negative-modulo. Original port is from @xnor's Python answer)

Old answer (61 bytes):

String c(int n){return"0123456789".replaceAll("["+n+"]","");}

Try it here.

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

REXX, 36 bytes

#=0123456789
arg n
say verify(#,n)-1
\$\endgroup\$
0
\$\begingroup\$

AHK, 39 bytes

i=[%1%]
Send % RegExReplace(99066**2,i)

Again, the inherent confusion between the input variable 1 and the actual number 1 causes confusion in AHK functions. At least it only cost 3 bytes this time.

99066**2 = 99066^2 = 9814072356 (a trick I copied from Rod's answer)

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

Chip, 64 bytes

Azv~a
##'Bzv~b
`^v##'Czv~c
*f|`^-##'Dzv~d
Z~'~e `^-##'
ZZZZZZZ~S

Try it online!

Chip is a 2D language that operates on individual bits in a byte stream. Each byte of input is broken down into its component bits for computation, then stitched back together for output.

This solution uses a rather simple algorithm, that is only a minor twist on that used by many of the other solutions:

  1. Start with a value of 0x2:

     0+1+2+3+4+5+6+7+8+9 =  45 (0x2D)
                     ~45 = -46 (0xD2)    *
              -46 & 0x0F =   2  (0x2)
    

    * I only do half of two's complement negation; I skip the increment at the end for a reason. I'll get back to this.

  2. Add each code point in the string, masked with 0x0F, ignoring carries.

  3. After the ninth addition, the current value will be equal to -1 minus the missing digit, masked with 0x0F:

    Let's say we were missing the digit '4':

                  -1 - 4 =  -5  (0xB)
                   ~(-5) =   4  (0x4)    *
    

    * Again, we only do half of negation. This instance cancels out the offset introduced by the previous negation.

  4. Prefix the value with 0x3, giving the codepoint for the missing digit:

              0x30 | 0x4 =  52 (0x34)
    

What portions of the code do each bit? Well, they're a bit mixed together, but I'll try to cover the highlights:

  • The # elements do the addition described in step 2.
  • The z elements near the adders carry over the current value to the next cycle so that we can have a running sum.
  • The Z elements keep track of which digit of the input we are on, handling the condition in step 3. They also provide the signal used to initialize the adders to 0x2, as described in step 1.
  • The S element suppresses all output until the Z elements disable it on the final digit. (If you are looking at the TIO, try deleting this element to see all the intermediate values. Also, adding the flag -v will print the actual code points to stderr.)
  • The letters A through D are reading the 4 low bits of the input, and a through d write those same bits of the output.
  • The letters e and f provide the value 0x30 to the output as described in step 4.
\$\endgroup\$
0
\$\begingroup\$

D, 24 bytes

writeln(477-readln.sum);

Just add up all characters in the given string (not terminated by a newline). The sum is s = 48 * 9 + (0 + 1 + 2 + ... + 9 - x) = 477 - x, therefore, x = 477 - s.

The calls make use of optional parentheses (-4 bytes), and .sum invocation uses uniform function call syntax (-1 more byte).

Try it online!

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

Q, 24 bytes

{1#iasc"0123456789"in x}

Gets a boolean vector between the expectation and input, then sorts the indices of the expectation by that boolean vector in ascending order, first value always being the missing element since boolean for it is set to 0 and we know that value=index in this case.

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

Racket 106 bytes:

(filter-not(λ(x)(member x(string->list(number->string n))))
(for/list((i(range 48 58)))(integer->char i)))

Ungolfed:

(define (f n)
  (filter-not
   (λ(x)
     (member x
             (string->list
              (number->string n))))
   (for/list((i(range 48 58)))(integer->char i))))

Testing:

(f 867953120)

Output:

'(#\4)
\$\endgroup\$
0
\$\begingroup\$

C#, 21 bytes

z=>45-z.Sum(v=>v-'0')

The expression v-'0' takes the char value such as '3' and subtracts the char value for '0', leaving the value 3, essentially converting the character 3 into the integer 3.

45 is the sum of all the numbers 0 through 9. 45 - the sum of the passed-in integers yields the missing integer.

Sample code

public static void Main()
{
    Func<string, int> X = z=>45-z.Sum(v=>v-'0');
    
    Console.WriteLine(X("123456789"));
    Console.WriteLine(X("134567890"));
    Console.WriteLine(X("867953120"));
}

Test Here: https://dotnetfiddle.net/yanR5S

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

Noodel, 8 bytes

ɲdFḶṡạĖ⁻

Try it:)


How it works

ɲdFḶṡạĖ⁻
         # Input implicitly pushed onto the stack.
ɲd       # Pushes the string "0123456789" onto the stack.

  FḶṡạĖ⁻ # Loops nine times removing digits from the string "0123456789" producing the missing number.
  F      # Pushes the string "F" onto the stack.
   Ḷ     # Consumes the string "F" and converts to a base 98 number producing 9 then loops the following that many times.
    ṡ    # Swaps the string "0123456789" with the input on the stack.
     ạ   # Gets the ith element from the input and pushes it onto the top of the stack.
      Ė  # Grabs the string "0123456789" at the bottom of the stack and puts it at the top.
       ⁻ # Removes the element pulled out of the input from the string.
         # Implicit end of the loop.

         # Implicit push to the screen, outputting the missing digit.
\$\endgroup\$
0
\$\begingroup\$

Pyt, 5 bytes

ɳą←ą\

Try it online!

Takes input as a string (with quotes)

ɳ          push "0123456789"
 ą         convert to array of characters
  ←ą       get input string; convert to array of characters
    \      set difference; implicit print

Pyt, 5 bytes

Ś9△-~

Try it online!

Takes input without quotes

Ś        implicit input; sum of digits
 9△      45 (9th triangle number)
   -     subtract
    ~    negate; implicit print
\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 3 bytes

kDḍ

Attempt This Online!

Explanation

kDḍ  # Implicit input
  ḍ  # Symmetric set difference
kD   # with the string "0123456789"
     # Implicit output
\$\endgroup\$

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.