记住元音!


25

输入项

一串可打印的ASCII字符,例如:

This is an example string.

输出量

对于每个BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz没有元音(AEIOUaeiou)的辅音(),请在其末尾添加小写字母。
第一个元音之前的辅音保持原样

Thisi isi ana examapale seterinigi.

测试用例

AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)
=> ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)

And here comes a **TEST** case with 10% symbols/numbers(#)!
=> Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!

This is an example string.
=> Thisi isi ana examapale seterinigi.

abcdefghijklmnopqrstuvwxyz
=> abacadefegehijikiliminopoqorosotuvuwuxuyuzu

A pnm bnn
=> A panama banana

Tell me if you need more test cases!
=> Telele me ifi you neede more tesete casese!

计分

由于这是,因此每种语言中字节数最少的答案将获胜(不接受任何答案)。


因此,插入的元音是否应该始终小写,而文本可能同时大写和小写?
暴民埃里克(Erik the Outgolfer)

输出可以是列表/数组的形式吗?
内森·迪默

@EriktheOutgolfer是的,我不想在需要小写的地方使用大写,但是如果必须检查相邻字母的大小写,这会使挑战变得过于复杂
wastl

11
吃健康的孩子,尝试A pnm bnn
Stewie Griffin

4
还有人认为“意大利人如何”需要在标题中出现吗?
Artelius

Answers:


14

视网膜,48字节

i`(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])
$l$1

在线尝试!说明:前行搜索不跟随元音的点,而后向搜索则寻找紧接在前的辅音和前一个元音,然后以小写形式插入。


8

的JavaScript(ES6),108个 105字节

(由于@Shaggy,节省了3个字节。)

f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s

搜索元音没有以下元音的辅音:

/[aeiou]|[a-z][^aeiou]/ig

(我们不需要显式搜索辅音,因为基于会排除元音/[aeiou]|...。)

元音存储在中v,并且未v插入以下元音的辅音:

r[1]?r[0]+v.toLowerCase()+r[1]:v=r

(如果r[1]存在,我们已经匹配了辅音和非元音。)

如果没有任何更改,我们将返回输入。否则,我们将对替换后的字符串进行递归。


1
这样更好。我真的需要看看正则表达式
路易斯·费利佩·德·耶稣·穆诺兹

+1个聪明的想法可在地图上使用替换+
联接

基于您的(几乎)没有递归的工作版本:不过,s=>s.replace(/[aeiou][^a-z]*([a-z](?![aeiou]))+/gi,s=>s.replace(/(?!^)./g,a=>a+s[0].toLowerCase()))我似乎对非字母序列没有问题
Downgoat

递归当然可以简化这里的事情。
瑞克·希区柯克

(s+=' ')应该保存几个字节。
粗野的


4

标准ML225个 223字节

str o Char.toLower;fun?c=String.isSubstring(it c)"aeiou"fun g(x,l)$d=(fn l=>if Char.isAlpha$andalso not(?d)then if? $then(it$,l)else(x,l^x)else(x,l))(l^str$)fun f$(c::d::r)=f(g$c d)(d::r)|f$[c]= #2(g$c c);f("","")o explode;

在线尝试!

少打高尔夫球:

val lower = str o Char.toLower

fun isVowel c = String.isSubstring (lower c) "aeiou"

(* c is the current char, d is the next char, x is the last vowel and l the accumulator 
   for the resulting string *)
fun g (x,l) c d = 
    if Char.isAlpha c andalso not (isVowel d)
    then if isVowel c 
         then (lower c, l^str c)
         else (x, l^str c^x)
    else (x, l^str c)

fun f t (c::d::r) = f (g t c d) (d::r)
  | f t [c] = #2(g t c #"d")

val h = f ("","") o explode;

在线尝试!


哇,ML高尔夫看起来真的很有趣!我喜欢it和使用$变量名。
林恩

@Lynn 一段时间前,我写了一篇有关标识符重命名的提示,并计划也写一篇it,但还没有解决。
Laikoni


4

Perl 5,68 67 59字节

perl -pe '$v="[aeiou])";1while s/($v[^a-z]*[b-z]\K(?<!$v(?!$v/\L$1/i'

这是的有用的一个很好的例子,\K在Dom Hastings指出这一功能之前,我不敢相信我对此功能一无所知。

我无法仅使用来获得正确的行为s///g,因此实际循环似乎是必要的。(有可能在没有显式声明的情况下正确使用后置断言while-但我没有找到它。)


不错的方法!没办法提出更好的建议,但是设法减少了6个字节:在线尝试!
Dom Hastings

1
@DomHastings:通过考虑[aeiou])变量来缩短(最多58个字节):在线尝试!
ShadowRanger

3

JavaScript ES6,115字节

@ETHProductions节省了8个字节

s=>[x="",...s].map((i,j)=>(r=/[aeiou]/i).test(i)?x=i:/[a-z]/i.test(i)&&!r.test(s[j]||1)?i+x.toLowerCase():i).join``

我设法在打高尔夫球的过程中对此进行了进一步的充气O_o,但它也修复了一个错误

s=>[x="",...s].map(             // Create a new array with x storing last vowel
                                // This also offsets indexes by one so rel to original str refers to next char
   (i,j)=>                      // Going through each char...
      (r=/[aeiou]/i).test(i)?   // If it's vowel, store it in x
          x=i:
      /[a-z]/i.test(i)          // If a letter (thats not a vowel excluded by above)
         &&!r.test(s[j]||1)?    // Test if next char is *not* vowel
         i+x.toLowerCase():i    // If it isn't, then add the most recent vowel after
    ).join``                    // Combine back to string

@RickHitchcock哦,拍摄完全忘了结束字符,尽快修复
Downgoat

1
@RickHitchcock确定固定
Downgoat

嗯,是的,谢谢@ETHproductions高尔夫
Downgoat

3

JavaScript,88 82字节

使用单个正则表达式完成:

原始版本(88字节):

s=>s.replace(/(?<=([aeiou]).*?(?![aeiou])[a-z])(?=[^aeiou]|$)/gi,(_,c)=>c.toLowerCase())

查看Neil的正则表达式后的更新版本(82字节):

s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase())

var tests = {
  "AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)":
    "ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)",
  "And here comes a **TEST** case with 10% symbols/numbers(#)!":
    "Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!",
  "This is an example string.":
     "Thisi isi ana examapale seterinigi.",
  "abcdefghijklmnopqrstuvwxyz":
    "abacadefegehijikiliminopoqorosotuvuwuxuyuzu",
  "A pnm bnn":
     "A panama banana",
  "Tell me if you need more test cases!":
     "Telele me ifi you neede more tesete casese!"
};

for ( test in tests )
{
  var result = (s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase()))(test);
  console.log( result === tests[test], result );
}


3

Japt -P,28个字节

ó@\ctX ©\VtYÃËè\v ?P=D:D¬qPv

在线尝试!

开箱及其工作方式

UóXY{\ctX &&\VtY} mD{Dè\v ?P=D:Dq qPv

UóXY{           }  Split the string between any two chars that don't satisfy...
     \ctX &&\VtY     The first char is a consonant and the second is a non-vowel
mD{                And map...
   Dè\v              If this item is a vowel...
       ?P=D            Assign it to P and return as-is
           :Dq qPv     Otherwise, split the item into chars and join with P lowercased
                       (P starts with "", so beginning consonants are not affected)

-P                 Join with ""

ó功能胜过任何形式的正则表达式。


不错,你击败了我:D。
魔术章鱼缸

做得好-我为此感到很头痛!
粗野的


2

Perl 6的 75个73 71  69字节

{({S:i/.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>/$0.lc()/}...*eq*).tail}

试试吧

{({S:i{.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail}

试试吧

{({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail}

试试吧

{({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><(<![aeiou]>}=$0.lc}...*eq*).tail}

试试吧

展开:

{  # bare block lambda with implicit parameter $_

  (
    # generate a sequence

    {  # code block used to generate the values

      S               # substitute (not in-place)
      :i              # :ignorecase
      {

          .*              # start at end of string

          ( <[aeiou]> )   # store the previous vowel in $0

          .*

          <:L - [_aeiou]> # letter other than a vowel

          <(              # ignore everything before this

                          # this is where `$0.lc` gets inserted

          # )>            # ignore everything after this

          <![aeiou]>      # not a vowel (zero width lookahead)

      } = $0.lc       # replace with lowercase of the earlier vowel
    }

    ...    # keep generating until:

    * eq * # there are two equal strings (no changes)

  ).tail   # get the last value
}

2

Python 3,125个字节

lambda s,v='[^aeiouAEIOU':sub(f'(?<={v}\W\d])(?={v}]|$)',lambda m:sub(f'{v}]','',s[:m.end()])[-1:].lower(),s)
from re import*

在线尝试!

Python 3.6允许我们便宜地使用f字符串来重用我们的元音集(对于保存的另外四个字符,则是反正则表达式字符类的开头)(f每个字符串的前缀,然后{v}根据需要,而不是'+v+'您需要连接,或者直接[^aeiouAEIOU插入。

不匹配任何字符的正则表达式,只是一个位置,避免了普通正则表达式要求的不重叠匹配的问题,并且消除了对匹配的任何部分进行反向引用的需要;我们使用match对象的全部目的是获取用于查找先前元音的切片索引。

部分取消高尔夫,它将类似于:

import re

def get_last_vowel(string):
    '''
    Returns the lowercase version of the last vowel in a string if
    the string contains any vowels, otherwise, return the empty string
    '''
    try:
        *restvowels, lastvowel = re.sub(r'[^aeiouAEIOU]', '', string)
    except ValueError:
        lastvowel = ''  # No vowels in string
    return lastvowel.lower()

def rememebere_tehe_vowelese(string):
    '''Inserts the lowercased last vowel seen after any consonant not followed by a vowel'''
    return re.sub(r'(?<=[^aeiouAEIOU\W\d])(?=[^aeiouAEIOU]|$)',
                  lambda match: get_last_vowel(string[:match.end()]),
                  string)

2

TSQL,500字节

 CREATE TABLE i (i CHAR(999)); INSERT i VALUES ('The rain in Spain stays mainly in the plain')
 DECLARE @w CHAR(999)=(SELECT i FROM i),@r VARCHAR(999)='';WITH d(n,c,i,q)AS(SELECT n,SUBSTRING(@w,n,1),CHARINDEX(SUBSTRING(@w,n,1),'AEIOUaeiou'),CHARINDEX(SUBSTRING(@w,n,1),'BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz')FROM(SELECT DISTINCT number n FROM master..[spt_values]WHERE number BETWEEN 1 AND LEN(@w))D)SELECT @r=@r+f.c+LOWER(COALESCE(CASE WHEN f.q<>0 AND COALESCE(d2.i,0)=0 THEN SUBSTRING(@w,(SELECT MAX(n)FROM d WHERE i<>0 AND n<f.n),1)END,''))FROM d f LEFT JOIN d d2 ON f.n=d2.n-1 SELECT @r

i用于输入


2
假设通常不允许输入存在于某个变量中。可以改成一个函数吗?
Laikoni

@Laikoni解决方案已更新以匹配给定的规则
Jan Drozen

2

SWI-Prolog,593字节

a(S,D):-atom_chars(S,D).
g(_,[],_,-1).
g(E,[E|_],R,R).
g(E,[_|T],I,R):-N is I+1,g(E,T,N,R).
c(A,E):-g(E,A,0,R),R > -1.
v(X):-a('AEIOUaeiou',X).
c(X):-a('BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz',X).
d([_],_,R,R).
d([H|T],_,I,R):-v(V),c(V,H),!,d(T,H,I,[H|R]).
d([H,N|T],V,I,R):-c(C),c(C,H),v(W),c(W,N),!,d([N|T],V,I,[H|R]).
d([H,N|T],V,I,R):-c(C),c(C,H),v(W),\+c(W,N),string_lower(V,LV),!,d([N|T],V,I,[LV,H|R]).
d([H|T],V,I,R):-!,d(T,V,I,[H|R]).
r([],Z,Z).
r([H|T],Z,A):-r(T,Z,[H|A]).
r(S,D):-r(S,D,[]).
m(X,R):-a(X,O),r(O,P),r([''|P],Q),d(Q,'',I,[]),r(I,J,[]),atomic_list_concat(J,R).

仅使用内置谓词(不带正则表达式或列表操作库)。

用法:

?- m('A pnm bnn').
'A panama banana'
true .

2

Haskell142130字节

""&
import Data.Char
v=(`elem`"aeiouAEIOU")
s&(x:y:z)|v y=x:s&(y:z)
s&(x:y)|v x=x:[toLower x]&y|isAlpha x=x:s++s&y|1>0=x:s&y
_&x=x

在线尝试!

最初""&(&)稍后定义的函数的部分应用程序,其位置太奇怪了,以至于TIO ""&不能计算TIO中的字节,而不能计算完整程序中将其分配给任何命名值所需的字节。


少打高尔夫球:

import Data.Char (isAlpha, toLower)

vowel :: Char -> Bool
vowel = (`elem`"aeiouAEIOU")

replace :: String -> String
replace = go "" -- start by carrying no extra vowel
  where go _ "" = ""
        -- special case for "anything followed by vowel" so later cases can ignore next character
        go s (x:y:more) | vowel y = x : go s (y:more)
        go s (x:xs) | vowel x = x : go [toLower x] xs -- update the vowel we're carrying
                    | isAlpha x = x : s ++ go s xs -- non-vowel letter not followed by a vowel
                    | otherwise = x : go s xs -- some non-letter junk, just include it and carry on

确实应该有一种方法可以更简洁地通过折叠而不是递归来实现,但是我无法弄清楚。


这是定义标题而f不会出现在主体中的一种非常怪诞的方法:在线尝试!
Laikoni

其中有两个不必要的空格v = (,您可以将其定义g为中缀运算符
Laikoni

将基本案例g _""=""放在最后一个位置可节省一个字节:(g _ x=x如果您按照Laikoni的建议切换到infix,则为两个字节)。
nimi

根据我们的约定,您需要添加括号""&以使其起作用。
Laikoni

1

05AB1E,34个字节

vyžMylåil©1V}žPylåžM¹N>èå_Y&&i®«}J

在线尝试!


我收回这一观点,我只能将这种怪异现象削减3个字节……我想我可以将布尔值削减下来,但是必须有3种情况。1个元音。辅音为1。如果存在数字/符号,则为1。


v                                 # For each...
 y                                # Push current element.
  žM                              # Push lower-case vowels (aeiou).
    ylå                           # Lower-case current element is vowel?
       i©1V}                      # If so, put it in register, set Y to 1.
            žP                    # Push lower-case consonants (b...z)
              ylå                 # Is current char a consonant?
                 žM¹N>èå_         # Push vowels again, is input[N+1] NOT a vowel? 
                         Y        # Did we ever set Y as 1?
                          &&      # All 3 previous conditions true?
                            i®«}  # Concat the current vowel to the current char.
                                J # Join the whole stack.
                                  # '}' isn't needed here, b/c it's implied.
                                  # Implicit return.

0

Powershell,104字节

基于Neil的正则表达式

[regex]::Replace($args,'(?i)(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])',{"$($args.Groups[1])".ToLower()})

将其另存为get-rememebere.ps1。测试脚本:

$test = @"
AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)
And here comes a **TEST** case with 10% symbols/numbers(#)!
This is an example string.
abcdefghijklmnopqrstuvwxyz
A pnm bnn
Tell me if you need more test cases!
"@

$expected = @"
ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)
Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!
Thisi isi ana examapale seterinigi.
abacadefegehijikiliminopoqorosotuvuwuxuyuzu
A panama banana
Telele me ifi you neede more tesete casese!
"@

$result = .\get-rememebere.ps1 $test
$result -eq $expected
$result

1
这不只是一个片段吗?我的意思是,powershell有输入,所以您不能假定输入在$t。相关中继发布:codegolf.meta.stackexchange.com/a/8731/78123
wastl

0

红色,276字节

func[s][v: charset t:"AEIOUaeiou"c: charset 
u:"BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"b:
parse s[collect[any keep[thru c opt v]keep thru end]]p:""foreach
c b[either find t e: last c: to-string c[p: e][parse c[any[copy p v
| skip]]if find u e[append c lowercase p]]prin c]]

在线尝试!

可读性:

f: func [ s ] [
   v: charset t: "AEIOUaeiou"
   c: charset u: "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
   b: parse s [
       collect [ any keep [ thru c opt v ]
       keep thru end ]
   ]
   p: "" 
   foreach c b [
       e: last c: to-string c
       either find t e [ p: e ][
           parse c [ any [ copy p v | skip ] ]
           if find u e [ append c lowercase p ]
       ]
       prin c
   ]
]

0

Yabasic,180字节

完整的程序,从STDIN输入并输出到STDOUT

Line Input""s$
x$="AEIOUaeiou"
For i=1To Len(s$)
c$=Mid$(s$,i,1)
?c$;
If InStr(x$,c$)Then
v$=c$
Else
a=Asc(Upper$(c$))
If a>64And a<91And!InStr(x$,Mid$(s$,i+1,1))Then?v$;Fi
Fi
Next

在线尝试!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.