34
\$\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\$
  • 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 '17 at 19:48
  • 10
    \$\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\$ – AdmBorkBork Mar 27 '17 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\$ – AdmBorkBork Mar 27 '17 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 '17 at 0:45
  • 2
    \$\begingroup\$ Several answers take an integer as function input. Is that allowed? \$\endgroup\$ – Dennis Mar 28 '17 at 0:52

64 Answers 64

36
\$\begingroup\$

Python 2, 18 16 bytes

+beauty thanks to @Sarge Borsch

`99066**2`.strip

Try it online!

99066**2 is just a shorter way to generate a string that contains 0~9

\$\endgroup\$
  • 7
    \$\begingroup\$ 32043 can be changed to a more beautiful number. 99066 is center-symmetric (doesn't change if rotated 180 degrees around center) or maybe 97779 (palindrome, two distinct digits) \$\endgroup\$ – Sarge Borsch Mar 28 '17 at 10:12
  • 1
    \$\begingroup\$ If the OP allows to print the number twice, 764**4 can save two bytes. \$\endgroup\$ – Titus Mar 30 '17 at 9:16
  • \$\begingroup\$ @Titus 764**4 is missing 5,8 and 9 \$\endgroup\$ – Rod Mar 30 '17 at 11:15
  • 1
    \$\begingroup\$ Typo ... I meant 763**4 = 338920744561 \$\endgroup\$ – Titus Mar 30 '17 at 12:00
25
\$\begingroup\$

Python, 22 bytes

lambda s:-int(s,16)%15

Try it online!

An arithmetic solution. Interprets the input string as hex, negates it, and takes the result modulo 15.

\$\endgroup\$
  • 2
    \$\begingroup\$ Can you explain why this works? \$\endgroup\$ – KarlKastor Mar 28 '17 at 20:07
  • 1
    \$\begingroup\$ @KarlKastor, modulo 15 in base 16 works analogically to modulo 9 in base 10. Modulo base-1 is constant when taking sum of digits, just because 10 ≡ 1 (mod base-1). Sum of all possible digits is constant, so the missing digit is the difference of this constant and the input number (modulo base-1). \$\endgroup\$ – mik Mar 29 '17 at 13:43
16
\$\begingroup\$

APL (Dyalog), 4 bytes

Derived function

⎕D∘~

⎕DDigits

 (ties a left argument to the following dyadic function to create a monadic function)

~ except [the argument]

Try it online!


Function train

⎕D~⊢

⎕DDigits

~ except

 the right argument

Try it online!


Explicit program

⎕D~⍞

⎕DDigits

~ except

 character input

Try it online!

\$\endgroup\$
12
\$\begingroup\$

Brain-Flak, 48 38 36 + 3 = 39 bytes

10 bytes saved thanks to DJMcMayhem!

((([]())[]{}){()()({}[()])}{}[{{}}])

Try it online!

Explanation

The sum of all the digits in Ascii is 525. This program sums up the input and subtracts it from 525 to get the missing digit.

((([]())[]{}){()()({}[()])}{}      )

Will push 525. This takes advantage of the fact that we know there will be 9 elements of input to begin with. This means that [] evaluates to 9 which allows us to get to large numbers like 525 quickly.

Next we have the bit:

                             [{{}}]

which will sum up the inputs and subtract it from the total.

\$\endgroup\$
  • \$\begingroup\$ How does this work? \$\endgroup\$ – Pavel Mar 27 '17 at 19:51
  • \$\begingroup\$ @ГригорийПерельман Explanation added! \$\endgroup\$ – Sriotchilism O'Zaic Mar 27 '17 at 19:58
  • 2
    \$\begingroup\$ If you move the negative(sum(input())) to the end, you can abuse the stack-height nilad to push 525 easier. (([][][]()()()){()()({}[()])}{}[{{}}]) should save you 10 bytes \$\endgroup\$ – DJMcMayhem Mar 27 '17 at 20:04
  • \$\begingroup\$ 30 bytes by subtracting 477 instead \$\endgroup\$ – Jo King Apr 6 '18 at 15:41
12
\$\begingroup\$

Haskell, 24 23 bytes

(477-).sum.map fromEnum

Try it online! Usage: (477-).sum.map fromEnum $ "123456890". 477 is the sum of the character codes of the digits 1 to 9, excluding 0. This anonymous function computes 477 minus the sum of all digit character codes to find the missing one.

Turning the char digits to ints is one byte longer:

(45-).sum.map(read.pure)
foldl(\a b->a-read[b])45

Try it online!

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

Jelly, 3 bytes

ØDḟ

Simply filters () the input string from “0123456789” (ØD).

Try it online!

\$\endgroup\$
  • 3
    \$\begingroup\$ I like the way that all the golfing languages (and even some non-golfing languages) are using the same algorithm, but Jelly manages to have the shortest names for the builtins it uses, and the least boilerplate for reversing the arguments to . \$\endgroup\$ – user62131 Mar 27 '17 at 20:26
  • 1
    \$\begingroup\$ @ais523 APL is letter by letter the same (except that it would be an APL snippet rather than a function/program): Ø=, D=D, =~, as in ⎕D~'867953120'. \$\endgroup\$ – Adám Mar 27 '17 at 21:20
  • 3
    \$\begingroup\$ Me, while scrolling through the answers: "I'm predicting 3 characters in Jelly." Bingo. :^D \$\endgroup\$ – DLosc Mar 28 '17 at 0:09
9
\$\begingroup\$

Ruby, 14

Sums the ascii codes and subtracts from 48*9+45

->s{477-s.sum}

Use like this

f=->s{477-s.sum}

puts f["123456789"]
\$\endgroup\$
9
\$\begingroup\$

JavaScript (ES6), 26

Edit 1 byte save thx @Neil, with a much more smarter trick

Xoring all the values from 1 to 9 gives 1. Xor 1 one more time and the result is 0. So, if any single value is missing, the result will be the missing value.

s=>eval([1,...s].join`^`)

Test

f=s=>eval([1,...s].join`^`)

function go() {

  var i=I.value;
  O.textContent = f(i)
}  

go()
<input oninput='go()' value='012987653' id=I>
<pre id=O></pre>

\$\endgroup\$
  • \$\begingroup\$ s=>eval([1,...s].join`^`) saves a byte. \$\endgroup\$ – Neil Mar 28 '17 at 9:37
  • \$\begingroup\$ @Neil ... and it's much more interesting too \$\endgroup\$ – edc65 Mar 28 '17 at 10:05
  • \$\begingroup\$ I feel this tip came suspiciously short after my answer :D anyway nice golf +1. \$\endgroup\$ – Christoph Mar 28 '17 at 10:13
  • 1
    \$\begingroup\$ @Christoph Well it sounded as if you wanted to spread the word... \$\endgroup\$ – Neil Mar 28 '17 at 10:49
  • \$\begingroup\$ @Neil absolutly :) Nice to see that it helped! \$\endgroup\$ – Christoph Mar 28 '17 at 10:51
