A 또는 An?


21

영어에서이 재미와 사이의 간단한 차이 an와 a: 사용 an모음 소리로 시작하는 단어를 이전 할 때, 그리고 a단어가 자음 소리와 함께 시작됩니다.

이 문제를 간단하게하기 위해 an모음 ( aeiou)으로 a시작하는 단어와 자음으로 시작하는 단어가 앞에옵니다.

입력

문자열로, 인쇄 가능한 ASCII 문자를 포함 [?]삽입하도록 선택해야합니다 장소에 나타나는 an나 a. [?]단어 앞에 항상 나타납니다. 문장이 문법적으로 정확하고 평소와 같이 서식이 있다고 가정 할 수 있습니다.

산출

입력 문자열 [?]이 해당 단어 ( an또는 a) 로 바뀝니다 . 대문자 사용에 대해 걱정해야합니다!

자본화시기

단어 앞에 문자가 없거나 (입력에서 첫 번째 단어) .?!뒤에 공백 이 오는 단어는 대문자를 사용하십시오 .

예

Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?

이것은 이므로 바이트 단위의 가장 짧은 코드가 이깁니다!


알았어 고마워. 입력 [?]과 단어 사이에 여분의 공백이 없을 것이라고 가정 할 수 있습니까 ?
— DJMcMayhem

8
문장의 시작 부분에서 입력 중간에 대문자를 사용해야합니까? ( "이것은 [?] 테스트입니다. [?] 테스트입니다.") 그렇다면 문장은 어떤 문장 부호로 끝날 수 있습니까? 따옴표 나 괄호 안의 문장은 어떻습니까? 또는 마침표로 끝나는 약어 ( "예 : [?] 같은 입력")? 대문자 사용 규칙에는 이상한 특수한 사례가 많이 있으므로 프로그램이 처리하거나 처리 할 필요가없는 것에 대해 명시 적으로 알려주십시오.
— DLosc

1
언제 대문자로 표기해야합니까? 첫 캐릭터?
— DJMcMayhem

31
[?] hour ago I met [?] European.모든 사람이 울부 짖도록 테스트 사례를 추가해야합니다 .
— Martin Ender

1
이제 우리는[?] hour ago I met [?] horse.
— 비커

답변:


6

V , 41 바이트

ÍãÛ?Ý ¨[aeiou]©/an
ÍÛ?Ý/a
Í^aü[.!?] a/A

온라인으로 사용해보십시오! 또한 여분의 바이트 수없이 모든 테스트 사례를 확인하는 데 편리하게 사용할 수 있습니다.

이것은 V의 "Regex Compression"을 이용합니다. 인쇄 할 수없는 많은 문자를 사용하므로 다음은 16 진 덤프입니다.

0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9  ...?.. .[aeiou].
0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b  /an...?./a..^a.[
0000020: 2e21 3f5d 2093 612f 41                   .!?] .a/A

불행히도 OP는 " 대문자에 대해 걱정할 필요 가 있다 "고 말했다 . (강조 광산).
— El'endia Starman

1
@ El'endiaStarman 아, 나는 그것을 잘못 읽었다. 나는 그것을 고칠 수는 있지만 OP가 명시하지 않았기 때문에 자본화 할 단서가 없습니다.
— DJMcMayhem

@ El'endiaStarman 수정되었습니다.
— DJMcMayhem

7

펄, 48 바이트

Ton Hospel 로 인해 1 바이트를 절약했습니다 .

#!perl -p
s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg

shebang을 하나로 계산하여 입력을 stdin에서 가져옵니다.

설명

#!perl -p               # for each line of input, set $_, auto-print result

s;                      # begin regex substitution, with delimiter ;
\[\?]                   # match [?] literally, and replace with:
;
A.n x$'=~/^ [aeiou]/i   # 'A', concatenate with 'n' if post-match ($')
                        #   matches space followed by a vowel
^$"x/[^.?!] \G/         # if the match is preceded by /[^.?!] /, xor with a space
                        #   this will change An -> an

;eg                     # regex options eval, global

샘플 사용법

$ echo Hello, this is [?] world! | perl a-an.pl
Hello, this is a world!

$ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl
How about we build a big building. It will have an orange banana hanging out of a window.

$ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl
A giant en le sky. A yarn ball?

$ echo [?] hour ago I met [?] European. | perl a-an.pl
A hour ago I met an European.

2
이것을 설명해 주시겠습니까?
— sudee

