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

2
\$\begingroup\$

Japt, 6 bytes

¬x n45

Try it online!

Explanation:

¬x n45
   n45     // 45-
¬          //    Split the input into an array "123" → ["1","2","3"]
 x         //    Return the sum of all the items ["1","2","3"] → 6
           // 45 - 6 = output
\$\endgroup\$
2
\$\begingroup\$

C (tcc), 36 31 bytes

f(long*s){s=9-(*s+s[1]%16)%15;}

Takes a string as input and returns an int. As written, this work only on little-endian architectures.

The lack of a return statement is undefined behavior, but this works with tcc and gcc.

Try it online!

Alternate version, 33 bytes, no UB

f(long*s){*s=57-(*s+s[1]%16)%15;}

Takes a string pointer as input and overwrites the string with the result (allowed by default).

While this is perfectly valid C, it will not work with compilers such as gcc, which store strings in read-only memory sections.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I like the use of longs to compress the information. \$\endgroup\$ – Bijan Mar 28 '17 at 0:55
2
\$\begingroup\$

dc, 12 10 bytes

Cdi?B%-B%p

Try the dc version online!

This uses the fact that the sum of the digits from 0 to 9 is 45, which is 1 more than a multiple of 11.

The program works by viewing the input as a base 12 number, finding its remainder when divided by 11, and subtracting that from 12 (to find the missing digit). The only catch is that if 0 or 1 is the missing digit, this would give an answer of 11 or 12, respectively, so I mod out by 11 one additional time at the end to take care of those cases.


This yields a short bash solution also:

Bash + Unix utilities, 17 15 bytes

dc -eCdi?B%-B%p

Try the bash version online!

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

J, 9 bytes

Num_j_&-.

Try it online!

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

QBIC, 25 bytes

;{~instr(A,!a$)|a=a+1\_Xa

Explanation

;       Get the input as A$
{       Start an infinite DO loop
~instr  Test if A$ has an occurrence of a% cast to string       
(A,!a$) a starts out as 0. !..$ casts to string.
|a=a+1  If we did find an instance, tets for the next a
\_Xa    Else, quit, printing our missing number.
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 21 bytes

20 bytes of code + -p flag.

s/./+$&/g;$_=45-eval

Try it online!
Note that the input needs to be supplied without final newline (with echo -n for instance).


Some other (longer) approaches (all with -p flag):

$\=45;$\-=$_ for/./g}{

$_=9876543210=~s/[$_]//gr

for$@(0..9){$\=$@if!/$@/}}{
\$\endgroup\$
1
\$\begingroup\$

C, 44 bytes

j;f(char*s){for(j=477;*s;)j-=*s++;return j;}

Try it online!

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

PHP, 53 bytes

There allready was a array_sum and regex solution, wanted to provide another:

print_r(array_diff(range(0,9),str_split($argvs[1])));

A few bytes more, but as bonus it will provide all missing numbers.

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

Batch, 83 76 52 bytes

@set/pn=
@cmd/cset/a(641670-0x%n:~,4%-0x%n:~4%)%%15

Takes input on STDIN. Uses @xnor's hex modulo 15 trick, except that a) Batch only has 32-bit integers, so I have to split the string into two b) Batch only does remainder, not modulo, so I have to subtrat the values from a large multiple of 15 first.

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

PHP, 43 Bytes

for(;strpos(_.$argv[1],48+$i++););echo$i-1;

PHP, 50 Bytes

<?=join(preg_grep("#[{$argv[1]}]#",range(0,9),1));
\$\endgroup\$
  • 1
    \$\begingroup\$ save 1 byte: for(;strpos(_.$argv[1],48+$i++););echo$i-1; \$\endgroup\$ – Christoph Mar 28 '17 at 6:34
  • \$\begingroup\$ @Christoph I have the feeling that you forget the chr function \$\endgroup\$ – Jörg Hülsermann Mar 28 '17 at 9:51
  • 1
    \$\begingroup\$ I have the feeling you should learn your tools ;) If needle is not a string, it is converted to an integer and applied as the ordinal value of a character see strpos on php.net. \$\endgroup\$ – Christoph Mar 28 '17 at 10:01
  • \$\begingroup\$ @Christoph you are right \$\endgroup\$ – Jörg Hülsermann Mar 28 '17 at 10:39
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\$

JavaScript, 26 bytes

v=>45-eval([...v].join`+`)

I'm not a big fan of eval, but it does the job. The sum of all digits 0-9 is 45. 45 minus the sum of the passed-in digits is the value of the missing digit.

Test

f=v=>45-eval([...v].join`+`)


function test() {

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

test()
<input oninput='test()' value='012987654' id=I>
<pre id=O></pre>

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

Scala, 9 bytes

477-_.sum

To use it, assign it to a variable:

val f:(String=>Int)=477-_.sum

_ is syntactix sugar for the arguments of a function, so this expands to x => 477 - x.sum, which will subtract the sum of the ascii codes of the input from 477.

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

PHP, 50 39 Bytes

function x($y){echo(45-array_sum(str_split($y)));}

Jörg Hülsermann's answer prompted me to try the CLI method, Thanks.

echo 45-array_sum(str_split($argv[1]));

Test it at the command line with:

php -r 'echo 45-array_sum(str_split($argv[1]))."\n";' /'12346789'

Test it (The old version) here if you'd like.

Wheat Wizard's answer put me in the right direction and I got help from This Answer

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

J, 14 bytes

((i.10)-."."0)

Try it online!

J is always surprisingly inadequate for golfing :(

(                )  NB. Monadic fork: (f g h) x = (f x) g (h x)
  (i.10)            NB. Array of integers from 0 to 9
            "."0    NB. Digits of string (". = evaluate, "0 = each atom)
         -.         NB. Except
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save 2 bytes by shortening (i.10)"_ to (i.10) \$\endgroup\$ – Tikkanz Mar 30 '17 at 3:16
  • \$\begingroup\$ @TIkkanz thanks! I never remember the left verb of a fork can be a noun :( \$\endgroup\$ – kaoD Mar 31 '17 at 14:48
1
\$\begingroup\$

TXR Lisp, 28 bytes:

This is 28 bytes. It reads a line of digits and yields a string of the missing ones as the result value;

(diff"0123456789"(get-line))

This uses the awk macro to do read every line of input and print the missing digits. It only adds one byte to the length:

(awk((mf(diff"0123456789"))))

At the system prompt:

$ txr -P '(diff"0123456789"(get-line))'
135249
0678

$ txr -e '(awk((mf(diff"0123456789"))))'
123456789
0
234567890
1
012357698
4
13579
02468
^D
\$\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\$

Pure bash, 28

a=1234567890
echo ${a//[$1]}

Try it online.

\$\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\$

awk, 18 bytes

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

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

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

Bash, 36 bytes

sort <(fold -1<<<$a;seq 0 9)|uniq -u

Try it online!

Posting to get golfing tips over this.

fold -1<<$a writes one char of input per line

seq 0 9 writes 0..9 one per line after this.

Those lines are fed to sort and filtered by uniq -u displaying only not duplicated lines.

\$\endgroup\$

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.