프로그래머의 말처럼 : 게 으르려고 노력하십시오


25

이야기

9gag 에서이 게시물을 보셨습니까 ? 어쩌면 당신은 자신의 문장을 만드는 느낌이 들었습니다. 그러나 당신은 30 분 안에 스크립트를 골프로 칠 수 있다는 것을 알고 있습니다.

제출

프로그램은 입력 문자열을 얻습니다. 입력 문자열은 아래 설명과 같이 따옴표가 추가되어 반환됩니다. 표준 허점은 금지되어 있습니다. 라인리스트로 출력이 허용됩니다. 출력을 중단하지 않는 후행 공백과 빈 줄이 허용됩니다.

입력 규칙

  • 입력은 인쇄 가능한 ASCII 문자 만 포함합니다.
  • 입력에 공백이 포함될 수 있습니다. 단어는 그들과 함께 결정됩니다.
  • 공백 뒤에는 다른 공백이 절대로 오지 않습니다.
  • 입력이 없거나 빈 문자열의 경우는 중요하지 않습니다.

출력 규칙

한 단어가 제공되면 프로그램은 따옴표 사이에 문자열을 반환해야합니다.

입력 문자열에 2 개 이상의 단어가 있으면 먼저 초기 입력을 반환하지만 첫 번째 단어는 따옴표 안에 있습니다. 그런 다음 다음 줄에서 초기 입력을 반환하지만 두 번째 단어는 따옴표로 묶습니다. 나머지 단어들도 마찬가지입니다.

일반적으로 프로그램은 입력에 단어가있는만큼 많은 행을 리턴해야합니다.

예 :

test -> "test"

This is codegolf -> "This" is codegolf
                    This "is" codegolf
                    This is "codegolf"

This is a significantly longer, but not the longest testcase -> "This" is a significantly longer, but not the longest testcase
                                                                This "is" a significantly longer, but not the longest testcase
                                                                This is "a" significantly longer, but not the longest testcase
                                                                This is a "significantly" longer, but not the longest testcase
                                                                This is a significantly "longer," but not the longest testcase
                                                                This is a significantly longer, "but" not the longest testcase
                                                                This is a significantly longer, but "not" the longest testcase
                                                                This is a significantly longer, but not "the" longest testcase
                                                                This is a significantly longer, but not the "longest" testcase
                                                                This is a significantly longer, but not the longest "testcase"

Here is an another one -> "Here" is an another one
                          Here "is" an another one
                          Here is "an" another one
                          Here is an "another" one
                          Here is an another "one"

이것은 이므로 최소 바이트 응답이 이깁니다!


7
중복 단어가 있습니까?
무지의 구현

10
입력 문자열에 "문자 가 포함되지 않는다고 가정 할 수 있습니까 ?
손잡이


14
이 "문제"는 "재미"에서 "골프"여야합니다.
Jono 2906

3
우리는 다른 따옴표처럼 사용할 수 '', ‘’또는 “”, 대신를 ""?
주세페

답변:


10

vim, 38 바이트

:s/"/<C-d>/g
qqysW"Ypds"W@qq@qdk:%s/<C-d>/"/g

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

vim-surround 플러그인이 필요합니다 .

입력에 "문자 가 없으면 19 바이트 로 수행 할 수 있습니다 .

qqysW"Ypds"W@qq@qdk