1
/[.?!]/공간 뒤의 자본화에 대한 지원 이 누락 됨
— Ton Hospel

1
@TonHospel 10 시간 전, 문제는 이것을 언급하지 않았습니다.
— primo

2
좋아, 사양을 즉석에서 변경하는 것은 너무 불공평하다. 추신 : 나는 \G백 워드를 사용 하는 것을 좋아합니다. 약간 더 짧은 PPS :s;\[\?];A.n x$'=~/^ [aeiou]/^$"x/[^.?!] \G/;eg
— Ton Hospel

1
@sudee가 설명을 포함하도록 업데이트되었습니다.
— primo

7

루비, 78 72 바이트

->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}}

언 골프

def f(s)
    s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m|
        capitalize = $1
        vowel = $2
        replacement = if vowel then
            capitalize ? "An" : "an"
        else
            capitalize ? "A" : "a"
        end
        m.sub('[?]', replacement)
    end
end

2
"anAn"[...]정말 영리합니다. 👍🏻 내부를 건너 뛰어 몇 바이트를 절약 할 수 있습니다 sub.s.gsub(/(^|\. )?\K\[\?\] ([aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+" #$2"}
— Jordan

6

PHP, 207 바이트

foreach(explode("[?]",$s)as$i=>$b){$r=Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])].n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))];echo$i?$r.$b:$b;$a=$i?''==$d?a:$b:(''==$d?".":a);}

나는 때때로 더 완벽한 솔루션을 좋아
하지만 ... 완전히 완료 되지는 않았지만 약간 과잉이라는 것을 인정해야합니다.

파일로 저장하고 다음으로 실행 php <filename> STDIN의 입력으로 .

테스트 사례

How about we build [?] big building ... with [?] orange banana hanging out of [?] window.
=>  How about we build a big building ... with an orange banana hanging out of a window.

Hello, this is [?] world!               =>  Hello, this is a world!
Should I use [?] '[?]' or [?] '[?]'?    =>  Should I use an 'an' or an 'a'?
[?] elephant in [?] swimsuit.           =>  An elephant in a swimsuit.

How I met your moth[?].                 =>  How I met your motha.
b[?][?][?] short[?]ge!                  =>  banana shortage!

고장

foreach(explode("[?]",$s)as$i=>$b)
{
    $r=
        // lookbehind: uppercase if the end of a sentence precedes
        Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])]
        .
        // lookahead: append "n" if a vowel follows (consider quote characters blank)
        n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))]
    ;
    // output replacement and this part
    echo$i?$r.$b:$b;
    // prepare previous part for next iteration
    $a=$i               // this part was NOT the first:
        ?   ''==$d
            ? a             // if empty -> a word ($r from the previous iteration)
            : $b            // default: $b
        :  (''==$d      // this WAS the first part:
            ? "."           // if empty: end of a sentence (= uppercase next $r)
            : a             // else not
        )
    ;
    // golfed down to `$a=!$i^''==$d?a:($i?$b:".");`
}

3
"바나나 부족"에 찬성! LOL
— MonkeyZeus

@MonkeyZeus : 시험[?][?][?]s [?]lert!
— Titus

