Find the Missing Letter

27

2

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'

aimorris

Posted 2017-07-17T07:35:11.103

Reputation: 1 217

Can I take a string instead? – Leaky Nun – 2017-07-17T07:41:33.013

@LeakyNun Strings are arrays of characters, so yes. – aimorris – 2017-07-17T07:42:54.013

Will the first or the last ever go missing? – Leaky Nun – 2017-07-17T07:46:48.823

@LeakyNun No. I have edited the question to make it clearer. – aimorris – 2017-07-17T07:49:12.560

1Can 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? – Mr. Xcoder – 2017-07-17T08:59:51.567

1@Mr.Xcoder A string is just an array of characters, so yes – aimorris – 2017-07-17T09:02:30.443

@rahnema1 Completely different, but okay... – aimorris – 2017-07-17T09:03:25.743

Is a full program that reads from standard input and prints to standard output acceptable? And what about an anonymous code block / lambda function? Or a named stand-alone function, for languages that don't have "methods"? Or even just a code snippet that isn't wrapped in a block / lambda / function / method? (Quite a lot of the answers, including mine at the moment, seem to be of this type. In some languages with implicit I/O, such snippets are effectively indistinguishable from full programs.) – Ilmari Karonen – 2017-07-17T11:30:52.633

2Rule 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). – NH. – 2017-07-17T19:13:06.900

Answers

5

Pyth, 5 bytes

-rhQe

Try it online!

Leaky Nun

Posted 2017-07-17T07:35:11.103

Reputation: 45 011

11

C# (.NET Core), 48 47 46 bytes, input as char array

s=>{for(int i=0;s[++i]==++s[0];);return s[0];}

Try it online!

Explanation: the first element in the array is incremented as well as a pointer iterating the following elements. When both the first element and the current element are different, it returns the first element.

C# (.NET Core), 58 56 50 bytes, input as string

s=>{var c=s[0];while(s.IndexOf(++c)>=0);return c;}

Try it online!

Previous 58-byte solution (referenced in the first comment):

s=>{for(int i=1;;i++)if(s[i]-s[0]>i)return(char)(s[i]-1);}

Algorithms using System.Linq

The following algorithms must add using System.Linq; (18 bytes) to the byte count and therefore are longer.

I quite liked this one (52+18 bytes):

s=>{int i=0;return(char)(s.First(c=>c-s[0]>i++)-1);}

And you also have a one-liner (45+18)-byte solution:

s=>(char)(s.Where((c,i)=>c-s[0]>i).First()-1)

And a very clever (37+18)-byte solution, courtesy of Ed'ka:

s=>s.Select(e=>++e).Except(s).First()

Charlie

Posted 2017-07-17T07:35:11.103

Reputation: 11 448

1Won't this fail to compile with not all code paths return a value? But +1 for the comparison check with s[i]-s[0], pretty clever! – TheLethalCoder – 2017-07-17T08:35:34.200

@TheLethalCoder It won't fail as the for loop does not have a stop condition, so it will keep iterating until the if condition evaluates to true. – Charlie – 2017-07-17T08:38:57.420

Of course! Nice work. – TheLethalCoder – 2017-07-17T08:39:52.660

Turns out the full Linq version is just under double the bytes! – TheLethalCoder – 2017-07-17T08:57:35.020

I'm not sure, but if you switched from ++i to i++, you could probably omit <= in favor of <. – enedil – 2017-07-17T09:46:11.340

@enedil No, I can't, that would not yield the proper results. Try it online!

– Charlie – 2017-07-17T09:56:23.843

Can you do (char)--s[i] to save some bytes? – TheLethalCoder – 2017-07-17T10:55:13.980

1

You can save 8 bytes like this: a=>{int i=0;for(;a[++i]-a[0]<=i;);return--a[i];} (when you take the input as char[]). Not thanks to me btw, thanks to @Nevay's comment on my Java 8 answer.

– Kevin Cruijssen – 2017-07-17T11:12:45.127

1@KevinCruijssen found a way to save two more bytes taking the input as a char array. – Charlie – 2017-07-17T11:51:59.627

