34
\$\begingroup\$

Guidelines

Task

Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array (lists in some languages).


Rules

  • This is code golf so the shortest answer in bytes wins!
  • You will always get a valid array
  • There will always be exactly one letter missing
  • The length of the array will always be at least 2.
  • The array will always contain letters in only one case (uppercase or lowercase)
  • You must output in the same case (uppercase or lowercase) that the input is
  • The array will always only go one letter a time (skipping the missing letter)
  • The array length will be between 2 and 25
  • The first or last element of the array will never be missing

Examples

['a','b','c','d','f'] -> 'e'

['O','Q','R','S'] -> 'P'

['x','z'] -> 'y'

['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'] -> 'v'

\$\endgroup\$
10
  • \$\begingroup\$ Can I take a string instead? \$\endgroup\$
    – Leaky Nun
    Jul 17, 2017 at 7:41
  • \$\begingroup\$ @LeakyNun Strings are arrays of characters, so yes. \$\endgroup\$
    – aimorris
    Jul 17, 2017 at 7:42
  • 1
    \$\begingroup\$ Can the output be an array containing the missing character (e.g: for the input ['a','b','c','d','f','g'], output ['e'], if that makes the code shorter? \$\endgroup\$
    – Mr. Xcoder
    Jul 17, 2017 at 8:59
  • 1
    \$\begingroup\$ @Mr.Xcoder A string is just an array of characters, so yes \$\endgroup\$
    – aimorris
    Jul 17, 2017 at 9:02
  • 3
    \$\begingroup\$ Rule four is simply a subset of rule eight and can be removed (at least, if you put the word "inclusive" at the end of rule eight). \$\endgroup\$
    – NH.
    Jul 17, 2017 at 19:13

59 Answers 59

1
2
1
\$\begingroup\$

J, 20 bytes

{&a.>:I.1 0 1&E.a.e.
  • a.e. boolean mask for the input letters across ascii charset
  • 1 0 1&E. new boolean mask indicating if the sequence 101 begins at that index, ie, find any place a "skip" sequence begins
  • I. the index of that match, ie, the character before the skipped one
  • >: increment by 1, ie, the index of the skipped char within ascii charset
  • {&a. pick that index from the ascii charset, ie, return the skipped char

Try it online!

\$\endgroup\$
9
  • \$\begingroup\$ That looks like a snippet to me. \$\endgroup\$
    – Adám
    Jul 17, 2017 at 11:31
  • \$\begingroup\$ @Adám It's written in a tacit (point-free) style, which I believe counts as "function-like" as opposed to a snippet. As best as I can tell, it's no more of a snippet than your APL solution is (but I do not know dyalog, so take what I say with a grain of salt). \$\endgroup\$
    – zgrep
    Jul 17, 2017 at 14:01
  • \$\begingroup\$ @Adám yes it is, in the sense that it can’t be assigned to a variable but assumes input on its right side. is this not legal? i asked about it somewhere and was told it was fine \$\endgroup\$
    – Jonah
    Jul 17, 2017 at 14:39
  • \$\begingroup\$ My understanding for APL/J/K is that the code must be able to reside in a name, whether by assignment or as the body an explicit verb/function (however, the explicit form must then have explicit input too). Snippet is code which assumes values in variables and/or needs pasting into a line, but cannot stand on their own. \$\endgroup\$
    – Adám
    Jul 17, 2017 at 15:09
  • \$\begingroup\$ @zgrep No, this code is explicit (non-tacit), but is missing the reference to its argument on the far right. My APL function is a complete tacit function which can assigned or put in a parenthesis. \$\endgroup\$
    – Adám
    Jul 17, 2017 at 15:10
1
\$\begingroup\$

ES6, 125 bytes:

(a=>((s,f)=>(r=(i,b)=>a[i]?r(i+1,b||(s[f](i)-s[f](i-1)-1&&String.fromCharCode(s[f](i-1)+1))):b)(1,0))(a.join(""),"charCodeAt"))

http://jsbin.com/vasoqidawe/edit?console

The returned function needs to be called with an array

(["a","c"])

one could save another 9 bytes through removing .join("") and passing a string:

("ac")

ES6, 108 bytes:

(a=>((s,f,o)=>(a.find((_,i)=>(o?++o:o=s[f](i))!==s[f](i)),String.fromCharCode(o)))(a.join(""),'charCodeAt'),0))

http://jsbin.com/tudiribiye/edit?console

\$\endgroup\$
4
  • 1
    \$\begingroup\$ bind ??? in code golf ? \$\endgroup\$
    – edc65
    Jul 17, 2017 at 9:23
  • \$\begingroup\$ @edc65 whats wrong with it ? ( sorry if this is n00b, but thats my first golf :)) \$\endgroup\$ Jul 17, 2017 at 9:27
  • \$\begingroup\$ @edc65 but youre probably right, removing it saved 4 bytes... \$\endgroup\$ Jul 17, 2017 at 9:42
  • \$\begingroup\$ a.join("") could be a.join`` \$\endgroup\$ Jul 17, 2017 at 10:48
1
\$\begingroup\$

Common Lisp, 88 bytes

(lambda(s)(loop as(x y)on s if(>(#1=char-code y)(1+(#1#x)))return(code-char(1+(#1#x)))))

Try it online!

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

Python 2, 69 bytes

lambda a:chr((ord(a[0])+ord(a[-1]))*-~len(a)/2-sum(ord(x)for x in a))

Try it online!

Some explanations As we know the first and the last elements of the list, we can easily compute the sum of the codes of all the chars in the list + the missed char (using summary formulas of arithmetic progression). The difference between this sum and the sum of the codes of all the chars in the list gives the code of the missed letter.

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

05AB1E, 9 7 bytes

ǤÝsKçθ

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ I'm going to judge from the 2 that we're using the same algorithm, even though I hardly know 05AB1E :) \$\endgroup\$
    – Leaky Nun
    Jul 17, 2017 at 7:51
  • \$\begingroup\$ @LeakyNun Well, I thought of the algorithm too... \$\endgroup\$ Jul 17, 2017 at 7:53
  • \$\begingroup\$ I just changed my algorithm though. \$\endgroup\$
    – Leaky Nun
    Jul 17, 2017 at 7:53
  • \$\begingroup\$ @LeakyNun It'd be longer in 05AB1E anyways. \$\endgroup\$ Jul 17, 2017 at 7:57
  • \$\begingroup\$ I just thought of another algorithm that contains 2, might be yours... \$\endgroup\$
    – Leaky Nun
    Jul 17, 2017 at 7:59
1
\$\begingroup\$

PHP, 43 bytes

for($x=$argn[0];$argn[++$i]==++$x;);echo$x;
\$\endgroup\$
2
  • \$\begingroup\$ For those curious to try this: the code expects a single string on STDIN. \$\endgroup\$
    – manatwork
    Jul 17, 2017 at 12:10
  • \$\begingroup\$ Doesn't php need <? to switch from echoing the input to running real code? \$\endgroup\$ Jul 18, 2017 at 16:48
1
\$\begingroup\$

Scala, 63 chars, 63 bytes

for(i<-1 to t.size-1)if(t(i-1)+1!=t(i))return (t(i)-1).toChar
0

See TIO link for tests. t is the input (a String), and I output a char. I tried doing it with a string (like this) but I don't think it is correct to output the code of the missing char. This would make the code 3 bytes shorter.

Try It Online!

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

05AB1E, 5 bytes

ÇŸçsK

Uses the 05AB1E encoding. Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ You're supposed to just return the missing character :P. \$\endgroup\$ Jul 17, 2017 at 16:32
  • \$\begingroup\$ ÇŸçsSK works though. \$\endgroup\$ Jul 17, 2017 at 16:33
1
\$\begingroup\$

Japt, 14 bytes

mc
g oUo¹kU md

Try it online!

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

PHP, 44 bytes

operating on separate command line arguments:

for($c=$argv[1];++$c==$argv[-~++$i];)echo$c;            # 44 bytes
for($c=$argv[$i=1];++$c==$argv[++$i];)echo$c;           # 45 bytes
<?=end(array_diff(range($argv[1],end($argv)),$argv));   # 53 bytes
<?=trim(join(range($argv[1],end($argv))),join($argv));  # 54 bytes
\$\endgroup\$
1
\$\begingroup\$

Brain-Flak, 45 bytes

{([{}()]({})){{}({}<>)((<()>))}{}}{}({}[()])

Try it online!

44 bytes of code, and +1 byte for the -c flag.

Surprisingly short for a language terrible at manipulating strings.

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

Python 3, 92 bytes

from string import *; f=lambda s:{*[a for a in ascii_letters if a>=s[0] and a<=s[-1] ]}^{*s}

Try it online!

Long solution but I like how sets work, and it seemed shorter in my head.

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

R, 67 bytes

l=letters;L=LETTERS;a=scan(,'');`if`(a==l&&T,l[a!=l][1],L[a!=L][1])

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ this only works if the first letter of the array is 'a' because if by default only checks the first value of the array! \$\endgroup\$
    – Giuseppe
    Jul 18, 2017 at 14:17
  • \$\begingroup\$ @Giuseppe Hmm.. Now when I am looking at my code that I wrote a day ago, I am not sure what I meant when checking if a==l&&T is true :) Thanks for pointing out the mistake! \$\endgroup\$ Jul 18, 2017 at 14:31
1
\$\begingroup\$

Octave, 34 32 bytes

@(x)char(setdiff(x(1):max(x),x))

Anonymous function; returns the missing character.

Try it online!

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

x86 Machine Code, 11 bytes

8A 11
41
8A 01
48
38 C2
74 F6
C3  

The above bytes define a function in 32-bit x86 machine code that finds the missing letter. It takes a single parameter, which is a pointer to the first element of a character array. (The length of the array is not needed, and the character array need not be NUL-terminated.)

The function uses the fastcall calling convention, where its parameter is passed in the ECX register. (It isn't essential that this calling convention or ECX be used for the input; we just need a register-based calling convention. You could trivially modify the code to take input in any register.)

The return value (the missing character) is returned in the AL register (low byte of EAX).

Note that characters are assumed to be 1 byte in length. This is perfectly sufficient for 8-bit ASCII characters, but is obviously not guaranteed to work on Unicode characters. The challenge doesn't specify, and the sample inputs only show basic ASCII. The whole world is ASCII, right?

Ungolfed assembly mnemonics:

; char FindMissingChar(char *letters);
Top:
    mov     dl, BYTE PTR [ecx]    ; load nth character from array
    inc     ecx                   ; increment pointer
    mov     al, BYTE PTR [ecx]    ; load n+1th character from array
    dec     eax                   ; decrement AL (shorter than 'dec al')
    cmp     dl, al                ; compare these two characters
    je      L2                    ; keep looping if n+1 is the char expected to follow n
    ret                           ; otherwise, return with the missing character in AL

Try it online!
(The TIO link passes the -m32 switch to GCC to ensure that it is compiling in 32-bit mode, and also applies an attribute to ensure the compiler uses the correct calling convention.)

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

><>, 12 bytes

i/o;
?/1+:i-

Try it online!

Explanation

i/o;
?/1+:i-

i/            | Push 1 byte input to the stack then move to second line
 /1+:         | Add 1 to the stack top then duplicate it
     i-       | Push 1 byte input and take from the stack top
?/            | Check stack top is 0, if not 0 move back to line 1
 /o;          | Print the stack top
\$\endgroup\$
1
\$\begingroup\$

8th, 99 bytes

Rationale

If the distance between letters is greater than two, then there is a missing letter. Letter distance is obtained by computing the difference between ASCII code of each letter.

Code

: f ' nip s:each repeat over n:- 2 n:= if n:1+ "" swap s:+ . reset 1 then depth n:1- while! reset ;

Ungolfed version

: f \ s -- c 
  ' nip s:each    \ convert each letter into its ASCII code and put them on stack
  repeat
    over
    n:- 2 n:=     \ check if there is a missing letter 
    if            
      n:1+        \ compute the ASCII code of missing letter
      "" swap s:+ \ convert ASCII code into printable character
      .           \ print out the missing letter
      reset 1     \ set condition to exit from while!
    then
    depth n:1-    \ verify if there are letters to check
  while!          
  reset           \ clean stack
;

Usage and examples

ok> "abcdf" f
e
ok> "OQRS" f
P
ok> "xz" f
y
ok> "abcdefghijklmnopqrstuwxyz" f
v
ok> "ab" f

ok> "def" f

ok>
\$\endgroup\$
1
\$\begingroup\$

Clojure, 102 89 bytes

#(nth(filter(fn[a](not(some #{a}%)))(map char(range(int(first %))(inc(int(last %)))))) 0)

Anonymous function, takes a string as parameter and returns the first missing character.

Seems like clojure ain't that good for golfin'...

Edit: Stripped whitespace and used nth ... 0 instead of first

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

Japt -h, 6 bytes

â¡Îc+Y

Try it

â¡Îc+Y     :Implicit input of array U
â          :Setwise union with
 ¡         :Map each 0-based index Y in U
  Î        :  First element of U
   c       :  Codepoint
    +Y     :  Add Y
           :Implicit output of last element
\$\endgroup\$
1
\$\begingroup\$

Python 3, 62 bytes

Outgolfed, but has a clean string interface :)

def f(s,i=0):a=chr(ord(s[0])+i);return a==s[i]and f(s,i+1)or a

Try it online!

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

Factor + math.unicode, 29 bytes

[ dup minmax [a,b] swap ∖ ]

Try it online!

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

PowerShell Core, 36 bytes

param($a)$a[0]..$a[-1]|?{$_-notin$a}

Try it online!

Takes the chars as an array of strings

$a[0]..$a[-1]  # creates a range from the first to the last character in the argument
|?{$_-notin$a} # keeps only the character that is not in the argument
\$\endgroup\$
1
\$\begingroup\$

J, 18 bytes

{.@(>:-.])&.(3&u:)

Same approach as many others.

Try it online!

{.@(>:-.])&.(3&u:)
            (3&u:)  NB. convert to char codes
    >:              NB. increment
        ]           NB. input
      -.            NB. set difference
  @                 NB. then
{.                  NB. take the head
          &.        NB. lastly, perform the inverse of 3&u:, which converts back to char
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 83 bytes

T=ToCharacterCode;FromCharacterCode[T@#[[Position[Differences@T@#,{2}][[1,1]]]]+1]&

input

[{"a","b","c","d","f"}]

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

Perl, 39 bytes

33 bytes code + 6 for -nalF.

print grep"@F"!~$_,$F[0]..$F[$#F]

Explanation

Creates a list of first character to last character and strips out any items that exist in the source string.

Try it online!

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

J,30 bytes - till I can get rid of more parentheses!

a.{~((([:i.#)+/a.i.{.)-.a.i.])       'abcef'

Returns d

 a.{~     take from 
 ((([:i.#) number of input bytes
 +/a.i.{.) starting from 2nd input byte
 -.a.i.]) subtract all but missing character from input

Or, a byte longer (31), completely different method but perhaps more elegantly?

a.{~<:a.i.t#~0,~<:2-/\a.i.t=:|.           'STUVX'

    returns W
\$\endgroup\$
0
\$\begingroup\$
const missed=ar=>String.fromCharCode(ar.reduce((a,v)=>a+1!==v.charCodeAt()?a:v.charCodeAt(),ar[0].charCodeAt())+1)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Hello, and welcome to PPCG! What language is this, and how many bytes? If you don't know the bytes, I'm here to help. Just type @NoOneIsHere, and your question, into a comment. \$\endgroup\$ Jul 22, 2017 at 15:30
  • \$\begingroup\$ Welcome to PPCG! Here are a few tips to help you: You should use 'f' for the name of an functions or variables as it reduces bytes. Also, you should add the language and the byte count above your code. If I am correct, this is Java? \$\endgroup\$
    – aimorris
    Jul 22, 2017 at 19:55
0
\$\begingroup\$

Vyxal g, 5 bytes

C›C?F

Try it Online!

Explanation

C›C?F  # Implicit input
C      # Convert to charcodes
 ›     # Increment
  C    # Convert from charcodes
   ?F  # Remove elements which are in the input
       # g flag gets minimum (first) element
\$\endgroup\$
0
\$\begingroup\$

Thunno 2 BM, 3 bytes

⁺$ṗ

Attempt This Online!

Port of my Vyxal answer.

Explanation

⁺$ṗ  # Implicit input, converted to ordinals by B flag
⁺    # Increment each ordinal in the list
 $   # Push the input (as an ordinal list) again
  ṗ  # Set difference between the incremented and original lists
     # Implicit output of minimum ordinal as a character
\$\endgroup\$
1
2

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.