여기서 우리는 재귀 적으로 호출하기 전에 qq ... @qq@q따옴표 ( ysW") 로 단어를 둘러싸고 , 줄 ( Yp)을 복제하고 , 따옴표 ( )를 삭제 ds"하고 다음 단어 ( W)로 이동 하는 재귀 매크로 ( )를 기록합니다 . 종료 된 후 외부 라인 두 개가 있으며이 라인은로 삭제됩니다 dk.

전체 솔루션 :s/"/<C-d>/g은 처음에는 이것을 기존의 "문자를 인쇄 할 수없는 문자로 대체 :%s/<C-d>/"/g하고 마지막에 대체를 취소하는 것으로 간단히 래핑합니다 .


2
실제로 같은 방법으로 예제를 만들었습니다. D
krinistof

8

하스켈, 65 바이트

([]#).words
a#(b:c)=unwords(a++('"':b++"\""):c):(a++[b])#c
_#_=[]

줄 목록을 반환합니다.

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


입력에 따옴표, 줄 바꿈 또는 기타 이스케이프 문자가 포함되어 있으면 실패한 것 같습니다.
밀 마법사


@ SriotchilismO'Zaic : 고정되었습니다. 지적 해 주셔서 감사합니다. 짧은 버전에 관해서 : xnor는 이미 이것을 답변 으로 게시했습니다 .
니미

단어는 \n공백으로 간주되므로 단어 가있을 때 제대로 동작 하지 않습니다 .
밀 마법사

@ SriotchilismO'Zaic : "입력은 인쇄 가능한 ASCII 문자 만 포함합니다 ~. "는 Space to 입니다. "입력에 공백이있을 수 있습니다"- "공백"이 아닙니다.
nimi

7

레티 나 0.8.2 , 17 바이트

 
" $'¶$` "
^|$
"

온라인으로 사용해보십시오! 링크에는 테스트 스위트가 포함되어 있습니다. 설명:

 
" $'¶$` "

줄을 복제 한 다음 따옴표를 삽입하여 각 공간을 확장하십시오.

^|$
"

첫 번째 줄과 마지막 줄을 수정하십시오.


7

젤리 ,  15  14 바이트

Ḳ⁾""j$€⁹¦K¥ⱮJ$

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

방법?

Ḳ⁾""j$€⁹¦K¥ⱮJ$ - Link: list of characters, S
Ḳ              - split (S) at spaces -> A
             $ - last two links as a monad:
           Ɱ   -   map...
            J  -   ...across: range of length -> I = [1,2,...len(A)]
          ¥    -   ...doing: last two links as a dyad: i.e. f(A, i) for i in I
      € ¦      -     sparse application...
       ⁹       -     ...to indices: chain's right argument, i
     $         -     ...action: last two links as a monad:
 ⁾""           -       literal list of characters = ['"', '"']
    j          -       join (with A[i]) -> (e.g. with ['i','s']) ['"','i','s','"']
         K     -     join with spaces

쉽게 저장하십시오 . (유사한 코드를 최초로 게시했기 때문에 여기에 의견을 달기로 결정했습니다. : P)
Outgolfer Erik

@EriktheOutgolfer 덕분에 비슷한 개선 사항을 게시했습니다.
Jonathan Allan

6

자바 스크립트 (ES6),  43 42 41  38 바이트

@mazzy 덕분에 3 바이트 절약

비표준이지만 널리 지원되는 RegExp.left​Context및을 사용 RegExp.rightContext합니다. 그것은 다른 인용문이 많이 있습니다 ...

s=>s.replace(/(\S+) ?/g,`$\`"$1" $'
`)

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


똑똑한! 하지만 테스트 케이스의 쉼표에서 볼This is a significantly "longer,"...
mazzy

/(\S+)/g작동 하지 않습니까?
Shaggy

1
@mazzy 아, 감사합니다. 테스트 케이스를 쉼표로 잘못 읽었으므로 실제로 의도적으로 그렇게했습니다. 이제 수정되었습니다.
Arnauld

@Shaggy 다음 단어의 왼쪽 문맥에 공간이 나타나지 않도록 공간을 캡처해야한다고 생각합니다.
Arnauld

1
@mazzy 정말 괜찮습니다. 감사!
Arnauld

6

자바, 235 183 132 바이트

s->{String a[]=s.split(" "),r="",t;for(int l=a.length,i=0,j;i<l;i++,r+="\n")for(j=0;j<l;)r+=(t=i==j?"\"":"")+a[j++]+t+" ";return r;}

-52 바이트는 다양한 것들을 학대함으로써 (정적 액세스, 목록 대 배열, 반환 대신 인쇄 등. @ValueInk 감사합니다.)
-51 바이트는 게으른 게으르고 @KevinCruijssen이 나를 위해 일
하게합니다.


That's some crazy overhead you need for the java.util.Arrays.copyOfRange. If you utilize java.util.List you can use subList for shorter, and print to STDOUT instead of building an array. I got 193 bytes with those ideas, and also abusing the var keyword.
Value Ink

@ValueInk thanks! I also replaced String.join with s.join for those extra IDE warnings (and -10 bytes).
Benjamin Urquhart

1
@OlivierGrégoire no thank you :^)
Benjamin Urquhart

2
@OlivierGrégoire Challenge accepted and beaten, sir! ;p 71 bytes
Kevin Cruijssen

1
@KevinCruijssen Nice! I haven't even thought regex would do the job. Well done ;-)
Olivier Grégoire

5

First code golf attempt hopefully it's not terrible and hopefully it's not rule breaking

Kotlin, 105 112 147 117 bytes/chars

fun main(a:Array<String>){val q=a[0].split(" ")
q.forEach{println(q.fold(""){i,n->i+if(it==n)"\"$n\" " else n+" "})}}

Try it online!



4

JavaScript, 91 97 75 78 bytes

f= 

t=>t.split` `.map((c,i,a)=>[...a.slice(0,i),`"${c}"`,...a.slice(i+1)].join` `)

// and test
console.log(f("Hello folks and world").join('\n'));

Outputs a list of lines as a JavaScript array. The last entry has a trailing space as allowed in the question. The test code writes each entry to the console on a separate line for demonstration purposes.

Thanks to Shaggy for 19 bytes off and no leading spaces - when the spread operator is used on an empty array to initialize an array literal, no slots are created in the array produced by the spread operator:

let empty = [];
let array = [...empty, value]
//  produces an array of length 1 containing value 

(The 91 byte version had a leading space on the first line, the 97 byte version took 6 bytes to remove it.)



1
The snippet doesn't run because you defined the f function. Otherwise verified. Good job!
krinistof

@krinistof fixed it, thx!
traktor53

Words after the quoted word are separated by commas instead of spaces (Firefox, not sure if that's a browser issue)
wastl

1
@wastl Golfed 3 bytes too many and didn't see the commas due to blurry eyes. Putting back the second spread operator (as in Shaggy"s link) removes the commas . Note to self... put my glasses on next time ;-(
traktor53

4

Python 3, 79, 69, 65 bytes

w,i=input(),0
while~i:m=w.split();m[i]='"%s"'%m[i];print(*m);i+=1

Try it online!

Shaved 10 bytes thanks to xnor. And now this is 65 bytes as per Erik the Outgolfer solution. Program ends with IndexError but this is fine.


2
Terminating with error is fine for programs. A handy trick: you can use print(*l) in Python 3 in place of print(" ".join(l)).
xnor

Even better, use Extended Iterable Unpacking.
xnor

2
65 bytes: Instead of assigning w to input().split(), assign it to input(), then, in the while loop, assign m to w.split(), which will create a new list at each iteration to avoid reference issues, then set m[i] to '"%s"'%m[i] and print(*m).
Erik the Outgolfer

4

Java 8, 72 71 67 62 bytes

s->s.replaceAll("(?<=(^.*))(\\S+) ?(?=(.*$))","$1\"$2\" $3\n")

Try it online.

Explanation:

s->                    // Method with String as both parameter and return-type
  s.replaceAll("...",  //  Replace all matches in this regex
               "...")  //  With this
                       //  And then return the result

Regex explanation:

(?<=(^.*))(\\S+) ?(?=(.*$))   # === MATCH ===
(?<=     )                    # A positive look-behind to:
     ^.*                      #  The optional leading portion of the string
    (   )                     #  (which is captured in capture group 1)
           \\S+               # Followed by one or more non-space characters,
                              # so the next word in line
          (    )              # (which is captured in capture group 2)
                 ?            # Followed by an optional space
                  (?=     )   # Followed by a positive look-ahead to:
                      .*$     #  The trailing optional portion of the string
                     (   )    #  (which is captured in capture group 3)

$1\"$2\" $3\n                 # === REPLACEMENT ===
$1                            # The match of capture group 1
                              # (the leading portion)
    $2                        # Followed by the match of capture group 2
                              # (the current word in the 'iteration'),
  \"  \"                      # surrounded by quotation marks
                              # Followed by a space character
         $3                   # Followed by the match of capture group 3
                              # (the trailing portion)
           \n                 # Followed by a trailing newline

2
You have just paved the way for a multitude of regex answers. Well done.
Benjamin Urquhart

I tried to port this to Python. Sometimes I wish regex parsers were consistent across languages.
Benjamin Urquhart

1
@BenjaminUrquhart Unfortunately they aren't.. Java regex is different than C# regex, Python is different again, Perl is different again, etc. Indeed a bit annoying.
Kevin Cruijssen


3

Ruby, 98 chars.

First submission ever. This can definitely be shortened. I just wanted to get an answer in quickly.

a=->s{s.split.each_index{|i|puts s.split.each_with_index.map{|a,j|i==j ? "\"#{a}\"":a}.join(" ")}}

Try it online!


Welcome to PPCG! My suggestion would be for each index, save s.split as a variable and edit the index you want to have the quotes around it, instead of using the overly verbose each_with_index.map. Also, you can submit the anonymous lambda without naming it, and join can be replaced with a * operator. This drops your byte count to 64 bytes.
Value Ink

Fantastic! I knew there was a shorter way to do the join, but I was trying to get out of the office and wanted to submit something before leaving XD. I didn't realize the rules allowed for anonymous lambdas like that.
snowe

3

Perl 6, 43 40 bytes

{m:ex/^(.*?<<)(\S+)(>>.*)$/>>.join('"')}

Try it online!

Matches all possible words, then joins each list by quotes. This could be one byte shorter if we could output lines in reverse order.

Explanation:

{                                      }  # Anonymous code block
 m:ex/^                  $/               # Match all strings
       (.*?)         (.*)                 # Match before and after sections
            <<(\S+)>>                     # And the actual word (with no spaces)
                           >>.join('"')   # And join each line by "s

3

Reflections, 229 bytes

  _1 +\ /\/(3\  /(0\
/+_:   # \#_: v1=2#_ \
\     /_+/:3; / 1/\:1)
/v(3(2/ \3)(3 ;\#@ \ /
   /:#_(0\:_ / (0*  /0  \
 0 >~    <>~   <0 \  *#_/
 \       /     /\/ v/ 
   \=2#_1/\2#_>  (0~
                 \ ^\
\                   /

Test it!

I "quickly" "golfed" this in a "funny" "golfing" language.

Looking at all that whitespace, it could probably be shorter.



2

Stax, 10 bytes

▓¼MY@≈╢∞◙╗

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

jY      split on spaces and store in y register
m       for each word, run the rest of the program and implicitly output
  '"|S  surround with double quotes
  yia&  start with register y, and replace the ith element, where i is the iteration index
  J     join with spaces

Run this one


2

C (gcc), 136 133 bytes

As C's tokenizing functions would mess up the string on future reads, I instead calculate the number and offsets for each word and then finish when the total number of iterations of the outer loop matches the number of words.

i,j=1;f(s,c,t)char*s,*c,*t;{for(i=0;i++<j;puts(""))for(j=0,c=t=s;t;t=c+!!c)printf("%3$s%.*s%s ",(c=index(t,32))-t,t,"\""+!!(i-++j));}

Try it online!


Swapping "\""+!!(i-++j) for i-++j?"":"\"" saves you a byte.
gastropner

2

PowerShell, 60 40 36 bytes

-20 bytes inspired by Arnauld

$args-replace'(\S+) ?','$`"$1" $''
'

Try it online!

The result has one extra space and one empty line in the tail.


Powershell, no regexp, 60 bytes

($w=-split$args)|%{$p=++$c
"$($w|%{$q='"'*!--$p
"$q$_$q"})"}

Try it online!

Less golfed:

$words=-split $args                     # split by whitespaces
$words|%{
    $position=++$counter
    $array=$words|%{
        $quotation='"'*!--$position     # empty string or quotation char
        "$quotation$_$quotation"
    }
    "$($array)"                         # equivalent to $array-join' '
}

Neither works if the input words contain tabs or other whitespace. From the challenge, only spaces delimit words.
AdmBorkBork

you are right, of course. But rules are: 1. The input only contains printable ASCII characters., 2. The input may contain spaces. Tabs and other whitespace is not printable ASCII, is not it? :)
mazzy

1
I suppose that's true - I was only basing my statement off of the OP's comment here, but that hasn't been edited into the challenge ... so I suppose your submission is fine as it currently is.
AdmBorkBork

2

JavaScript, 62 bytes

Thanks @Shaggy for golfing off 10 bytes

f=
x=>x.split` `.map((c,i,a)=>(s=[...a],s[i]=`"${c}"`,s.join` `))

console.log(f("Hello folks and world").join('\n'));

Explanation

  • The function splits the string at each space (x.split` `)
  • For each element in the resulting array perform the following function
  • Create a shallow copy of the array (s=[...a])
  • Replace the nth element in the array with itself surrounded with quotation marks (s[i]=`"${c}"`)
  • return the shallow copy joined with spaces (s.join` `)



2

R, 94 76 bytes

-18 bytes thanks to Giuseppe

m=matrix(s<-scan(,a<-'"'),n<-length(s),n);diag(m)=paste0(a,s,a);write(m,1,n)

Try it online!

Thanks to digEmAll for setting up the TIO properly. It takes in e.g. This is codegolf and outputs correctly

"This" is codegolf 
 This "is" codegolf 
 This is "codegolf" 

It uses a matrix format with the sentence repeated n times; then we only need to change the diagonal entries. Note that usually, in R code-golf, strings are read in with scan(,""), but any string can be used instead of the empty string as the what (or w) parameter.

Explanation of old ungolfed version:

s <- scan(t=scan(,''),w=t)    # read in input and separate by spaces
n <- length(s)                # number of words
m = matrix(s, n, n)           # fill a matrix, one word per entry, each column corresponds to the whole sentence. The sentence is repeated n times.
diag(m) = paste0('"', s, '"') # replace diagonal entries with the corresponding word surrounded by quotes
cat(rbind(m,"\n"))        # add a \n at the end of each column, then print column-wise


@Giuseppe Thanks! How did I not see that I didn't need two calls to scan??
Robin Ryder

Sometimes you just get into a golfing groove. If we can use other quotes than "", we can reduce to 68 bytes using sQuote.
Giuseppe

2

This is my first code golf. hopefully its not shit.

EDIT: got it down to 54 bytes with a better regular expression.

**EDIT 2: per suggestions, fixed a bug and made it shorter **

JavaScript (V8), 46 bytes

t=>t.split(' ').map(v=>t.replace(v,'"'+v+'"'))

Try it online!


5
If the input contains duplicate words, subsequent copies never get quoted.
recursive

Splitting on spaces would be shorter.
Shaggy

@recursive should be fixed.
r3wt

@Shaggy thanks, i incorporated your suggestion
r3wt

1
Still doesn't work for duplicate words
Jo King


2

Elm Using recursion, 132,130,121,111,100 99 bytes

Golfed down 9 bytes thanks to Kevin Cruijssen technique and another 22 bytes were cracked by ASCII-only. Turned to non-tail recursion during the golf.

f b a=case a of
 c::r->String.join" "(b++("\""++c++"\"")::r)::f(b++[c])r
 _->[]
u=f[]<<String.words

Try it online

85 bytes after exposing String functions to the current scope

f b a=case a of
 c::r->join" "(b++("""++c++""")::r)::f(b++[c])r
 _->[]
u=f[]<<words

Ungolfed version (Using tail recursion)

push : List a -> a -> List a
push list el =
    list ++ [ el ]

zip : (List a -> a -> List a -> b) -> List a -> List a -> List b -> List b
zip transform before after mapped =
    case after of
        [] ->
            mapped

        current :: rest ->
            transform before current rest
                |> push mapped
                |> zip transform (push before current) rest

wrap : appendable -> appendable -> appendable
wrap v str =
    v ++ str ++ v

cb : List String -> String -> List String -> String
cb before current rest =
    before ++ wrap "\"" current :: rest
        |> String.join " "

result : List String
result =
    zip cb [] (String.words "This is code golf") []

Try ungolfed


2

Japt, 14 12 bytes

¸£¸hYQ²i1X)¸

Try it

2 bytes saved thanks to Oliver.

¸£¸hYQ²i1X)¸     :Implicit input of string
¸                :Split on spaces
 £               :Map each X at index Y
  ¸              :  Split input on spaces
   hY            :  Set the element at index Y to
     Q           :    Quotation mark
      ²          :    Repeat twice
       i1X       :    Insert X at 0-based index 1


D'oh! Of course! Thanks, @Oliver.
Shaggy

1

PowerShell, 70 65 bytes

param($a)$a.Split()|%{$a-replace[regex]"( |^)$_( |$)"," ""$_"" "}

Try it online!

Has test suite in trial. Has 1 leading space on first row, and 1 trailing space on last row. Attempting to refactor.


4
This doesn't work if you have a duplicate word in the test string.
snowe

1

Charcoal, 19 bytes

E⪪θ ⪫E⪪θ ⎇⁼κμ⪫""λλ 

Try it online! Link is to verbose version of code. Note: Trailing space. Explanation:

  θ                     Input string
 ⪪                      Split on literal space
E                       Map over words
       θ                Input string
      ⪪                 Split on literal space
     E                  Map over words
            μ           Inner index
          ⁼             Equals
           κ            Outer index
         ⎇             If true then
               ""       Literal string `""`
              ⪫         Joined i.e. wrapping
                 λ      Current word
                  λ     Otherwise current word
    ⪫                  Joined with literal space
                        Implicitly print each result on its own line

1

Attache, 34 bytes

Join&sp=>{On&_&Repr=>Iota@_}@Split

Try it online! Anonymous function returning a list of lines.

Explanation

Join&sp=>{On&_&Repr=>Iota@_}@Split
                             Split      Splits the input on whitespace
         {         =>Iota@_}            Over each number K, 0 to #words - 1
          On  &Repr                     Apply the Repr (quoting) function
            &_                          on the Kth element in the input
Join&sp=>                               then rejoin the words of each inner sentence

1

C# (Visual C# Interactive Compiler), 123 bytes

I wonder if can this be shortened with regular expressions.

s=>(r=s.Split(' ')).Select((a,i)=>(string.Join(" ",r.Take(i))+" \""+a+"\" "+string.Join(" ",r.Skip(i+1))).Trim());string[]r

Try it online!




Port of Java answer - 104 :)
dana


@KevinCruijssen - I saw you got that regex earlier :) Figured that was a totally different approach so I didn't try porting it over, but yeah that is a good solution!
dana
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.