34
3
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
34
3
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
36
+beauty thanks to @Sarge Borsch
`99066**2`.strip
99066**2
is just a shorter way to generate a string that contains 0~9
732043 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) – Display Name – 2017-03-28T10:12:58.647
1If the OP allows to print the number twice, 764**4
can save two bytes. – Titus – 2017-03-30T09:16:39.403
@Titus 764**4
is missing 5
,8
and 9
– Rod – 2017-03-30T11:15:51.390
1Typo ... I meant 763**4
= 338920744561
– Titus – 2017-03-30T12:00:22.147
25
lambda s:-int(s,16)%15
An arithmetic solution. Interprets the input string as hex, negates it, and takes the result modulo 15.
2Can you explain why this works? – KarlKastor – 2017-03-28T20:07:03.000
1@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). – mik – 2017-03-29T13:43:59.613
16
⎕D∘~
⎕D
Digits
∘
(ties a left argument to the following dyadic function to create a monadic function)
~
except [the argument]
⎕D~⊢
⎕D
Digits
~
except
⊢
the right argument
⎕D~⍞
⎕D
Digits
~
except
⍞
character input
12
10 bytes saved thanks to DJMcMayhem!
((([]())[]{}){()()({}[()])}{}[{{}}])
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.
How does this work? – Pavel – 2017-03-27T19:51:44.900
@ГригорийПерельман Explanation added! – Post Rock Garf Hunter – 2017-03-27T19:58:51.937
2If 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 – James – 2017-03-27T20:04:07.197
30 bytes by subtracting 477 instead – Jo King – 2018-04-06T15:41:27.290
12
(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
10
3I 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 ḟ
. – None – 2017-03-27T20:26:59.973
1@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'
. – Adám – 2017-03-27T21:20:02.437
3Me, while scrolling through the answers: "I'm predicting 3 characters in Jelly." Bingo. :^D – DLosc – 2017-03-28T00:09:49.367
9
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>
s=>eval([1,...s].join`^`)
saves a byte. – Neil – 2017-03-28T09:37:45.143
@Neil ... and it's much more interesting too – edc65 – 2017-03-28T10:05:59.090
I feel this tip came suspiciously short after my answer :D anyway nice golf +1.
– Christoph – 2017-03-28T10:13:09.1901@Christoph Well it sounded as if you wanted to spread the word... – Neil – 2017-03-28T10:49:48.170
@Neil absolutly :) Nice to see that it helped! – Christoph – 2017-03-28T10:51:12.920
9
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"]
8
-6 Thanks to Basic Sunset
-2 Thanks to Martin Ender
.
$*_5$*
+`_1|1_
1
Replace every digit with that many _
s and 5 1
s:
.
$*_5$*
Remove all of the _
s and a 1
for each:
+`_1|1_
Count the number of 1
s left:
1
The first line of the second answer can be just .
. – Neil – 2017-03-27T20:37:06.657
You can save a few bytes by using deduplication instead of replacement: Try it online
– Business Cat – 2017-03-27T20:39:15.687Oh well, and here was I just getting the second answer down to the old byte count of the first answer... ^
5
^.
$*9¶
.
$*_
+`_¶_
¶
_
– Neil – 2017-03-27T20:41:12.190
@Neil I got it to one less than the original. – Riley – 2017-03-27T20:51:00.397
(Huh, that looks suspiciously similar to my answer, the only difference is that you switched from _
to 1
to save a byte.) – Neil – 2017-03-27T20:56:08.013
@Neil It is. I forgot to up the amount of credit I gave you, my bad. – Riley – 2017-03-27T20:57:34.010
Thanks! (But I'm still impressed by the extra byte saving.) – Neil – 2017-03-27T20:59:33.290
@Neil I only knew of that because Martin Ender commented on my last Retina answer to tell me about it.
– Riley – 2017-03-27T21:00:56.010Here's a worse answer using a similar approach, but perhaps someone can see an opportunity I missed. – FryAmTheEggman – 2017-03-28T17:10:46.250
6
6
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.
s=>[...s].map(c=>r-=c,r=45)|r
;-) – ETHproductions – 2017-03-27T21:01:09.183
3You are too much in love with reduce
. +1 anyway – edc65 – 2017-03-27T21:06:50.523
@Arnauld I don't see that working when s[0]!='0'
, but there's already an answer that uses eval
. – Neil – 2017-03-28T08:58:57.007
Could you do s=>(15-\
0x${s}`%15)%15`? – Arnauld – 2017-03-28T14:40:41.293
@Arnauld Bah, and I'd already done that for the Batch port too... – Neil – 2017-03-28T14:55:27.147
6
-[-[->-<],]>++.
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.
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
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.
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 + 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.
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.
5
5
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.
5
<?=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.
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
– Jörg Hülsermann – 2017-03-28T10:43:24.150
5
I found a shorter bash solution, that uses an interesting checksum approach:
sum -s|dc -e524?--P
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.4
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
3
A,sq-
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
3
Includes +1 for -r
s/$/0123456789/
:
s/(.)(.*)\1/\2/
t
s/$/0123456789/ # Append 0123456789
: # Start loop
s/(.)(.*)\1/\2/ # remove a duplicate character
t # loop if something changed
3
ẹ:Ị↔x
Arguably should be shorter (I'm still confused as to why the ẹ
is necessary), but this is the best I could do.
ẹ:Ị↔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
x
implementation is old and pretty buggy, which is why you need ẹ
. – Fatalize – 2017-03-28T06:23:53.847
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. – None – 2017-03-28T15:15:45.727
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) – Fatalize – 2017-03-29T06:43:14.893
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. – None – 2017-03-29T06:46:12.040
3
I saved 1 byte by moving the program onto 1 line and 1 byte by doing some better math
~+;@.%a--7;#
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.
#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
3
(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.
3
5v&;52/ni?@.>!&oW+
Expanded
5 v
& ;
5 2 / n i ? @ .
> ! & o W + . .
. .
. .
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.
3
<?=45-array_sum(str_split($argv[1]));
3
The number 2^29 has all the digits but 4, so 33 bytes: =REGEXEXTRACT(4&2^29,"[^"&A4&"]") – Steve Kass – 2017-03-31T00:28:02.893
@SteveKass Nice. =REGEXEXTRACT(0&49^9,"[^"&A1&"]")
is also a valid solution, given similar logic. Updated answer. – Grant Miller – 2017-03-31T22:25:28.250
3
seq
instead of brace expansion, -3 bytes (Thx @Riley !)seq 0 9|tr -d \\n$1
Test
$seq 0 9|tr -d \\n123456789
0
If you moved the space before the $1
it would be more obvious... – Neil – 2017-03-28T09:34:38.117
@Neil, yep, that's a nice idea ! Thx ! – zeppelin – 2017-03-28T09:50:55.847
2
param($n)0..9|?{$n-notmatch$_}
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.
2
-jkUT
-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.
2
2
žhISK
Explanation
žh # from the string "0123456789"
K # remove
IS # each digit of the input
6I 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'. – Penguino – 2017-03-27T23:50:28.103
SK
can now be м
to save a byte. – Kevin Cruijssen – 2019-12-12T13:28:41.047
2
¬x n45
¬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
2
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.
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.
I like the use of longs to compress the information. – Bijan – 2017-03-28T00:55:51.200
2
Cdi?B%-B%p
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:
dc -eCdi?B%-B%p
2
1
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!/$@/}}{
1
@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.
1
for(;strpos(_.$argv[1],48+$i++););echo$i-1;
<?=join(preg_grep("#[{$argv[1]}]#",range(0,9),1));
1save 1 byte: for(;strpos(_.$argv[1],48+$i++););echo$i-1;
– Christoph – 2017-03-28T06:34:23.087
@Christoph I have the feeling that you forget the chr function – Jörg Hülsermann – 2017-03-28T09:51:52.857
1
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.
@Christoph you are right – Jörg Hülsermann – 2017-03-28T10:39:10.910
1
;{~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.
1
1
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.
1
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
1
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>
1
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.
1
((i.10)-."."0)
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
1You can save 2 bytes by shortening (i.10)"_
to (i.10)
– Tikkanz – 2017-03-30T03:16:00.497
@TIkkanz thanks! I never remember the left verb of a fork can be a noun :( – kaoD – 2017-03-31T14:48:12.590
1
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
1
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
1
You could have got this to 8 bytes; 8 bytes because this uses unicode characters.
– None – 2019-12-12T13:31:45.2671
Fn.new{|x|"0123456789".trim(x)}
Fn.new{|x| // New anonymous function with parameter x
"0123456789" // Declare all the numbers
.trim(x) // Trim out everything included in x
} // The remaining number is the result
1
'0'9.St
'0'9. % Define the range of string 0 to 9
S % Swap so that instructions are in the right order
% a[0], "0...9" -> "0...9", a[0]
t % Trim out everything in 0...9 that appears in a[0]
% The result is the remaining number
CJ525S-C
C % Convert every character to its code point form
J % Sum the list
525S- % Minus 525 from the value
C % Convert to character form
% Implicit output
1
Prompt Str1
For(A,0,9
If not(inString(Str1,sub("0123456789",A+1,1
Disp A
End
Iterates over a string of each digit, checking if each digit is in the input string. If a digit is not in the input string, that digit is displayed. The sub( command is 1-indexed, so we add 1 during that step which helps us also avoid an extra byte looping to 10. The byte count is affected by the 2 byte tokens inString(, sub(, and Str1, if you rely on the input sitting in Ans before execution that would cut 5 bytes.
0
(['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"
([0..9]\\).map digitToInt
Uses set difference, unlike the other Haskell answer, type String -> Int
Call like
([0..9]\\).map digitToInt$"123467890" -- Outputs 5
0
->x{'0123456789'.tr x,''}
Not terribly competitive, I'm afraid
0
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!
,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
.
0
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.
0
@(a)477-a*~~a'
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]
0
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+"]","");}
0
#=0123456789
arg n
say verify(#,n)-1
0
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)
0
sort <(fold -1<<<$a;seq 0 9)|uniq -u
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.
0
0
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
0
Azv~a
##'Bzv~b
`^v##'Czv~c
*f|`^-##'Dzv~d
Z~'~e `^-##'
ZZZZZZZ~S
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:
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.
Add each code point in the string, masked with 0x0F
, ignoring carries.
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.
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:
#
elements do the addition described in step 2.z
elements near the adders carry over the current value to the next cycle so that we can have a running sum.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.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.)A
through D
are reading the 4 low bits of the input, and a
through d
write those same bits of the output.e
and f
provide the value 0x30
to the output as described in step 4.0
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).
0
{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.
0
Execution:
perl -pe '$_=/0/?9-$_%9:0'
perl -pe '$_=-hex($_)%15'
15 14 bytes of code + 1 byte for -p switch.
Explanation:
If 0
exists in the input, return 9 - modulo 9 of the input, otherwise return 0.
Interprets input as hex string, negates it, and calculates modulo 15 (based on xnor's Python answer).
0
{$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.
0
ɲdFḶṡạĖ⁻
ɲ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.
0
(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)
5@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. – James – 2017-03-27T19:48:24.173
@DJMcMayhem this is definitely a subset of that challenge though. It's not a superset, but most answers from the challenge can be trivially copied over. – Rɪᴋᴇʀ – 2017-03-27T19:48:40.320
10@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. – AdmBorkBork – 2017-03-27T19:50:36.260
3
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.
– AdmBorkBork – 2017-03-27T20:23:35.4571It'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. – Bijan – 2017-03-28T00:45:12.100
2Several answers take an integer as function input. Is that allowed? – Dennis – 2017-03-28T00:52:03.633
I can't technically 'return' an integer in SInclair ZX80 or ZX81 BASIC, but would it be okay to store the missing integer in a variable and printing that once I have returned from a sub-routine that will determine the missing variable? – Shaun Bebbers – 2017-03-28T13:17:23.420
Can I print the number twice? – Titus – 2017-03-30T09:08:09.083
Can I take input as a newline-separated string? – Pseudo Nym – 2019-12-12T22:23:06.753