내가 상상할 수있는 모든 :( 심해 동키 콩 (Donkey Kong)는 이제 부족에 대한 아픈 걱정입니다
— MonkeyZeus

5

Minkolang 0.15 , 75 바이트

od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r

여기 사용해보십시오!

설명

od                                                                    Take character from input and duplicate (0 if input is empty)
  4&                                                                  Pop top of stack; jump 4 spaces if not 0
    r$O.                                                              Reverse stack, output whole stack as characters, and stop.

    "]?["                                                             Push "[?]" on the stack
         30$Z                                                         Pop the top 3 items and count its occurrences in the stack
              3&                                                      Pop top of stack; jump 3 spaces if not 0
                00w                                                   Wormhole to (0,0) in the code box

                3X                                                    Dump the top 3 items of stack
                  "Aa"                                                Push "aA"
                      I2-                                             Push the length of stack minus 2
                         "Aa ."40$Z,                                  Push ". aA" and count its occurrences, negating the result
                                    *                                 Multiply the top two items of the stack
                                     2&$r                             Pop top of stack and swap the top two items if 0
                                         x                            Dump top of stack
                                          r                           Reverse stack
                                           $O                         Output whole stack as characters
                                             " aeiou"                 Push a space and the vowels
                                                     od               Take a character from input and duplicate
                                                       0Z             Pop top of stack and count its occurrences in the stack (either 1 or 2)
                                                         1=           1 if equal to 1, 0 otherwise
                                                           3&         Pop top of stack; jump 3 spaces if not 0
                                                             "n"      Push "n" if top of stack is 0

                                                             r        Reverse stack
                                                              5X      Dump top five items of stack
                                                                $r    Swap top two items of stack

Minkolang은 환상적이므로 프로그램 카운터가 오른쪽 가장자리를 벗어나면 왼쪽에 다시 나타납니다. 확실히 골프를 칠 수 있지만 사양으로 인해 21 바이트를 추가해야했기 때문에 시도하지 않을 수 있습니다.


6
나는 그 설명을 읽은 후 excitebike를하고 싶은 유일한 사람입니까?
— Magic Octopus Urn

3

자바 스크립트 (ES6), 90 86 87 85

대문자 사양이 변경됨에 따라 한 번 더 편집

다시 편집 1 바이트 저장 thx @Huntro

IsmaelMiguel이 지적한대로 인용 부호 등을 관리하기 위해 2 바이트를 더 편집하십시오 (op가 요청했는지 여부를 모르더라도). 이전에는 86 바이트를 세었지만 85였습니다.

의견이 불완전한 경우 댓글 이벤트에 명시된 대문자 규칙을 따르려고 시도

x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

테스트

f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

function go() {
  var i=I.value, o=f(i)
  O.innerHTML = '<i>'+i+'</i>\n<b>'+o+'</b>\n\n'+O.innerHTML 
}

go()
#I { width:80% }
<input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button><pre id=O></pre>


[?][?]포기 해서는 안 Ana됩니까? 그리고 [?][?] a.생산 해서는 안 Ana a.됩니까?
— Ismael Miguel

@IsmaelMiguel 나는 당신이 무슨 뜻인지 정확히 이해하지 못하지만 어쨌든[?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.
— edc65

알았지 만 코드에서 [?] "[?]".( An "A", 인용 부호는 관련이 없음) 및 [?] "A".( )에 대해 이상한 결과를 제공 합니다 [?] A..
— Ismael Miguel

@IsmaelMiguel [?] "[?]"은 유효한 입력이 아닙니다. [?] will always appear before a word "[?]"는 단어가 아닙니다.
— edc65

2
두 번째 탈출은 ]필요하지 않습니다. /(\w )?\[\?](\W*.)/g
— Huntro

2

배치, 136 바이트

@set/ps=
@for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%%
@set s=%s:[?]=a%
@if %s:~0,1%==a set s=A%s:~1%
@echo %s:. a=. A%

STDIN에서 입력 라인을받습니다.


2

PHP, 100 92 바이트

<?=preg_filter(["/\[\?]\K(?= [aeiou])/i","/([.?!] |^)\K\[\?]/","/\[\?]/"],[n,A,a],$argv[1]);

정규식을 더 골프화하는 것이 가능했습니다.

정의되지 않은 상수에 대한 알림을 제공하지만 여전히 작동합니다.

편집 : primo 덕분에 8 바이트가 절약되었습니다.


또한 [n,A,a]둘러보기 어설 션 ( \K및 (?= )) 을 사용하여 교체 배열을 얻을 수 있어야합니다 .
— primo

2

파이썬 3.5.1, 153 (147) 124 바이트

*s,=input().replace('[?]','*');print(*[('a','A')[i<1or s[i-2]in'.?!']+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='')

입력 :

[?] apple [?] day keeps the doctor away. [?] lie.

출력 :

An apple a day keeps the doctor away. A lie.

123 바이트 버전-대문자 규칙을 처리하지 않습니다.

s=list(input().replace('[?]','*'));print(*['a'+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='')

무시 했어!


1
Welcome to Codegolf. You could use ; and golf it.
— ABcDexter

1
m.start() for should be m.start()for, s[i+2] in 'aeiouAEIOU' should be s[i+2]in'aeiouAEIOU'. An easy -3-byte shave due to whitespace.
— Erik the Outgolfer

1
('an','a')[s[i+2]in'aeiouAEIOU'] is inverted, you could use 'a'+'n'*(s[i+2]in'aeiouAEIOU') to fix that and save 2 bytes. Here you can find a lot of tips to golf.
— Rod

1
This community is so lovely, seeing how many people are willing to help a newcomer and provide golfing tips!
— yo'

1
Wow enumerate() is cool. Thanks @chepner.
— Gurupad Mamadapur

2

Java, 180178 bytes

My first post here, I did use a part of the Kevin Cruijssen post but and up with a different approach, he helped me to reduce a bit more so, thanks to him !

String c(String s){String x[]=s.split("\\[\\?]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;}

Here it is ungolfed :

static String c(String s) {
        String x[] = s.split("\\[\\?\\]", 2), r = x[0];
        return x.length > 1 ? r + (r.matches("(.+[.!?] )|(^)$") ? "A" : "a")
                + ("aeiouAEIOU".contains("" + x[1].charAt(1)) ? "n" : "") + c(x[1]) : r;
    }

And the result

A simple explanation, I use a recursive approch to find every [?].

I couldn't find a way to use the matches with insensitive case (not sure it is possible).

178bytes : Thanks to Martin Ender !


1
Welcome to PPCG! I don't think you need to escape the ] in your regex.
— Martin Ender

You are right, only the opening one is enought, thanks
— AxelH

2

05AB1E, 38 36 35 bytes

2FžNžM‚NèSðì…[?]©ìDu«D®'a'nN׫::}.ª

Try it online or verify all test cases.

Explanation:

2F            # Loop 2 times:
  žN          #  Push consonants "bcdfghjklmnpqrstvwxyz"
  žM          #  Push vowels "aeiou"
    ‚         #  Pair them together into a list
     Nè       #  And use the loop-index to index into this pair
  S           #  Convert this string to a list of characters
   ðì         #  Prepend a space in front of each character
     …[?]     #  Push string "[?]
         ©    #  Store it in variable `®` (without popping)
          ì   #  And prepend it in front of each string in the list as well
  }D          #  Then duplicate the list
    u         #  Uppercase the characters in the copy
     «        #  And merge the two lists together
              #   i.e. for the vowel-iteration we'd have ["[?] a","[?] e","[?] i","[?] o",
              #    "[?] u","[?] A","[?] E","[?] I","[?] O","[?] U"]
   D          #  Duplicate it
    ®         #  Push "[?]" from variable `®`
     'a      '#  Push "a"
       'n    '#  Push "n"
         N×   #  Repeated the 0-based index amount of times (so either "" or "n")
           «  #  And append it to the "a"
    :         #  Replace all "[?]" with "an"/"a" in the duplicated list
     :        #  And then replace all values of the lists in the (implicit) input-string
 }.ª          #  After the loop: sentence-capitalize everything (which fortunately retains
              #  capitalized words in the middle of sentences, like the "European" testcase)
              # (and after the loop the result is output implicitly)

1
There's a little bug in it. It capitalizes each word after an "an". For example "[?] orange" becomes "an Orange". Seems to work, if you add a ] after the ::
— Dorian

@Dorian Woops.. I removed that } later on because I thought it would save a byte, but you're indeed right that it fails for [?] vowel cases.. Thanks for letting me know!
— Kevin Cruijssen

1

C#, 204 235 bytes

string n(string b){for(int i=0;i<b.Length;i++){if(b[i]=='['){var r="a";r=i==0||b[i-2]=='.'?"A":r;r=System.Text.RegularExpressions.Regex.IsMatch(b[i+4].ToString(),@"[aeiouAEIOU]")?r+"n":r;b=b.Insert(i+3,r);}}return b.Replace("[?]","");}

Ungolfed full program:

using System;

class a
{
    static void Main()
    {
        string s = Console.ReadLine();
        a c = new a();
        Console.WriteLine(c.n(s));
    }

    string n(string b)
    {
        for (int i = 0; i < b.Length; i++)
        {
            if (b[i] == '[')
            {
                var r = "a";
                r = i == 0 || b[i - 2] == '.' ? "A" : r;
                r = System.Text.RegularExpressions.Regex.IsMatch(b[i + 4].ToString(), @"[aeiouAEIOU]") ? r + "n" : r;
                b = b.Insert(i + 3, r);
            }
        }
        return b.Replace("[?]", "");
    }
}

I'm sure this could be improved, especially the Regex part, but can't think of anything right now.


does it work without the imports?
— cat

Whoops, forgot to include the regex import in the count.
— Yodle

1
The golfed code should run as-is in whatever format -- if it doesn't run without the regex import, then the regex import should go in the golfed code too
— cat

Okay, thanks. Still ironing out exactly how to answer. The count and answer include System.Text.RegularExpressions now.
— Yodle

This looks good now. :) You can also check out Code Golf Meta and the faq tag there.
— cat