1Shorter Linq version: s=>s.Select(e=>++e).Except(s).First() – Ed'ka – 2017-07-20T10:57:00.753

8

Alice, 10 bytes

/X.
\ior@/

Try it online!

Explanation

This is just a framework for linear programs that operate entirely in Ordinal (string processing) mode:

/...
\.../

The actual linear code is then:

i.rXo@

Which does:

i   Read all input.
.   Duplicate.
r   Range expansion. If adjacent letters don't have adjacent code points, the
    intermediate code points are filled in between them. E.g. "ae" would turn
    into "abcde". For the inputs in this challenge, this will simply insert
    the missing letter.
X   Symmetric set difference. Drops all the letters that appear in both strings,
    i.e. everything except the one that was inserted by the range expansion.
o   Output the result.
@   Terminate the program.

Martin Ender

Posted 2017-07-17T07:35:11.103

Reputation: 184 808

7

Haskell, 33 30 bytes

f a=until(`notElem`a)succ$a!!0

Try it online!

Anders Kaseorg

Posted 2017-07-17T07:35:11.103

Reputation: 29 242

until saves a byte: f(a:b)=until(`notElem`a:b)succ a – xnor – 2017-07-17T08:31:47.563

@xnor 3 bytes, actually. Thanks! – Anders Kaseorg – 2017-07-17T08:45:25.507

7

Java 8, 70 57 56 48 46 bytes

a->{for(int i=0;++a[0]==a[++i];);return a[0];}

-14 (70 → 56) and -2 (48 → 46) bytes thanks to @CarlosAlejo.
-8 (56 → 48) bytes thanks to @Nevay.

Explanation:

Try it here.

a->{            // Method with char-array parameter and char return-type
  for(int i=0;  //  Start index-integer at 0 and loop as long as
    ++a[0]      //   the previous character + 1 (by modifying the character at index 0)
    ==a[++i];   //   equals the next character (by raising the index by 1 before checking)
  );            //  End of loop
  return a[0];  //  Return the now modified character at index 0 in the array
}               // End of method

Kevin Cruijssen

Posted 2017-07-17T07:35:11.103

Reputation: 67 575

1You can use an implicit cast instead of an explicit cast to save 8 bytes a->{int i=0;for(;a[++i]-a[0]<=i;);return--a[i];}. – Nevay – 2017-07-17T10:15:55.330

7

Ruby, 21 characters

->a{[*a[0]..a[-1]]-a}

Returns a single element array, according to question owner's comment.

Sample run:

irb(main):001:0> ->a{[*a[0]..a[-1]]-a}[['a','b','c','d','f']]
=> ["e"]

Try it online!

manatwork

Posted 2017-07-17T07:35:11.103

Reputation: 17 865

6

C (gcc), 33 35 36 48 60 bytes

All optimizations should be turned off and only on 32-bit GCC.

f(char*v){v=*v+++1-*v?*v-1:f(v);}

Take input as a string.

Try it online!

Keyu Gan

Posted 2017-07-17T07:35:11.103

Reputation: 2 028

2"All optimizations should be turned off and only on 32-bit GCC." is a very roundabout way of saying this doesn't work (only appears to work due to UB) – sehe – 2017-07-18T19:48:59.203

I'd say foo(char*a){return*a+1==a[1]?foo(a+1):++*a;} is pretty good; Only 1 char shorter than the more natural foo(char*a){while(*a+1==a[1])a++;return++*a;} – sehe – 2017-07-18T19:54:13.023

@sehe constant undefined behavior is considered acceptable on PPCG – Keyu Gan – 2017-07-19T03:07:44.977

5

Python 3, 74 62 58 44 40 bytes

-12 bytes thanks to Erik the Outgolfer. -18 bytes thanks to Leaky Nun. -4 bytes thanks to musicman523.

Takes input as a bytestring.

lambda s:chr(*{*range(s[0],s[-1])}-{*s})

Try it online!

Another cool solution:

lambda s:chr(*{*range(*s[::~-len(s)])}-{*s})

totallyhuman

Posted 2017-07-17T07:35:11.103

Reputation: 15 378

