인생이 레몬을 줄 때 레모네이드 만들기


21

도전

당신은 어디 단어, 입력 문자열이 주어집니다 "Lemon"이 변환되어야 발견 "Lemonade" 하지만a , d그리고 e문장에 다른 곳에서 빌려해야합니다.


예

입력 예 :

어렸을 때 레몬을 찾았 어요

출력 예 :

내가 어렸을 때 레모네이드를 찾았 어

레모네이드는 원본에서 다음 첨자 문자를 도용하여 만든

내가 foun D 레모네이드 어 전자 N I이었다 아이

이것은 "e", "d"및 "a"중 하나의 가능한 출력 예일뿐입니다 ( 물론 단어 lemon를 제외하고 )


코멘트

• 충분하지 않은 경우 e, a또는 d당신이야해야 할 - 수 주어진 문자로 무엇 출력. 예를 들어 입력 bdblemon은bblemond

• lemon텍스트가 항상 독립형 일 수는 없습니다 (양쪽에 공백). 예를 들어 lemons입력 어딘가에 단어가 있을 수 있으며 출력은lemonades

• 입력은 lemon0을 포함하여 s를 포함 할 수 있습니다 lemon(이 경우 출력은 입력과 동일)

• 당신은 예를 들어, 대문자와 소문자와 레모네이드를 만들 수 있습니다 leMon될 수 leMonade하고, ade어떤 경우 일 수있다 빌려 (또한이되었습니다 수 있도록 leMonADe).
빌린 편지의 경우 빌린 당시의 상태를 유지해야합니다.
(예 : 입력-> 출력, he hAD lemOn-> h h lemOnADe)

• 전체 프로그램 일 필요는 없으며 기능만으로도 충분합니다.

• 입력은 CP437 문자 세트 만 가정 할 수 있습니다


코드 골프

이것은 이므로 가장 적은 바이트 수가 이깁니다!


의사 테스트 사례

* 참고 : 주어진 입력에 대해 가능한 여러 출력 이있을 수 있으므로 이러한 테스트 사례와 같이 프로그램이 정확하게 출력되지 않을 수 있습니다. 이는 사람들이 논리를 이해할 수 있도록하기위한 것입니다.

입력 : EpaD leMons
출력 : p LeMonaDE

입력 : hello world
출력 : hello world

입력 : 레몬 레몬
출력 : 레몬 레몬
* ( , , 문자는 또 다른 "레몬"에서 촬영해서는 안됩니다)ead


투입물 : HE HAD lemonade 산출물 : HH lemonADEade

입력 : 당신은 레몬을 좋아합니까? 당신은 레몬에 나를 광고한다!
결과 : o 당신은 레몬을 좋아합니까? 레모네이드를 마신다!

입력 : AE 레몬
출력 : lemonAE

입력 : 55bad 레몬
출력 : 55b lemonad

code-golf  string  code-golf  parsing  internet  stack-exchange-api  code-challenge  kolmogorov-complexity  restricted-source  brain-flak  python  logic  pyth  code-golf  string  search  optimized-output  code-golf  tips  language-design  golfing-language  code-golf  tips  language-design  code-golf  number  sorting  pi  code-golf  math  number  code-golf  string  balanced-string  classification  brain-flak  code-golf  math  number-theory  decision-problem  code-golf  tips  code-golf  number  sequence  code-golf  balanced-string  brain-flak  code-golf  math  sequence  arithmetic  fibonacci  code-golf  math  parsing  code-golf  string  keyboard  code-golf  code-golf  string  source-layout  whitespace  code-golf  math  rational-numbers  code-golf  string  code-golf  string  code-golf  math  sequence  code-golf  number  floating-point  code-golf  string  decision-problem  subsequence  code-golf  string  kolmogorov-complexity  code-golf  string  permutations  balanced-string  brain-flak  code-golf  string  math  number  code-golf  string  primes  cipher  code-golf  string  ascii-art  chemistry  code-golf  ascii-art  grid  counting  code-golf  math  arithmetic  integer  code-golf  number  kolmogorov-complexity  code-golf  ascii-art  kolmogorov-complexity  sequence  metagolf  brain-flak  code-golf  ascii-art  kolmogorov-complexity  code-golf  string  whitespace 

답변:


6

자바 스크립트 (ES6) 159 157 155 162 바이트

편집 : 오류를 발생시키지 않고 "주어진 문자로 가능한 것을 출력하십시오"+7 바이트


수정 된 문자열을 반환하는 재귀 함수입니다.

f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``

작동 원리

표현식 s.split(/(lemon)/i) 은 입력 문자열을 분할 lemon하지만 결과에서 캡처 그룹을 유지합니다.

예를 들어 "foo lemon bar LEMON baz".split(/(lemon)/i) 배열을 생성합니다 [ 'foo ', 'lemon', ' bar ', 'LEMON', ' baz' ].

이 배열을 반복적으로 반복하여 문자를 추출합니다. a , d및 e또는 대문자 더 위치에있는 항목에서 대응하고 이상한 위치에있는 항목에를 추가.

댓글

f = (                                   // given:
  s,                                    //   s = input string or previous value of 'n'
  a = s.split(/(lemon)/i),              //   a = split array, as described above
  n = (a.length - 1) * 1.5              //   n = total number of characters to be found
) =>                                    //
  n ?                                   // if there's still at least one character to find:
    f(                                  //   do a recursive call with:
      n,                                //     1) the current value of 'n'
      a.map((s, i) =>                   //     2) an updated version of 'a', where
        i & 1 | !n || (                 //       for even positions:
          a[i] = s.replace(             //         we look for the next character
            [/a/i, /e/i, /d/i][n % 3],  //           'a', 'e' or 'd' (case insensitive)
            c => (                      //           append it to
              a[--n / 3 << 1 | 1] += c, //           one of the entries at an odd position
              ''                        //           and remove it from the original entry
            )                           //           end of replace() callback
          )                             //         end of replace()
        )                               //       end of position condition
      ) && a,                           //     end of map() -> yield the updated 'a'
      n -                               //     3) the updated value of 'n', skipping the
      (n == s)                          //        current character if not found at all
    )                                   //   end of recursive call
  :                                     // else:
    a.join``                            //   success: join 'a' and return it