1

Java 7, 239 214 213 bytes

String c(String s){String x[]=s.split("\\[\\?\\]"),r="";int i=0,l=x.length-1;for(;i<l;r+=x[i]+(x[i].length()<1|x[i].matches(".+[.!?] $")?65:'a')+("aeiouAEIOU".contains(x[++i].charAt(1)+"")?"n":""));return r+x[l];}

Ungolfed & test cases:

Try it here.

class M{
  static String c(String s){
    String x[] = s.split("\\[\\?\\]"),
           r = "";
    int i = 0,
        l = x.length - 1;
    for (; i < l; r += x[i]
                     + (x[i].length() < 1 | x[i].matches(".+[.!?] $") 
                        ? 65
                        : 'a')
                     + ("aeiouAEIOU".contains(x[++i].charAt(1)+"")
                        ? "n"
                        : ""));
    return r + x[l];
  }

  public static void main(String[] a){
    System.out.println(c("Hello, this is [?] world!"));
    System.out.println(c("How about we build [?] big building. It will have [?] orange banana hanging out of [?] window."));
    System.out.println(c("[?] giant en le sky."));
    System.out.println(c("[?] yarn ball? [?] big one!"));
    System.out.println(c("[?] hour ago I met [?] European. "));
    System.out.println(c("Hey sir [Richard], how 'bout [?] cat?"));
    System.out.println(c("[?] dog is barking. [?] cat is scared!"));
  }
}

