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
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.
Sign up to join this communityYou 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
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.
477SSm8[a+A{]x-n
<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
{$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.
\011.t.w0.i.-.+.m\001.-.c.t.a\055.-.n
Try it online! (with pxem.posixism)
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
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
žhsм
ž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.
[9876543210]$v[v'$>,<]v*'#<^v'.>1#########^0123456789
[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
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
rsi
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
ax
477
, not 221
.
\$\endgroup\$
Jan 12 at 11:44
dl
, or if you want to return whole eax
, movzx eax, dl
is only 2 bytes more, mov
saves 3 bytes
\$\endgroup\$
push 9/pop rcx/mov dl,221/lodsb/sub edx,eax/loop $-3/movzx eax,dl/ret
\$\endgroup\$
`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.
(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)
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
10,`^~
There's a shorter, 4-byte solution if input can be taken in the form of an array of integers:
10,^
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 ~
->x{'0123456789'.tr x,''}
Not terribly competitive, I'm afraid
(['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
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
.
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.
@(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]
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+"]","");}
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)
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.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).
{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.
(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)
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
ɲ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.
ɳą←ą\
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
Ś9△-~
Takes input without quotes
Ś implicit input; sum of digits
9△ 45 (9th triangle number)
- subtract
~ negate; implicit print