Какое у меня второе имя?


30

Примечание . Победивший ответ будет выбран 12.12.17. Текущий победитель - Джольф, 1 байт .

Я удивлен тем, что на этом сайте у нас еще не было ответа на вопрос, каково мое второе имя. Я много искал, но ничего не нашел. Если это дубликат, отметьте его как таковой.

Ваш вызов

Разобрать строку, которая выглядит как 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
Может ли вывод быть списком строк?
— Энтони Фам,

5
Если разрешены другие форматы, кроме строки, разделенной пробелами, отредактируйте ее в спецификации.
— Мартин Эндер

5
@ programmer5000: если на входе может быть список строк, как на счет вывода? Является ли ["John", "Jacob", "Jingleheimer", "Schmidt"]-> ["Jacob", "Jingleheimer"]допустимым решением?
— Ними

3
Разрешены ли ведущие пробелы?
— betseg

2
@DJ Потому что «Ван» не его второе имя, это часть его фамилии. Особенно неприятный случай - это Дэвид Ллойд Джордж, которого зовут Дэвид, а фамилия - Ллойд Джордж. Любая попытка разобрать имена настоящих людей, как это, обречена. На самом деле, вы даже не можете сказать, какие имена и фамилии (подумайте Ли Ши).
— Дэвид Конрад

Ответы:


4

Джольф, 1 байт

€

Получает внутреннюю часть ввода. Попробуй это здесь!


Не получается запустить пример - похоже, ничего не происходит, когда я нажимаю на любую из кнопок. Использование Chrome 57.0.2987.133

@YiminRong Я могу только гарантировать, что он работает на Firefox.
— Конор О'Брайен

44

Ом , 2 байта (CP437)

Принимает и возвращает список строк.

()

Объяснение:

()   Main wire, arguments: a

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

10
Думаю, правильный инструмент для работы
— Рохан

15

Vim, 6 5 байтов

dW$BD

Попробуйте онлайн!

(выходы с завершающим пробелом)

Поскольку Vim обратно совместим с V, я включил ссылку TIO для V.

объяснение

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

Драт, ты меня обыграл. dWWDэкономит один байт
— DJMcMayhem

5
@DJMcMayhem Это работает только для одного второго имени.
— Мартин Эндер

Какая разница между dW и dw?
— Дункан Х Симпсон

1
@DuncanXSimpson dWудаляет до пробела. dwудаляет до несловесных символов.
— Фонд Моника иск

14

Python , 24 байта

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

Попробуйте онлайн ввод строки!

Формат ввода: строка


Python 2 , 16 байт

lambda n:n[1:-1]

Попробуйте онлайн список ввода!

Формат ввода: список


Вы должны отредактировать заголовок с помощью Pythonвместо Python 2, потому что он работает Python 3также, как раз собирался опубликовать это.
— г-н Xcoder

@ L3viathan, так как OP не упомянул формат вывода must be a string, и так как формат ввода может быть списком, распечатка списка не может рассматриваться как неправильный результат!
— Киртана Прабхакаран

Согласно комментариям к вопросу, вы можете как вводить, так и выводить список строк. Сохраните кучу байтовlambda n:n[1:-1]
— Люк Савчак

1
Так как вы можете читать из STDIN, может заменить лямбда с input()(Python 3 только)
— BallpointBen

Вы правы. Спасибо. Я добавил правки!
— Киртана Прабхакаран

13

Brain-Flak , 133 байта

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

Попробуйте онлайн!

132 байта кода, плюс 1 байт для -cфлага, который допускает ввод и вывод ASCII.

К сожалению, в нем много дублирующегося кода, но его будет очень сложно использовать повторно. Я посмотрю на это позже. Вот объяснение:

#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 байт при удалении комментариев. Я добавил первые два и последнюю строку. TIO
— Райли

@riley Классное решение. Не стесняйтесь размещать это самостоятельно!
— DJMcMayhem


12

Haskell, 23 , 17 9 байт

init.tail

Принимает и возвращает список строк. Попробуйте онлайн!

Удалить первую строку, удалить последнюю строку.

Редактировать: @Generic Display Name отметил, что входные данные могут быть списком строк, которые сохранили 6 байтов.

Редактировать II: вернуть список строк вместо одной строки


Похоже, что ввод в виде списка разрешен, поэтому отбросьте слова для -5 байтов
— Общее отображаемое имя

@ GenericDisplayName: О, не заметил. Благодарность!
— Ними

Мой Ohm-ответ и Mathematica также отвечают на оба выходных списка строк, так что вы, вероятно, можете отбросить unwords.на -8 байт.
— Ник Клиффорд

@NickClifford: да, я сам это видел и попросил у ОП уточнения.
— nimi

11

Mathematica, 10 байт

Rest@*Most

Безымянная функция, которая принимает и возвращает список строк.

Restотбрасывает последний элемент, Mostотбрасывает первый элемент, @*это функция композиции. Замена Restи / Mostили использование правильной композиции /*вместо этого также будет работать. Это лучше, чем индексирование #[[2;;-2]]&по одному байту.


10

Brain-Flak , 86 байт

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

Попробуйте онлайн!

Большая часть этого кода происходит из этого ответа . Если вам нравится мое решение, вы должны также подтвердить это.

#Push 2
(()())

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

  #While not a space
  {
      #Pop
      {}

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

  #Endwhile
  }

  #Pop the 0
  {}

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

#End loop twice
>)}{}

Отлично сработано! Я не думал о том, чтобы держать счетчик для толкания позже, поэтому я слишком долго думал о том, как перебирать различные стеки.
— DJMcMayhem

8

Java 7, 74 байта

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

Java 8, 49 байт

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

Функция, которая идентифицирует первое вхождение символа пробела и последнего и извлекает середину. Результирующая строка имеет префикс пробела (во время публикации OP не уточнил, разрешены ли начальные пробелы), что можно устранить, добавив.trim() to the code for an extra cost of 7 bytes.

По сравнению с C # у Java есть преимущество, заключающееся в указании конечного индекса вместо длины подстроки, что снижает количество байтов.


7

JavaScript (ES6), 22 байта

Принимает и выводит массив строк.

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

Контрольные примеры

Строковая версия (27 байт)

Принимает и выводит строку. Выходная строка представляет собой либо один пробел, если не найдено второе имя, либо отчество с начальным и конечным пробелами.

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


/./.exec.bind(/ .* /)кажется, подражают # 2, за исключением nullни одного
— dandavis

7

AWK , 17 10 байт

Сохранено 7 байт благодаря @steve!

$NF=$1=x;1

Попробуйте онлайн!

Объяснение:

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

Может быть сокращен до 11 байтов,$NF=$1="";1
— Стив

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

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

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!

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.