1.difference({*s}) -> -{*s} – Erik the Outgolfer – 2017-07-17T08:06:20.453

160 bytes – Leaky Nun – 2017-07-17T08:06:39.073

144 bytes with bytestring – Leaky Nun – 2017-07-17T08:09:19.753

12 more bytes – musicman523 – 2017-07-21T09:13:55.893

1Your solution is what I was after but in a far more elegant way – Pureferret – 2017-07-24T07:27:24.470

4

Mathematica, 46 bytes

Min@Complement[CharacterRange@@#[[{1,-1}]],#]&

J42161217

Posted 2017-07-17T07:35:11.103

Reputation: 15 931

I believe that Min@Complement[CharacterRange@@#[[{1,-1}]],#]& would save a byte. – LegionMammal978 – 2017-07-17T12:27:27.360

@LegionMammal978 actually 2! – J42161217 – 2017-07-17T12:45:50.800

3

JavaScript (ES6), 70 bytes

Input as a character array

(a,p)=>a.some(c=>(q=p+1,p=c.charCodeAt(),p>q))&&String.fromCharCode(q)

Less golfed

a=>{
  p = undefined;
  for(i = 0; c = a[i]; i++)
  {
    q = p+1
    p = c.charCodeAt()
    if (p>q)
      return String.fromCharCode(q)
  }
}

Test

F=(a,p)=>a.some(c=>(q=p+1,p=c.charCodeAt(),p>q))&&String.fromCharCode(q)

function update() {
  var a0=A0.value.charCodeAt()
  var a1=A1.value.charCodeAt()
  if (a1>a0) {
    var r = [...Array(a1-a0+1)]
      .map((x,i)=>String.fromCharCode(a0+i))
      .filter(x => x != AX.value)
    I.textContent = r.join('') + " => " + F(r)
  }
  else {
    I.textContent=''
  }
}

update()
input { width: 1em }
Range from <input id=A0 value='O' pattern='[a-zA-Z]' length=1 oninput='update()'>
to <input id=A1 value='T' pattern='[a-zA-Z]' length=1 oninput='update()'>
excluding <input id=AX value='Q' pattern='[a-zA-Z]' length=1 oninput='update()'>
<pre id=I></pre>

edc65

Posted 2017-07-17T07:35:11.103

Reputation: 31 086

3

PHP>=7.1, 46 bytes

Take input as string

<?=trim(join(range(($a=$argn)[0],$a[-1])),$a);

PHP Sandbox Online

Jörg Hülsermann

Posted 2017-07-17T07:35:11.103

Reputation: 13 026

3

Retina, 33 25 bytes

$
¶$_
T`p`_p`.*$
D`.
!`.$

Try it online! Works with any range of ASCII characters. Edit: Saved 8 bytes thanks to @MartinEnder. Explanation: The first stage duplicates the input. The second decreases all of the characters in the copy by 1 code point. The third stage deletes all of the characters in the copy that still appear in the original. This just leaves the original input, the character that precedes the first character of the original input and the missing character. The last stage then just matches the missing character.

Neil

Posted 2017-07-17T07:35:11.103

Reputation: 95 035

Here is 25, using the same basic idea: https://tio.run/##K0otycxL/P9fhevQNpV4rpCEgoT4ggQ9LRUulwQ9LsUEPZX///0DggA (I'm decrementing the second line because that saves a byte and then I'm finding the unique char using deduplication.)

– Martin Ender – 2017-07-17T14:00:54.533

@MartinEnder Deduplication is exactly what I wanted all along, and I already forgot Retina has it, sigh... (I know incrementing the first line takes a byte more than decrementing the second line but it made the match regex shorter.) – Neil – 2017-07-17T14:53:12.360

3

SWI Prolog, 124 bytes

m([H|T]):-n(H,N),c(T,N),!,m(T).
n(I,N):-o(I,C),D is C+1,o(N,D).
c([N|_],N).
c(_,N):-print(N),!,fail.
o(C,O):-char_code(C,O).

Examples:

?- m(['a','b','c','d','f']).
e
false.

?- m(['O','Q','R','S']).
'P'
false.

?- m(['x','z']).
y
false.

?- m(['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
false.

Little explanation:

The m is the "main" procedure,the n produces next expected character in the list. The c does comparison - if expectation matches the next item, continue, else print out expected character and jump out of the window.

Jan Drozen

Posted 2017-07-17T07:35:11.103

Reputation: 491

1Shorter than fail: 0=1. – mat – 2017-07-22T22:28:45.747

3

C++14, standard library, generic container type (87 86 bytes)

[](auto a){return++*adjacent_find(begin(a),end(a),[](auto a,auto b){return a+1!=b;});}

Container type from namespace ::std is assumed (e.g. std::string, std::list or std::vector. Otherwise using namespace std; or similar would be assumed.

Thanks to @Ven, with a little bit of preprocessor hacking, you get get it down to 82 bytes (1 newline)

#define x [](auto a,int b=0){return++
x *adjacent_find(begin(a),end(a),x a!=b;});}

See it Live On Coliru

C++14 no standard library (still generic, 64 63 bytes)

[](auto& a){auto p=*begin(a);for(auto c:a)if(c!=p++)return--p;}

Again, need to help name lookup only if container type not from namespace ::std (or associated with it)

Live On Coliru for std::string e.g.

Live On Coliru for char const[] e.g.

sehe

Posted 2017-07-17T07:35:11.103

Reputation: 360

You need to put a space between the strike-out text and the next text. – CJ Dennis – 2017-07-19T07:28:59.663

@CJDennis Done. By the way, your current rep (2469) is a beautiful number (being 3*823 and also visually paired as (24)(69) which is (2 2 2 3)(3 23)) – sehe – 2017-07-19T13:53:44.003

2

Charcoal, 18 bytes

Fγ¿¬∨∨‹ι⌊θ›ι⌈θ№θιι

Try it online! Link is to verbose version of code. Takes input as a string. Works with any almost contiguous sequence of ASCII characters.

Neil

Posted 2017-07-17T07:35:11.103

Reputation: 95 035

2

Rexx (Regina), 56 bytes

a=arg(1)
say translate(xrange(left(a,1),right(a,1)),'',a)

Try it online!

Finally one that enables REXX to use its strong string-manipulation.

theblitz

Posted 2017-07-17T07:35:11.103

Reputation: 1 201

2

C#, 104 bytes

using System.Linq;a=>(char)Enumerable.Range(a.Min(),a.Max()-a.Min()).Except(a.Select(c=>(int)c)).First()

Full/Formatted version:

using System.Linq;

namespace System
{
    class P
    {
        static void Main()
        {
            Func<char[], char> f = a =>
                (char)Enumerable.Range(a.Min(), a.Max() - a.Min())
                                .Except(a.Select(c=>(int)c))
                                .First();

            Console.WriteLine(f(new[] { 'a', 'b', 'c', 'd', 'f' }));

            Console.ReadLine();
        }
    }
}

TheLethalCoder

Posted 2017-07-17T07:35:11.103

Reputation: 6 930

A very clever Linq version by Ed'ka: s=>s.Select(e=>++e).Except(s).First()

– Charlie – 2017-07-20T11:13:45.197

@CarlosAlejo I saw you added it to your answer so I won't update mine but yes it is very clever. A lot shorter than my version of doing it. – TheLethalCoder – 2017-07-20T11:14:29.097

2

CJam, 6 bytes (full program) / 7 bytes (code block)

q),^W=

Try it online!

This is a full CJam program that reads the input string from standard input and prints the missing letter to standard output. CJam doesn't actually have "methods", which is what the challenge asks for, but the closest thing would probably be an executable code block, like this:

{),^W=}

Try it online!

This code block, when evaluated, takes the input as a string (i.e. an array of characters) on the stack, and returns the missing character also on the stack.


Explanation: In the full program, q reads the input string and places it on the stack. ) then pops off the last character of the input string, and the range operator , turns it into an array containing all characters with code points below it (including all letters before it in the alphabet). Thus, for example, if the input was cdfgh, then after ), the stack would contain the strings cdfg (i.e. the input with the last letter removed) and ...abcdefg, where ... stands for a bunch of characters with ASCII codes below a (i.e. all characters below the removed last input letter).

The symmetric set difference operator ^ then combines these strings into a single string that contains exactly those characters that appear in one of the strings, but not in both. It preserves the order in which the characters appear in the strings, so for the example input cdfg, the result after ),^ will be ...abe, where ... again stands for a bunch of characters with ASCII codes below a. Finally, W= just extracts the last character of this string, which is exactly the missing character e that we wanted to find (and discards the rest). When the program ends, the CJam interpreter implicitly prints out the contents of the stack.


Bonus: GolfScript, 6 bytes (full program)

),^-1>

Try it online!

It turns out that nearly the same code also works in GolfScript. We save one byte in the full program version due to GolfScript's implicit input, but lose one byte because, unlike CJam's W, GolfScript doesn't have a handy single-letter variable initialized to -1.

Also, CJam has separate integer and character types (and strings are just arrays containing characters), whereas GolfScript only has a single integer type (and has a special string type that behaves somewhat differently from normal arrays). The result of all this is that, if we want the GolfScript interpreter to print out the actual missing letter instead of its ASCII code number, we need to return a single-character string instead of just the character itself. Fortunately, making that change here just requires replacing the indexing operator = with the array/string left truncation operator >.

Of course, thanks to GolfScript's implicit I/O, the code above can also be used as a snippet that reads a string from the stack and returns a single-character string containing the missing letter. Or, rather, any snippet that takes a single string on the stack as an argument, and returns its output as a printable string on the stack, is also a full GolfScript program.

Ilmari Karonen

Posted 2017-07-17T07:35:11.103

Reputation: 19 513

6

Code snippets are not allowed by default; only functions and full programs are. So you probably need that q (program), or {...} (block). +1 for the approach though

– Luis Mendo – 2017-07-17T11:18:08.163

This is very clever! – Esolanging Fruit – 2017-07-19T09:12:43.380

2

JavaScript (ES6), 64 bytes

Takes input as a string.

s=>(g=p=>(c=String.fromCharCode(n++))<s[p]?p?c:g(p):g(p+1))(n=0)

How?

  • Initialization: We start with n = 0 and p = 0 and call the recursive function g().

    g = p =>                                   // given p
      (c = String.fromCharCode(n++)) < s[p] ?  // if the next char. c is not equal to s[p]:
        p ?                                    //   if p is not equal to zero:
          c                                    //     step #3
        :                                      //   else:
          g(p)                                 //     step #1
      :                                        // else:
        g(p + 1)                               //   step #2
    
  • Step #1: We increment n until c = String.fromCharCode(n) is equal to the first character of the input string s[0].

  • Step #2: Now that we're synchronized, we increment both n and p at the same time until c = String.fromCharCode(n) is not equal to s[p] anymore.

  • Step #3: We return c: the expected character which was not found.

Test cases

let f =

s=>(g=p=>(c=String.fromCharCode(n++))<s[p]?p?c:g(p):g(p+1))(n=0)

console.log(f('abcdf'))                     // -> 'e'
console.log(f('OQRS'))                      // -> 'P'
console.log(f('xz'))                        // -> 'y'
console.log(f('abcdefghijklmnopqrstuwxyz')) // -> 'v'

Arnauld

Posted 2017-07-17T07:35:11.103

Reputation: 111 334

2

MATL, 8 7 bytes

1 byte saved thanks to @Luis

tdqf)Qc

Try it at MATL Online

Explanation

      % Implicitly grab the input as a string
t     % Duplicate the string
d     % Compute the differences between successive characters
q     % Subtract 1 from each element
f     % Get the locations of all non-zero characters (1-based index)
)     % Extract that character from the string
Q     % Add one to get the next character (the missing one)
c     % Convert to character and display

Suever

Posted 2017-07-17T07:35:11.103

Reputation: 10 257

@LuisMendo Awesome, thanks! – Suever – 2017-07-17T13:31:08.990

2

Excel, 110 + 2 = 112 bytes

=CHAR(CODE(LEFT(A1))-1+MATCH(0,IFERROR(FIND(CHAR(ROW(INDIRECT(CODE(LEFT(A1))&":"&CODE(RIGHT(A1))))),A1),0),0))

Must be entered as an array formula (Ctrl+Shift+Enter) which adds curly brackets { } on each end, adding two bytes. Input is as a string in A1, which is OK per OP.

This is not the shortest answer by far (Excel rarely is) but I like seeing if it can be done.

Engineer Toast

Posted 2017-07-17T07:35:11.103

Reputation: 5 769

2

Python 2 - 76 bytes

Loses to existing python 2 solution but it's a slightly different approach so I thought I'd post it anyway:

lambda c:[chr(x)for x in range(ord(c[0]),ord(c[0]+26)if chr(x)not in c][0]

LangeHaare

Posted 2017-07-17T07:35:11.103

Reputation: 299

2

Husk, 6 bytes

→S-(ḣ→

Try it online!

This function takes a string (list of characters) as input, and returns a character as output.

Explanation

→S-(ḣ→
    ḣ→    Get the list of all characters from the null byte to the last character of the input
 S-       Subtract the input from this list
→         Get the last element of the result

Leo

Posted 2017-07-17T07:35:11.103

Reputation: 8 482

2

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>

Chaos Manor

Posted 2017-07-17T07:35:11.103

Reputation: 521

1

05AB1E, 9 7 bytes

ǤÝsKçθ

Try it online!

Erik the Outgolfer

Posted 2017-07-17T07:35:11.103

Reputation: 38 134

I'm going to judge from the 2 that we're using the same algorithm, even though I hardly know 05AB1E :) – Leaky Nun – 2017-07-17T07:51:45.073

@LeakyNun Well, I thought of the algorithm too... – Erik the Outgolfer – 2017-07-17T07:53:04.407

I just changed my algorithm though. – Leaky Nun – 2017-07-17T07:53:32.383

@LeakyNun It'd be longer in 05AB1E anyways. – Erik the Outgolfer – 2017-07-17T07:57:13.673

I just thought of another algorithm that contains 2, might be yours...

– Leaky Nun – 2017-07-17T07:59:49.657

@LeakyNun Nah as I said above it's the deltas thingy. – Erik the Outgolfer – 2017-07-17T08:04:23.060

1

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

Jonas Wilms

Posted 2017-07-17T07:35:11.103

Reputation: 131

1bind ??? in code golf ? – edc65 – 2017-07-17T09:23:26.397

@edc65 whats wrong with it ? ( sorry if this is n00b, but thats my first golf :)) – Jonas Wilms – 2017-07-17T09:27:19.533

@edc65 but youre probably right, removing it saved 4 bytes... – Jonas Wilms – 2017-07-17T09:42:44.167

a.join("") could be a.join`` – user2428118 – 2017-07-17T10:48:59.560

1

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!

Jonah

Posted 2017-07-17T07:35:11.103

Reputation: 8 729

That looks like a snippet to me. – Adám – 2017-07-17T11:31:48.493

@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). – zgrep – 2017-07-17T14:01:57.850

@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 – Jonah – 2017-07-17T14:39:27.453

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. – Adám – 2017-07-17T15:09:05.950

@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. – Adám – 2017-07-17T15:10:17.867

@Adám noted, thx. sort of unfortunate rule for J but Ill keep it in mind going forward – Jonah – 2017-07-17T15:38:21.080

@Adám Oh. So I see. You make a fair and valid point. – zgrep – 2017-07-17T19:12:06.083

19: ({.@-.~>:)&.(a.&i.) – Ed'ka – 2017-07-20T10:58:55.990

@Ed'ka very nice! – Jonah – 2017-07-20T14:23:32.517

1

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!

Renzo

Posted 2017-07-17T07:35:11.103

Reputation: 2 260

1

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.

mdahmoune

Posted 2017-07-17T07:35:11.103

Reputation: 2 605

1

APL (Dyalog), 17 bytes

(⊃⎕AV/⍨∨\∧~)⎕AV∘∊

Try it online!

⎕AV∘∊ Boolean: each character in the Atomic Vector (character set) member of the argument?

() apply the following tacit function:

 the first element of

⎕AV the Atomic Vector (the character set)

/⍨ which

∨\ follows the initial (member of the argument)

 but

~ is not (a member of the argument)

Adám

Posted 2017-07-17T07:35:11.103

Reputation: 37 779

1

PHP, 43 bytes

for($x=$argn[0];$argn[++$i]==++$x;);echo$x;

user63956

Posted 2017-07-17T07:35:11.103

Reputation: 1 571

For those curious to try this: the code expects a single string on STDIN. – manatwork – 2017-07-17T12:10:52.793

Doesn't php need <? to switch from echoing the input to running real code? – manassehkatz-Moving 2 Codidact – 2017-07-18T16:48:23.690

1

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!

V. Courtois

Posted 2017-07-17T07:35:11.103

Reputation: 868

1

05AB1E, 5 bytes

ÇŸçsK

Uses the 05AB1E encoding. Try it online!

Adnan

Posted 2017-07-17T07:35:11.103

Reputation: 41 965

You're supposed to just return the missing character :P. – Magic Octopus Urn – 2017-07-17T16:32:15.250

ÇŸçsSK works though. – Magic Octopus Urn – 2017-07-17T16:33:07.097

1

Python 3, 42 bytes

f=lambda a,*r:r[0]-a>1and chr(a+1)or f(*r)

Try it online!

Uses unpacked bytestring as input: f(*b'OQRS')

Felipe Nardi Batista

Posted 2017-07-17T07:35:11.103

Reputation: 2 345

1

k, 17 bytes

{`c$-1+x@&2=-':x}

Try it online!

Explanation:

{               } /function(x)
            -':x  /create a list of differences/deltas
          2=      /check for equality with 2, result is boolean list
         &        /get indices of all 1s (there should only be one)
       x@         /get letter at said index in our string
    -1+           /go back one letter
 `c$              /cast to character

zgrep

Posted 2017-07-17T07:35:11.103

Reputation: 1 291

1

Japt, 14 bytes

mc
g oUo¹kU md

Try it online!

Oliver

Posted 2017-07-17T07:35:11.103

Reputation: 7 160

1

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

Titus

Posted 2017-07-17T07:35:11.103

Reputation: 13 814

1

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.

James

Posted 2017-07-17T07:35:11.103

Reputation: 54 537

1

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.

Pureferret

Posted 2017-07-17T07:35:11.103

Reputation: 960

1

R, 67 bytes

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

Try it online!

Maxim Mikhaylov

Posted 2017-07-17T07:35:11.103

Reputation: 571

this only works if the first letter of the array is 'a' because if by default only checks the first value of the array! – Giuseppe – 2017-07-18T14:17:06.327

@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! – Maxim Mikhaylov – 2017-07-18T14:31:06.227

1

Octave, 34 32 bytes

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

Anonymous function; returns the missing character.

Try it online!

Giuseppe

Posted 2017-07-17T07:35:11.103

Reputation: 21 077

1

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

Joshua

Posted 2017-07-17T07:35:11.103

Reputation: 231

1

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.)

Cody Gray

Posted 2017-07-17T07:35:11.103

Reputation: 2 639

1

><>, 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

Teal pelican

Posted 2017-07-17T07:35:11.103

Reputation: 1 338

0

Jelly, 7 bytes

.ịOr/Ọḟ

Try it online!

Leaky Nun

Posted 2017-07-17T07:35:11.103

Reputation: 45 011

0

Mathematica, 83 bytes

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

input

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

J42161217

Posted 2017-07-17T07:35:11.103

Reputation: 15 931

0

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!

Dom Hastings

Posted 2017-07-17T07:35:11.103

Reputation: 16 415

0

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

Richard Donovan

Posted 2017-07-17T07:35:11.103

Reputation: 87

0

const missed=ar=>String.fromCharCode(ar.reduce((a,v)=>a+1!==v.charCodeAt()?a:v.charCodeAt(),ar[0].charCodeAt())+1)

JSwindin

Posted 2017-07-17T07:35:11.103

Reputation: 1

1Hello, 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. – NoOneIsHere – 2017-07-22T15:30:30.523

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? – aimorris – 2017-07-22T19:55:24.753