Output:

Hello, this is a world!
How about we build a big building. It will have an orange banana hanging out of a window.
A giant en le sky.
A yarn ball? A big one!
A hour ago I met an European. 
Hey sir [Richard], how 'bout a cat?
A dog is barking. A cat is scared!

I tried using a recursive solution, I end up with 2 bytes more then you :( need to improvement maybe .. but since I use your regex, I don't like to post it.
— AxelH

@AxelH Could you perhaps post it on ideone and link here? Together we might spot something to golf. ;)
— Kevin Cruijssen

Here is it ideone.com/z7hlVi, I did find a better approch thanisEmpty using the regex ^$. I believe I end up with 202 ;)
— AxelH

@AxelH Ah nice. Hmm, I count 195 bytes instead of 202? Btw, you can golf it to 180 by doing a direct return with a ternary if-else: String c(String s){String x[]=s.split("\\[\\?\\]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;} So definitely shorter than my loop-answer. :)
— Kevin Cruijssen

Oh yeah, i manage to put the if bloc in one line at the end, forgot to replace it. Thanks;
— AxelH

1

Racket 451 bytes (without regex)

It is obviously a long answer but it replaces a and an with capitalization also:

(define(lc sl item)(ormap(lambda(x)(equal? item x))sl))
(define(lr l i)(list-ref l i))(define(f str)(define sl(string-split str))
(for((i(length sl))#:when(equal?(lr sl i)"[?]"))(define o(if(lc(string->list"aeiouAEIOU")
(string-ref(lr sl(add1 i))0))#t #f))(define p(if(or(= i 0)(lc(string->list".!?")
(let((pr(lr sl(sub1 i))))(string-ref pr(sub1(string-length pr))))))#t #f))
(set! sl(list-set sl i(if o(if p"An""an")(if p"A""a")))))(string-join sl))

Testing:

