내 중간 이름은 무엇입니까?


30

참고 : 당첨 답변은 4/12/17에 선택되며 현재 당첨자는 Jolf, 1 byte 입니다.

이 사이트에서 아직 중간 이름의 도전 과제가 없었던 것에 놀랐습니다. 나는 많은 검색을했지만 아무것도 찾지 못했습니다. 이것이 dup 인 경우이를 플래그로 지정하십시오.

당신의 도전

보이는 문자열을 구문 분석 Jo Jean Smith하고 반환 Jean합니다.

테스트 사례

Input: Samantha Vee Hills
Output: Vee

Input: Bob Dillinger
Output: (empty string or newline)

Input: John Jacob Jingleheimer Schmidt
Output: Jacob Jingleheimer

Input: Jose Mario Carasco-Williams
Output: Mario

Input: James Alfred Van Allen
Output: Alfred Van 

(마지막으로 기술적으로 올바르지는 않지만 수정하기가 너무 어렵습니다.)

노트:

  • 이름은 항상 2 개 이상의 공백으로 구분 된 부분을 가지며 중간 이름은 무제한이며 문자열 목록 / 배열 일 수 있습니다.
  • 이름은 알파벳 (대소 문자 구분)과-( 0x2d)를 포함 할 수 있습니다
  • 후행 줄 바꿈을 출력 할 수 있습니다.
  • 후행 줄 바꿈을 사용하려면 입력이 필요할 수 있습니다.
  • STDIN, 함수 매개 변수 또는 명령 행 인수의 입력은 허용되지만 하드 코딩은 허용되지 않습니다.
  • 표준 허점은 금지되어 있습니다.
  • 함수 반환 값, STDOUT, STDERR 등이 출력 될 수 있습니다.
  • 출력의 후행 공백 / 개행 / 탭이 허용됩니다.
  • 질문 있나요? 아래의 코멘트!

이것은 이므로 바이트 단위의 최단 응답자가 이깁니다!


2
출력이 문자열 목록이 될 수 있습니까?
Anthony Pham

5
공백으로 구분 된 문자열 이외의 다른 형식이 허용되는 경우 해당 형식을 사양으로 편집하십시오.
Martin Ender

5
@ programmer5000 : 입력이 문자열 목록이 될 수 있다면 출력은 어떻습니까? 인가 ["John", "Jacob", "Jingleheimer", "Schmidt"]> - ["Jacob", "Jingleheimer"]올바른 해결책은?
nimi

3
선행 공백이 허용됩니까?
betseg

2
@DJ "Van"은 그의 중간 이름이 아니기 때문에 그의 성의 일부입니다. 특히 까다로운 사례는 David Lloyd George입니다. 그의 이름은 David이고 성은 Lloyd George입니다. 이와 같이 실제 사람들의 이름을 파싱하려는 시도는 끝났습니다. 사실, 당신은 이름과 성이 무엇인지 알 수조차 없습니다 (리시를 생각하십시오).
David Conrad

답변:


4

줄프, 1 바이트

입력 내부를 가져옵니다. 여기 사용해보십시오!


예제를 실행할 수없는 것 같습니다. 버튼을 클릭해도 아무 일도 일어나지 않는 것 같습니다. Chrome 사용 57.0.2987.133

@YiminRong 나는 단지 firefox에서 작동하도록 보장 할 수 있습니다.
Conor O'Brien

44

, 2 바이트 (CP437)

문자열 목록을 승인하고 리턴합니다.

()

설명:

()   Main wire, arguments: a

(    Remove the first element of a
 )   ...and then the last element of that
     Implicit output

10
내가 생각하는 직업에 맞는 도구
Rohan Jhunjhunwala

15

Vim, 6 5 바이트

dW$BD

온라인으로 사용해보십시오!

(후행 공백이있는 출력)

Vim은 V와 역 호환되므로 V에 대한 TIO 링크를 포함 시켰습니다.

설명