데모


재귀 오류를 던지는 첫 번째 규칙을 준수하지 않는 것 ( " 가 충분하지 않은 경우 e, a또는 d이야 당신 출력해야 할 - 수를 주어진 문자로. 예를 들어 입력이 무엇 이었습니까 bdblemon출력 것bblemond ")?
— Kevin Cruijssen 12

1
@KevinCruijssen 흠, 맞아. 나는 오류를 던지는 것이 처음에 허용되었다는 것을 거의 확신했다. 최초 게시물의 유예 기간 동안 편집 했습니까? 어쨌든, 나는 그것을 고치려고 노력할 것입니다. 알아 주셔서 감사합니다.
— Arnauld

나는 실제로 편집 된 경우를 대비하여 내 의견을 말하기 전에 역사를 되돌아 보았습니다. 처음 5 분 동안 편집되었을 수도 있지만이를 확인하는 방법을 모릅니다. 그리고 문제 없습니다, 당신의 대답은 여전히 ​​인상적이므로 미리 +1하겠습니다. 의심 할 여지없이 문제를 해결할 수 있습니다 (많은 바이트를 추가하지 않고도).
— Kevin Cruijssen

@KevinCruijssen 지금은 7 바이트로 고정되었습니다.
— Arnauld

2
@Arnauld 네, 죄송합니다. 글의 처음 2 분 내에 haha, 내 사과를 전할 수있었습니다.
— Albert Renshaw

5

CJam, 130 바이트

LqY5m*{"lemon"_eu}%3/:z{~?}f%{_@\/_:,[{1$+}*]);@f{[\]}@+\1a*}/\{1
=}$0f=\1$,{"ade"{__C#)\Ceu#)|(\0+We\)@_N=@+N\t\}fC}fN0a/L*1a/\.{}

명확성을 위해 두 줄로 나뉩니다. 줄 바꿈은 계산되지 않습니다.

의사 코드 :

FLAG_1 = object()
FLAG_2 = object()
lemon_instances = [] # CJam: L
input_chars = list(all_input()) # CJam: q
lemons = [
    "LEMON", "LEMOn", "LEMoN", "LEMon", "LEmON", "LEmOn", "LEmoN", "LEmon",
    "LeMON", "LeMOn", "LeMoN", "LeMon", "LemON", "LemOn", "LemoN", "Lemon",
    "lEMON", "lEMOn", "lEMoN", "lEMon", "lEmON", "lEmOn", "lEmoN", "lEmon",
    "leMON", "leMOn", "leMoN", "leMon", "lemON", "lemOn", "lemoN", "lemon"
] # CJam: Y5m*{"lemon"_eu}%3/:z{~?}f%
for i in lemons: # CJam: { ... }/
    temp = input_chars.split(i) # CJam: _@\/
    lengths = temp.map(len) # CJam: _:,
    # Here, accum turns an array like [1,2,3] into [1,3,6].
    indices = accum(lengths) # CJam: [{1$+}*]
    indices.pop() # CJam: );
    temp2 = zip(temp, indices) # CJam: @f{[\]}
    lemon_instances = temp2 + lemon_instances # CJam: @+
    input_chars = join_array(temp, FLAG_1) # CJam: 1a*
lemon_instances.sort(key=lambda x: x[1]) # CJam: {1=}$
lemon_instances = [i[0] for i in lemon_instances] # CJam: 0f=
for i in range(len(lemon_instances)): # CJam: \1$,{...}fN
    for c in "ade": # CJam: "ade"{...}fC
        # list_index returns -1 if not found
        lower = list_index(input_chars, c)+1 # CJam: __C#)
        upper = list_index(input_chars, upper(c))+1 # CJam: \Ceu#)
        char_index = (lower or upper) - 1 # CJam: |(
        input_chars.append(FLAG_2) # CJam: \0+
        # -1 refers to the last element in the list
        swap_list_elements(input_chars, char_index, -1) # CJam: e\
        extracted = input_chars.pop() # CJam: )
        lemon_instances[i] += extracted # CJam: @_N=@+N\t\
remove_all(input_chars, FLAG_2) # CJam: 0a/L*
temp1 = input_chars.split(FLAG_1) # CJam: 1a/
# interleave([1, 2, 3], ["a", "b"]) gives [1, "a", 2, "b", 3]
temp2 = interleave(temp1, lemon_instances) # CJam: \.{}
print("".join(temp2))

나는 좋은 대답이 IMO이 더 upvotes이없는 슬프게 해요
— 알버트 렌쇼에게

4

레티 나 303 바이트

i+`(?<!lemon)(a)(.*)(lemon)(?!a)
$2$3$1
i+`(lemon)(?!a)(.*)(?<!lemon)(a)
$1$3$2
i+(?<!lemona?)(d)(.*)(lemona?)(?![ad])
$2$3$1
i+`(lemona?)(?![ad])(.*)(?<!lemona?)(d)
$1$3$2
i+(?<!lemona?d?)(e)(?!(?<=le)mon)(.*)(lemona?d?)(?![ade])
$2$3$1
i+`(lemona?d?)(?![ade])(.*)(?<!lemona?d?)(e)(?!(?<=le)mon)
$1$3$2

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

분명히 나는 ​​여기서 뭔가 잘못하고 있습니다.

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