(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")

Output:

"A giant en le a sky."
"A yarn ball?"
"A hour ago I met an European."
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"

Detailed version:

(define(contains sl item)
  (ormap(lambda(x)(equal? item x))sl))

(define(lr l i)
  (list-ref l i))

(define(f str)
  (define sl(string-split str))
  (for((i(length sl))#:when(equal?(lr sl i)"[?]"))
    (define an   ; a or an
      (if(contains(string->list "aeiouAEIOU")
                  (string-ref(lr sl(add1 i))0))
         #t #f ))
    (define cap   ; capital or not
      (if(or(= i 0)(contains(string->list ".!?")
                            (let ((prev (lr sl(sub1 i)))) (string-ref prev
                                       (sub1(string-length prev))))))
         #t #f))
    (set! sl(list-set sl i (if an (if cap "An" "an" )
                                 (if cap "A" "a")))))
  (string-join sl))

Yay for Racket! See also Tips for golfing in Racket / Scheme
— cat

It is an excellent language, though not meant for golfing.
— rnso

1

J, 113 bytes

[:;:inv 3(0 2&{(((('aA'{~[)<@,'n'#~])~('.?!'e.~{:))~('AEIOUaeiou'e.~{.))&>/@[^:(<@'[?]'=])1{])\' 'cut' . '([,~,)]

Try it online!

Shame, shame!


1

Retina, 66 60 bytes

i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])
a$.2*n$1
(^|[.?!] )a
$1A

Try it online.

Explanation:

Do a case-insensitive search for [?] followed by a vowel or consonant, where the optional vowel is saved in capture group 2, and the entire match in capture group 1:

i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])

Replace this with an a, followed by the length of the second group amount of n (so either 0 or 1 n), followed by the letter(s) of capture group 1:

a$.2*n$1

Then match an a at either the start of the string, or after either of .?! plus a space:

(^|[.?!] )a

And uppercase that A, without removing the other characters of capture group 1:

$1A

1

Java (JDK), 154 bytes

s->{String v="(?= [aeiou])",q="(?i)\\[\\?]",b="(?<=^|[?.!] )";return s.replaceAll(b+q+v,"An").replaceAll(q+v,"an").replaceAll(b+q,"A").replaceAll(q,"a");}

Try it online!

Explanation:

s->{
    String v="(?= [aeiou])",          // matches being followed by a vowel
    q="(?i)\\[\\?]",                  // matches being a [?]
    b="(?<=^|[?.!] )";                // matches being preceded by a sentence beginning
    return s.replaceAll(b+q+v,"An")   // if beginning [?] vowel, you need "An"
        .replaceAll(q+v,"an")         // if           [?] vowel, you need "an"
        .replaceAll(b+q,"A")          // if beginning [?]      , you need "A"
        .replaceAll(q,"a");}          // if           [?]      , you need "a"

1

C (gcc), 225 207 202 201 bytes

Thanks to ceilingcat for -24 bytes

#define P strcpy(f+d,index("!?.",i[c-2])+!c?
c;d;v(i,g,f)char*i,*g,*f;{for(d=0;i[c];c++,d++)strcmp("[?]",memcpy(g,i+c,3))?f[d]=i[c]:(index("aeiouAEIOU",i[c+4])?P"An ":"an "),d++:P"A ":"a "),d++,c+=3);}

Try it online!


0

Groovy, 73 162 bytes

def a(s){s.replaceAll(/(?i)(?:(.)?( )?)\[\?\] (.)/){r->"${r[1]?:''}${r[2]?:''}${'.?!'.contains(r[1]?:'.')?'A':'a'}${'aAeEiIoOuU'.contains(r[3])?'n':''} ${r[3]}"}}

edit: damn, the capitalization totally complicated everything here


Does this capitalize at the beginning of a sentence?
— Titus

nope. I see now, that the challenge description has been changed in the meantime...
— norganos

"Give me [?] hour with [?] open cellar door." Breaks your code: groovyconsole.appspot.com/edit/5159915056267264
— Magic Octopus Urn

the challenge description still is completely inconsistent. first it says "You do have to worry about capitalization!" and directly after that there are the rules for capitalization
— norganos

It is consistent. You have to worry about capitalization (that is, you need to manage it). Then it explains how
— edc65

0

C# 209 bytes

string A(string b){var s=b.Split(new[]{"[?]"},0);return s.Skip(1).Aggregate(s[0],(x,y)=>x+(x==""||(x.Last()==' '&&".?!".Contains(x.Trim().Last()))?"A":"a")+("AEIOUaeiou".Contains(y.Trim().First())?"n":"")+y);}

Formatted

string A(string b)
{
    var s = b.Split(new[] { "[?]" }, 0);
    return s.Skip(1).Aggregate(s[0], (x, y) => x + (x == "" || (x.Last() == ' ' && ".?!".Contains(x.Trim().Last())) ? "A" : "a") + ("AEIOUaeiou".Contains(y.Trim().First()) ? "n" : "") + y);
}

0

Perl 6, 78 bytes

{S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{$0 xx?$0}{<a A>[?$0]}{'n'x?~$1} $1/}

Explanation:

{
  S
    :ignorecase
    :global
  /
    ( # $0
    | ^             # beginning of line
    | <[.?!]> ' '   # or one of [.?!] followed by a space
    ) ?             # optionally ( $0 will be Nil if it doesn't match )

    '[?] '          # the thing to replace ( with trailing space )

    ( # $1
      <[aeiou]> ?   # optional vowel ( $1 will be '' if it doesn't match )
    )

  /{
    $0 xx ?$0      # list repeat $0 if $0
                   # ( so that it doesn't produce an error )
  }{
    < a A >[ ?$0 ] # 'A' if $0 exists, otherwise 'a'
  }{
    'n' x ?~$1     # 'n' if $1 isn't empty
                   # 「~」 turns the Match into a Str
                   # 「?」 turns that Str into a Bool
                   # 「x」 string repeat the left side by the amount of the right

  # a space and the vowel we may have borrowed
  } $1/
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my &code = {S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{<a A>[?$0]~('n'x?~$1)} $1/}

my @tests = (
  'Hello, this is [?] world!'
  => 'Hello, this is a world!',

  'How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.'
  => 'How about we build a big building. It will have an orange banana hanging out of a window.',

  '[?] giant en le sky.'
  => 'A giant en le sky.',

  '[?] yarn ball?'
  => 'A yarn ball?',

  '[?] hour ago I met [?] European.'
  => 'A hour ago I met an European.',

  "Hey sir [Richard], how 'bout [?] cat?"
  => "Hey sir [Richard], how 'bout a cat?",
);

plan +@tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  is code($input), $expected, $input.perl;
}
1..6
ok 1 - "Hello, this is a world!"
ok 2 - "How about we build a big building. It will have an orange banana hanging out of a window."
ok 3 - "A giant en le sky."
ok 4 - "A yarn ball?"
ok 5 - "A hour ago I met an European."
ok 6 - "Hey sir [Richard], how 'bout a cat?"

Can you remove a space from } $1 at the end (making it }$1)?
— Cyoce

@Cyoce There is a way of doing that, but it adds more complexity elsewhere. {S:i:g/(^|<[.?!]>' ')?'[?]'(' '<[aeiou]>?)/{<a A>[?$0]~('n'x?~$1.substr(1))}$1/}
— Brad Gilbert b2gills

Ok, I wasn't sure how perl would parse that
— Cyoce

0

Lua, 131 Bytes.

function(s)return s:gsub("%[%?%](%s*.)",function(a)return"a"..(a:find("[AEIOUaeiou]")and"n"or"")..a end):gsub("^.",string.upper)end

Although lua is a terrible Language for golfing, I feel I've done pretty well.


0

Pip, 62 55 54 50 bytes

Takes the string as a command-line argument.

aR-`([^.?!] )?\[\?]( [^aeiou])?`{[b"aA"@!b'nX!cc]}

Try it online!

Explanation:

a                                                   Cmdline argument
 R                                                  Replace...
  -`                           `                    The following regex (case-insensitive):
    ([^.?!] )?                                      Group 1: not end-of-sentence (nil if it doesn't match)
              \[\?]                                 [?]
                   ( [^aeiou])?                     Group 2: not vowel (nil if there is a vowel)
                                {                }  ... with this callback function (b = grp1, c = grp2):
                                 [              ]   List (concatenated when cast to string) of:
                                  b                 Group 1
                                   "aA"@!b          "a" if group 1 matched, else "A"
                                          'nX!c     "n" if group 2 didn't match, else ""
                                               c    Group 2

0

Racket (with regex) 228 bytes

(define(r a b c)(regexp-replace* a b c))
(define(f s)
(set! s(r #rx"[a-zA-Z ]\\[\\?\\] (?=[aeiouAEIOU])"s" an "))
(set! s(r #rx"[a-zA-Z ]\\[\\?\\]"s" a"))
(set! s(r #rx"\\[\\?\\] (?=[aeiouAEIOU])"s"An "))
(r #rx"\\[\\?\\]"s"A"))

Testing:

(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] apple?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")

Output:

"A giant en le a sky."
"A yarn ball?"
"An apple?"
"A hour ago I met an European. "
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"

0

Python 3, 104 103 bytes

-1 bytes, unescaped ]

lambda s:r('(^|[.?!] )a',r'\1A',r('a( [aeiouAEIOU])',r'an\1',r('\[\?]','a',s)));from re import sub as r

Try it online!

Starts by replacing all occurences of [?] with a,
Then replaces all a followed by a vowel, with an.
Then replaces all a at the start of input or a sentence with A.

Assumes that [?] will never be touching another word, and that lower-case a should never begin a sentence.


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