dW                      " Delete up to the next word (removes the first name)
$                       " Go to the end of the line
B                       " Go back one word
D                       " Delete it

드랏, 넌 날 이겼어 dWWD1 바이트를 절약합니다.
DJMcMayhem

5
@DJMcMayhem 정확히 하나의 중간 이름에서만 작동합니다.
Martin Ender

dW와 dw의 차이점은 무엇입니까?
Duncan X Simpson

1
@DuncanXSimpson은 dW공백까지 삭제합니다. dw단어가 아닌 문자까지 삭제합니다.
기금 모니카의 소송

14

파이썬 , 24 바이트

lambda n:n.split()[1:-1]

온라인 문자열 입력을 사용해보십시오!

입력 형식 : 문자열


파이썬 2 , 16 바이트

lambda n:n[1:-1]

온라인 목록 입력을 시도하십시오!

입력 형식 : 목록


당신과 함께 제목을 편집해야 Python하는 대신 Python 2이 작동하기 때문에, Python 3뿐만 아니라, 단지에 대한이 게시하는 것이었다.
Mr. Xcoder

OP가 출력 형식을 언급하지 않았기 때문에 @ L3viathan must be a string입력 형식이 목록이 될 수 있으므로 목록을 인쇄하면 잘못된 결과로 간주 될 수 없습니다!
Keerthana Prabhakaran

질문에 대한 의견에 따르면 문자열 목록을 입력하고 출력 할 수 있습니다. 많은 바이트를 저장lambda n:n[1:-1]
루크 Sawczak

1
STDIN에서 읽을 수 있으므로 람다를 input()(Python 3 전용)으로 대체 할 수 있습니다.
BallpointBen

네 말이 맞아 감사. 수정 사항을 추가했습니다!
Keerthana Prabhakaran

13

Brain-Flak , 133 바이트

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

온라인으로 사용해보십시오!

132 바이트의 코드와 -cASCII 입력 및 출력을 허용 하는 플래그의 경우 1 바이트

불행히도 여기에는 중복 된 코드가 많이 포함되어 있지만 재사용하기가 정말 어렵습니다. 나중에 살펴 보겠습니다. 여기에 설명이 있습니다 :

#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

86 bytes when you remove the comments. I added the first two and the last line. TIO
Riley

@riley Cool solution. Feel free to post it yourself!
DJMcMayhem


12

Haskell, 23, 17 9 bytes

init.tail

Takes and returns a list of strings. Try it online!

Drop first string, drop last string.

Edit: @Generic Display Name noted, that the input can be a list of strings, which saved 6 bytes.

Edit II: return list of strings instead of a single string


It looks like input as a list is allowed, so drop the words for -5 bytes
Generic Display Name

@GenericDisplayName: Oh, didn't notice. Thanks!
nimi

My Ohm answer and the Mathematica answer both output lists of strings as well, so you could probably drop unwords. for -8 bytes.
Nick Clifford

@NickClifford: yes, I saw that myself and asked the OP for clarification.
nimi

11

Mathematica, 10 bytes

Rest@*Most

An unnamed function that accepts and returns a list of strings.