8
\$\begingroup\$

Retina, 27 21 19 bytes

-6 Thanks to Basic Sunset
-2 Thanks to Martin Ender

.
$*_5$*
+`_1|1_

1

Try it online!

Replace every digit with that many _s and 5 1s:

.
$*_5$*

Remove all of the _s and a 1 for each:

+`_1|1_ 


Count the number of 1s left:

1
\$\endgroup\$
  • \$\begingroup\$ The first line of the second answer can be just .. \$\endgroup\$ – Neil Mar 27 '17 at 20:37
  • \$\begingroup\$ You can save a few bytes by using deduplication instead of replacement: Try it online \$\endgroup\$ – Business Cat Mar 27 '17 at 20:39
  • \$\begingroup\$ Oh well, and here was I just getting the second answer down to the old byte count of the first answer... ^ 5 ^. $*9¶ . $*_ +`_¶_ _ \$\endgroup\$ – Neil Mar 27 '17 at 20:41
  • \$\begingroup\$ @Neil I got it to one less than the original. \$\endgroup\$ – Riley Mar 27 '17 at 20:51
  • \$\begingroup\$ (Huh, that looks suspiciously similar to my answer, the only difference is that you switched from _ to 1 to save a byte.) \$\endgroup\$ – Neil Mar 27 '17 at 20:56
6
\$\begingroup\$

05AB1E, 6 bytes

45¹SO-

Try it online!

45     # Push 45
  ¹    # push input
   S   # Split
    O  # Sum
     - # Subtract (45 - sum)
\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 31 29 28 22 bytes

s=>(15-`0x${s}`%15)%15

Port of @xnor's Python answer, except that JavaScript only has a remainder operator rather than a modulo operator, so I can't do it in a single step. Edit: Saved 6 bytes thanks to @Arnauld.

\$\endgroup\$
  • \$\begingroup\$ s=>[...s].map(c=>r-=c,r=45)|r ;-) \$\endgroup\$ – ETHproductions Mar 27 '17 at 21:01
  • 3
    \$\begingroup\$ You are too much in love with reduce. +1 anyway \$\endgroup\$ – edc65 Mar 27 '17 at 21:06
  • \$\begingroup\$ @Arnauld I don't see that working when s[0]!='0', but there's already an answer that uses eval. \$\endgroup\$ – Neil Mar 28 '17 at 8:58
  • \$\begingroup\$ Could you do s=>(15-`0x${s}`%15)%15? \$\endgroup\$ – Arnauld Mar 28 '17 at 14:40
  • \$\begingroup\$ @Arnauld Bah, and I'd already done that for the Batch port too... \$\endgroup\$ – Neil Mar 28 '17 at 14:55
6
\$\begingroup\$

Brainfuck, 17 15 bytes

-[-[->-<],]>++.

Try it out here. This solution works on standard Brainfuck (8-bit cells) only, as it relies on wrapping.

It's a rare day when Brainfuck can actually compete, but this challenge just happened to line up with the BF spec pretty well!

Instead of straight-up breaking down this answer, I'd like to step through the iterations I took, because I think it would be more understandable (and more interesting).
Note: this solution is inspired largely by Wheat Wizard's Brain-Flak answer.

Explanation

Step 1, 26 bytes

In his answer, Wheat Wizard pointed out that the sum of the ASCII values from 0-9 sum to 525. And since standard Brainfuck only has a notion of [0,255], this makes the value 525 % 256 = 13. That is to say, subtracting the ASCII values of the input from 13 nets you the missing digit.

The first version of this program was:
1. Put 13 in the first cell
2. Take inputs into the second cell
3. Subtract the second cell from the first cell
4. Jump to 2 if there are inputs remaining
5. Print the first cell

And here's the code for the simple solution:

+++++++++++++ #Set the first cell to 13  
>,            #Take inputs into the second cell  
[[<->-],]     #Subtract the second cell from the first cell and repeat until inputs are over  
<.            #Print the first cell  

Step 2, 19 bytes

As pointed out in his answer, since we know the input will be exactly length 9, we can use that value as a constant, and eliminate that long string of +'s right at the beginning.
It also doesn't matter at what point we add 13 (thanks, commutative property!), so we'll mix it in with the subtraction and printing steps.

,        #Take input to enter the loop
[[->-<], #Subtract the first cell from the second cell 
>+<]     #Add 1 for each input; totaling 9
>++++    #Add the missing 4 to make 13
.        #And print

This was my original answer to this problem, but we can do better.

Step 3, 17 bytes

Interestingly enough, the previous answer works even if we begin with a + instead of a ,

+[[->-<],>+<]>++++.

Brainfuck required something in a cell in order to begin a loop. We naively added that extra 4 in the end, when it could have gone in other places.

-[[->-<],>+<]>++.

With some totally intentional (read: trial and error) loop trickery, starting off the program with a - leads to two interesting results:

  1. One gets added to the second cell (saving 1 byte at the end).
  2. The loops runs one extra time, totaling 10 instead of 9 (saving another 1 byte).

1 + 10 + 2 = 13, and we end up with the original answer.

Looking back on it, this is probably an excessive write-up for such a simple Brainfuck program.

Step 4, 15 bytes

After thinking about this solution a bit more, I was able to cut off 2 bytes.

I wanted to clarify something about the previous step:
The minus to enter the loop effectively adds 1, but what it's actually doing is subtracting 255 from the second cell (resulting in 1).

It's obvious in retrospect, but subtracting 1 from the first cell is the same as adding 1 to the second cell (because everything in the first cell gets subtracted from the second cell.)

-[-[->-<],]>++.

I was able to remove the ">+<" by adding a "-" at the beginning of the first loop. It has to go there, and not where the ">+<" was, because the program will loop infinitely otherwise.

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

Octave, 22 bytes

@(x)setdiff('0':'9',x)

Try it online!

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

Mathematica, 25 bytes

477-Tr@ToCharacterCode@#&

Pure function taking a string as input and returning an integer. Mathematica has long command names and is reluctant to convert between strings and integers, which makes it particularly bad at this challenge. The best I could find was the algorithm from Level River St's Ruby answer, which does a computation based on the total of the ASCII codes of the input string; in Mathematica, this uses only one long command name.

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

PHP, 27

<?=trim(32043**2,$argv[1]);

uses the trick from Rod's answer to generate a string containing all digits then removes all digits except for the missing one.


PHP, 41

for($b=1;$i<9;$b^=$argv[1][$i++]);echo$b;

This one uses xor because I haven't seen it yet.

\$\endgroup\$
  • \$\begingroup\$ Nice I have not think about trim. Alternatives values 32043,32286,33144,35172,35337,35757,35853,37176,37905,38772,39147,39336,40545,42744,43902,44016,45567,45624,46587,48852,49314,49353,50706,53976,54918,55446,55524,55581,55626,56532,57321,58413,58455,58554,59403,60984,61575,61866,62679,62961,63051,63129,65634,65637,66105,66276,67677,68763,68781,69513,71433,72621,75759,76047,76182,77346,78072,78453,80361,80445,81222,81945,83919,84648,85353,85743,85803,86073,87639,88623,89079,89145,89355,89523,90144,90153,90198,91248,91605,92214,94695,95154,96702,97779,98055,98802,99066 \$\endgroup\$ – Jörg Hülsermann Mar 28 '17 at 10:43
5
\$\begingroup\$

Bash + coreutils, 19 bytes

I found a shorter bash solution, that uses an interesting checksum approach:

sum -s|dc -e524?--P

Try it online!

Explanation:

The sum command prints a checksum and a block count. I don't know many details, but using the option -s (System V algorithm) will make the checksum equal to the ASCII sum of each input character code. As such, the checksum remains constant when the order of the same input characters changes.

Given 867953120 as test case (last example), here is how the script works:

  • sum -s outputs 473 1. If no integer was missing, the checksum would have been 525.
  • dc -e524? pushes 524 and then the pipe input. The stack is: 1 473 524. The idea is to subtract the checksum from 525, but since sum outputs 1 as well, I need to work with it.
  • --P. After applying the two subtractions (524-(473-1)), the stack is: 52. With 'P' I print the character with that ASCII code: 4, the missing digit.
\$\endgroup\$
4
\$\begingroup\$

Fortran 95, 146 128 bytes

function m(s)
character(len=10)::s,t
t='0123456789'
do j=1,10
k=0
do i=1,9
if(s(i:i)==t(j:j))k=1
end do
if(k==0)m=j-1
end do
end

Not very short, I'm afraid.

Ungolfed:

integer function m(s)
    implicit none

    character(len=9)::s
    character(len=10)::t
    integer:: i, j, k

    t='0123456789'
    do j=1,10
        k=0
        do i=1,9
            if (s(i:i) == t(j:j)) k=1
        end do
        if (k==0) m=j-1
    end do

end function m
\$\endgroup\$
3
\$\begingroup\$

CJam, 5 bytes

A,sq-

Try it online!

A,     e# The range from 0 to 9: [0 1 2 3 4 5 6 7 8 9]
  s    e# Cast to a string: "0123456789"
   q   e# The input
    -  e# Remove all characters from the range that are in the input
       e# Implicit output
\$\endgroup\$
3
\$\begingroup\$

GNU sed, 36 bytes

Includes +1 for -r

s/$/0123456789/
:
s/(.)(.*)\1/\2/
t

Try it online!

s/$/0123456789/ # Append 0123456789
:               # Start loop
s/(.)(.*)\1/\2/ # remove a duplicate character
t               # loop if something changed
\$\endgroup\$
3
\$\begingroup\$

Brachylog (2), 5 bytes

ẹ:Ị↔x

Try it online!

Arguably should be shorter (I'm still confused as to why the is necessary), but this is the best I could do.

Explanation

ẹ:Ị↔x
ẹ      Split the input into a list of characters
 :Ị    Pair that list with the string "0123456789"
   ↔x  Remove all elements of the list from the string
\$\endgroup\$
  • \$\begingroup\$ x implementation is old and pretty buggy, which is why you need . \$\endgroup\$ – Fatalize Mar 28 '17 at 6:23
  • \$\begingroup\$ You can actually make an argument that something like ¬∋ℕ should work in only 3 characters – that's what I tried first – but there's multiple reasons why it doesn't, and I don't think there's any plausible way to change Brachylog so that it would. \$\endgroup\$ – user62131 Mar 28 '17 at 15:15
  • \$\begingroup\$ Having ¬∋ℕ work like that is not even possible in Prolog, unless specifically programming what you mean by not not in. ¬ in Brachylog is equivalent to \+ in Prolog, and its meaning is that of "not provable under the closed-world assumption", rather than "give me choice points for everything that does not verify this" (which is almost always an infinite number of things) \$\endgroup\$ – Fatalize Mar 29 '17 at 6:43
  • \$\begingroup\$ The only way to do it in Prolog would be to "labelize" the in advance, but that would mean tinkering with Brachylog's evaluation order based on the content of the predicates. That's only one of the problems it has, though; there are a ton of others. \$\endgroup\$ – user62131 Mar 29 '17 at 6:46
3
\$\begingroup\$

Common Lisp, 47 bytes

(lambda(s)(- 45(reduce'+ s :key'digit-char-p)))

Ungolfed:

(lambda (s) (- 45 (reduce '+ s :key 'digit-char-p)))

Explaination:

(reduce '+ s :key 'digit-char-p)

This loops through the chars in s, converts them to digits, and adds them. Digit-char-p, conveniently, return the number of the char as its "true" value, so it can be used as a test or a conversion.

(- 45 ...)

Subtract from 45 gives back the digit that was missing from the input.

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

Cubix, 18 Bytes

5v&;52/ni?@.>!&oW+

Expanded

    5 v
    & ;
5 2 / n i ? @ .
> ! & o W + . .
    . .
    . .

Try it here

Uses the same sort of method as this brain-flak answer.

Create the value -525 on the stack by pushing 5, 2, concatenate, push 5, concatenate and negate.
Then repeatably get input and add until end of input is hit.
Remove the last input, negate(make positive) the last add result, output the character and halt.

The reason for working from -525 up is that the character output is hit for each input iteration. Since the value is negative, nothing is output until the loop is exited and the negative value is made positive.

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

PHP, 37 bytes

<?=45-array_sum(str_split($argv[1]));
\$\endgroup\$
3
\$\begingroup\$

Bash (+utilities), 22, 19 bytes

  • Use seq instead of brace expansion, -3 bytes (Thx @Riley !)
seq 0 9|tr -d \\n$1 

Test

$seq 0 9|tr -d \\n123456789
0

Try It Online!

\$\endgroup\$
  • \$\begingroup\$ If you moved the space before the $1 it would be more obvious... \$\endgroup\$ – Neil Mar 28 '17 at 9:34
  • \$\begingroup\$ @Neil, yep, that's a nice idea ! Thx ! \$\endgroup\$ – zeppelin Mar 28 '17 at 9:50
  • \$\begingroup\$ You could use seq instead of echo: seq 0 9|tr -d \\n$1 \$\endgroup\$ – Riley Mar 28 '17 at 15:25
3
\$\begingroup\$

Google Sheets, 39 33 bytes

Input is entered into cell A1.

Code:

=REGEXEXTRACT(4&2^29,"[^"&A1&"]")

Saved 6 bytes thanks to Steve Kass.

Previous Code:

=REGEXEXTRACT("0123456789","[^"&A1&"]")

Result:

enter image description here

\$\endgroup\$
  • \$\begingroup\$ The number 2^29 has all the digits but 4, so 33 bytes: =REGEXEXTRACT(4&2^29,"[^"&A4&"]") \$\endgroup\$ – Steve Kass Mar 31 '17 at 0:28
  • \$\begingroup\$ @SteveKass Nice. =REGEXEXTRACT(0&49^9,"[^"&A1&"]") is also a valid solution, given similar logic. Updated answer. \$\endgroup\$ – Grant Miller Mar 31 '17 at 22:25
3
\$\begingroup\$

Befunge 98, 14 12 bytes

I saved 1 byte by moving the program onto 1 line and 1 byte by doing some better math

~+;@.%a--7;#

Try it online!

Explanation

The sum of the ASCII values range from 477 to 468 depending on which number is missing. By subtracting this from 7, we get the range -470 to -461. By modding this number by 10, we get the range 0 - 9, which we can then print.

~+;       ;#    Sums the ASCII values of all characters to stdIn
~          #    The # doesn't skip over the ~ because it's on the end of a line
~               Once EOF is hit, the ~ reverses the IP's direction
          ;#    Jump the ; that was used before
       --7      Subtract the sum from 7 (really just 0 - (sum - 7))
     %a         Mod it by 10
   @.           Print and exit

The reason I use the ASCII values instead of taking integer input is because the & command in Try it Online halts on EOF (Even though it should reverse the IP). The ~ works correctly, though.

Old Program, 14 bytes

#v~+
@>'i5*--,

The sum of the ASCII values of all 10 digits is 525. By subtracting the sum of the given digits from 525, we get the ASCII value of the missing character.

#v~+         Sums the ASCII values of all characters on stdIn
             Moves to the next line when this is done
 >'i5*       Pushes 525 (105 * 5)
      --     Subtracts the sum from 525
@       ,    Prints and exits
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 30 bytes

param($n)0..9|?{$n-notmatch$_}

Try it online!

Takes input $n, constructs a range 0..9 (i.e., 0, 1, 2 ... 9), then uses a Where-Object clause (the |?{...}) to pull out the number that does regex -notmatch. That's left on the pipeline, output is implicit.

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

Röda, 28 bytes

{(_/"")|ord _|sum|chr 525-_}

Try it online!

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

Pyth, 5 Bytes

-jkUT

try it!

explanation

-jkUT
    T   # 10
   U    # The unary range of ten: [0,1,..,9]
 jk     # join that on the empty string
-       # set minus

"-jUT" also kinda works but produces newlines for every int.

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

05AB1E, 5 bytes

žhISK

Try it online!

Explanation

žh     # from the string "0123456789"
    K  # remove
  IS   # each digit of the input
\$\endgroup\$
  • 6
    \$\begingroup\$ I like it because you can say it out loud. '"žhISK", he cried, as he waved his wand over the top-hat and a small white rabbit appeared in a puff of smoke'. \$\endgroup\$ – Penguino Mar 27 '17 at 23:50

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.