Rest discards the the last element, Most discards the first element, @* is function composition. Swapping Rest and Most or using right-composition /* instead would also work. This beats indexing via #[[2;;-2]]& by one byte.


10

Brain-Flak, 86 bytes

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

Try it online!

Most of this code comes from this answer. If you like my solution you should upvote that one as well.

#Push 2
(()())

#Loop twice
{({}[()]<

  #While not a space
  {
      #Pop
      {}

      #Not equals 32
      ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

  #Endwhile
  }

  #Pop the 0
  {}

  #Reverse Stack
  {({}<>)<>}<>

#End loop twice
>)}{}

Well done! I didn't think about holding a counter for pushing later, so I spent too long thinking about how to loop across different stacks.
DJMcMayhem

8

Java 7, 74 bytes

String f(String s){return s.substring(s.indexOf(' '),s.lastIndexOf(' '));}

Java 8, 49 bytes

s->s.substring(s.indexOf(' '),s.lastIndexOf(' '))

Function which identifies the first occurrence of the space character and the last one and extracts the middle. The resulting string is prefixed by a space character (at the time of the posting, OP hasn't clarified if leading spaces are allowed), which can be eliminated by adding .trim() to the code for an extra cost of 7 bytes.

Compared to C#, Java has the advantage of specifying the end index instead of sub-string length, which brings down the byte count.


7

JavaScript (ES6), 22 bytes

Takes and outputs an array of strings.

([_,...a])=>a.pop()&&a

Test cases

String version (27 bytes)

Takes and outputs a string. The output string is either a single space if no middle name was found, or the middle names with leading and trailing spaces.

s=>(/ .* /.exec(s)||' ')[0]


/./.exec.bind(/ .* /) seems to mimic #2, except null for none
dandavis

7

AWK, 17 10 bytes

Saved 7 bytes thanks to @steve!

$NF=$1=x;1

Try it online!

Explanation:

$NF=    set last word to
$1=     set first word to
x       an empty variable, ie empty string
1       default action, ie print everything

Can be shaved down to 11 bytes, $NF=$1="";1
steve

3
Or 10 using $NF=$1=x;1
steve

1
@steve what does 1 do? I'm not so good at AWK :)
betseg

1 just means take the default action, that is, to print $0.
steve

6

Groovy, 19 bytes

{it.split()[1..-2]}

Explanation:

{        
 it                  all closures have an implicit argument called "it"
   .split()          splits by spaces by default. Returns an array of words
           [1..-2]   take the whole array from the second index (1) to the penultimate index (-2). Implicitly return
                  }

A closure / anonymous function


1
Welcome to PPCG! Can you take a list of strings as input to skip the .split()?
Martin Ender

Martin Ender Yes, if you assume that the input will always be a list of strings then {it[1..-2]} would work.
staticmethod

5

PHP, 37 Bytes

<?=join(" ",array_slice($argv,2,-1));

-4 bytes for an output as array

print_r(array_slice($argv,2,-1));

PHP, 42 Bytes

echo trim(trim($argn,join(range("!",z))));

PHP, 50 Bytes

echo preg_filter("#(^[^\s]+ |[^\s]+$)#","",$argn);


4

Perl 5, 27 18 bytes

Need to run with -n option.

/ (.+) /&&print$1

Try it online!

Wanted to do something similar in sed first, but, unfortunately, it doesn't support non-greedy quantifier. It is needed in case middle name is more than one word.

Edit

-9 bytes thanks to Dada.

Non-greedy quantifier is not needed anymore, among with some other things.


/ (.+) /&&print$1 should be sorter. Great to see some new people golfing with Perl!
Dada

@Dada Thanks for the tip! It's actually my first time ever writing in Perl. Do you know why print if s| (.+) |\1| doesn't work? To me it looks similar to what you wrote.
Maxim Mikhaylov

print if s| (.+) |\1| replaces the middle part with... the middle part! (minus the spaces before and after), so it doesn't work. On the other side, what I suggested only matches the middle part and print only it ($1).
Dada

4

Javascript (ES6) 49 16 bytes

Edit:

a=>a.slice(1,-1)

Try it online!

ungolfed:

function(name) {
  return a.slice(1, -1); //start at the second item and end at the second to last item
};

I forgot some of the simple properties of slice, and that the input can be an array. Thanks to @Neil and @fəˈnɛtɪk I was able to remove 27 bytes. Still not really competing.

Original:

This isn't really competing but here's a Javascript solution:

a=>{a=a.split(' ');return a.slice(1, a.length-1)}

This creates an anonymous function equal to:

function(name) {
  let name = name.split(' '); //first middle last -> [first, middle, last]
  return name.slice(1, name.length - 1); //get the second item to the second to last item in the array.
}

How I golfed it

This is a pretty simple golf. I turned the function into an arrow function. Then I "minified" the code. This included renaming name into a single character(a in this case) and removing the let decloration of the variable.

Snippet

Hope this helps anyone who is stuck on the challenge.


The length - is unnecessary, as slice already accepts negative lengths as being relative to the end. This means that you no longer need the intermediate variable, so you can turn your arrow function from a block into an expression.
Neil

Actually the way it works is that -1 is the last but one that you need here.
Neil

It is also slice(1,-1). slice(1,-2) removes two from the end.
fəˈnɛtɪk

You can also assume that you were passed an array to begin with, which lets you just perform slice and you are done.
fəˈnɛtɪk

I'm 99% sure that was changed since I started it. Thanks again.
David Archibald

3

Röda, 9 bytes

{_[1:-1]}

Try it online!

Not a very interesting solution. Takes a list from the stream and returns the middle names.

21 bytes and I/O:

{[(_/" ")[1:-1]&" "]}

Try it online!

This uses / (split) and & (join).


3

Jelly, 2 bytes

ḊṖ

Try it online!

This works as a non-inline link (i.e. function), not a full program.

'John','Jacob','Jingleheimer','Schmidt''Jacob','Jingleheimer'

As a full program, it would be 3 bytes: ḊṖK, which prints a space-separated middle name.



3

C#, 67 bytes

s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

Anonymous function which identifies the first occurrence of the space character and the last one and extracts the middle. It also extracts a trailing space, which can be removed at the cost of 2 bytes.

Full program with test cases:

using System;

namespace WhatsMyMiddleName
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string> f =
            s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

            Console.WriteLine(f("Jo Jean Smith"));          // "Jean"
            Console.WriteLine(f("Samantha Vee Hills"));     // "Vee"
            Console.WriteLine(f("Bob Dillinger"));          // ""
            Console.WriteLine(f("John Jacob Jingleheimer Schmidt"));// "Jacob Jingleheimer"
            Console.WriteLine(f("Jose Mario Carasco-Williams"));    // "Mario"
            Console.WriteLine(f("James Alfred Van Allen")); // "Alfred Van"
        }
    }
}


3

VBA, 69 bytes

Sub m(n)
f=InStr(1,n," ")
Debug.?Mid(n,f+1,InStrRev(n," ")-f)
End Sub

3

R, 30 27 22 bytes

Current solution due to user11599!

head(scan(,''),-1)[-1]

Takes input from stdin, returns each middle name as a separate string. Returns character() in the case of no middle name; that is, a vector of class character of length 0.

Explanation:

Read stdin into a list of strings, separated by spaces

     scan(,'')

Remove the last element. head returns the first n elements of a list, with n defaulting to 6. If n is -1 it returns all but the last element.

head(scan(,''),-1)

Now, remove the first element of this list.

head(scan(,''),-1)[-1]

This yields the middle name(s).


1
Even shorter: head(scan(,''),-1)[-1] 22 bytes. Note that '' are two single quotes.
user11599

If you don't want each name quoted, use, at 27 bytes, cat(head(scan(,''),-1)[-1])
user11599

Explanation: scan(,'') breaks the string into words, head(...,-1) drops the last word, head(...,-1)[-1] then drops the first word, cat() formats the output dropping the quotes. For no middle name, result isn't perfect, it's character(0), the empty string.
user11599

@user11599 Wow, thanks! I had played around with head() and tail(), but I didn't know you could pass a negative number as the second argument. Nice!
rturnbull

Your use of scan(,'') inspired me. I didn't think of approaching that way.
user11599

3

Ruby, 24 13 bytes

p ARGV[1..-2]

Saved 11 bytes thanks to Piccolo pointing out that array-like output is allowed.

Takes the name as separate command line arguments, e.g.:

$ ruby script.rb John Jacob Jingleheimer Schmidt

or

$ ruby -e 'p ARGV[1..-2]' John Jacob Jingleheimer Schmidt

Previous code (outputs a proper string):

puts ARGV[1..-2].join" "

@Jordan Good idea - however with $><<ARGV[1..-2].join" " it complains about the " " being unexpected, so I'd have to add parentheses - which would add 1 byte in the end.
Flambino

Ah, of course. My bad.
Jordan

The original poster said that the output can be an array, so you can shave some characters off by just changing your code to puts ARGV[1..-2], just so you know.
Piccolo

@Piccolo Huh? I don't see that anywhere? If true; p ARGV[1..-2] for 13 bytes - just looks nothing like the output in OPs challenge
Flambino


3

Golang, 152 81 bytes

import ."strings"
func f(x string)[]string{var k=Fields(x);return k[1:len(k)-1];}

It takes input as "Samantha Vee Hills" (with double quotes) and return the middle name to the stdout.

Try it Online!

Edit: @Dada, note that the "function as answer is allowed" shorten my code 71 bytes. a big thanks!


Welcome on the site. Submitting a function as answer is allowed, so you could shorten your code by doing something like this: Try it online!. Have a look at the Tips for Golfing in Go!
Dada

thank you @Dada for tips and shorten my code. It was my first code entry.
ersinakyuz

3

Matlab, 81, 79, 78, 55 Bytes

function x=a(s)
s=strsplit(s);x=strjoin(s(2:end-1));end

Takes in an input string, s, is split (by the default delimiter, whitespace char) into a cell array, from which the middle element is accessed. Then the middle elements are concatenated, or an empty string is returned.

Edit: thanks to Luis Mendo for saving 3 bytes!

Edit 2: Better solution from Ankit!


I am not a smart man! edited.
Owen Morgan

You can't use nnz on a cell array, but I did the other two changes :)
Owen Morgan

Suggested Edit by Ankit, who doesn't have enough rep to comment. (55 bytes): function x=a(s) s=strsplit(s);x=strjoin(s(2:end-1));end
mbomb007

3

C, 42 bytes

f(char**b){for(;b[2];printf("%s ",*++b));}

The parameter is a NULL terminated array of pointers to char.

See it work here.

The command line arguments may also be used with the same function.

C, 51 bytes

main(a,b)char**b;{for(;b[3];printf("%s ",b++[2]));}

A full program. Input is done through command line arguments.

See it work here.

C, 54 bytes

f(char**b){*strrchr(*b=strchr(*b,32),32)=0;*b+=!!**b;}

The parameter is an in/out parameter.

See it work here.


Welcome to PPCG!
Martin Ender

I'm receiving the following error when compiling with Visual Studio 2012:error C2100: illegal indirection
Johan du Toit

@JohanduToit VS is not C11 or even C99 conforming. My code is. As practical proof, both gcc and clang compile a valid program.
2501

2

Python 2, 42 19 16 Bytes

lambda n:n[1:-1]

Try it online! Thanks to @Kritixi Lithos for saving 23 bytes! Thanks @math_junkie for saving 3 more bytes. For input, put each part of the name as a string within a list like so:

["Samantha", "Vee", "Hills"]

And yes, the OP has approved a list to be a valid input.

Explanation

lambda n:n[1:-1]    # Returns only the middle elements... pretty literal here

1
print input()[1:-1] is shorter
Kritixi Lithos

Spring slicing sure is tricky
Anthony Pham

lambda n:n[1:-1] is even shorter
math junkie

1
I may have tried with a wrong input. But when I tried, with Samantha Vee Hills as input in repl.it link that you've shared, this just prints amantha Vee Hill which is definitely not the output required.
Keerthana Prabhakaran

2
Names will always have at least 2 space-separated parts is the first point of the question right.
Keerthana Prabhakaran

2

C++, 91 bytes

#import<list>
#import<string>
void f(std::list<std::string>&n){n.pop_front();n.pop_back();}

Takes input as a reference to a list of strings and modifies the list directly.

Try it online!

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.