As programmers say: Strive to be lazy

25

4

Story

Have you seen this post from 9gag? Maybe you got the feeling to make your own sentences. But then you realize that you could just golf a script in half an hour, and you will never have to deal time with that.

The submission

Your program will get an input string which it will return with added quotation marks as explained below. Standard loopholes are forbidden. Output as a list of lines is allowed. Trailing spaces and empty lines that don't break the output are allowed.

The rules of input

  • The input only contains printable ASCII characters.
  • The input may contain spaces. The words are determined with them.
  • It's guaranteed that a space will never be followed by another space.
  • The case of no input or empty string doesn't matter.

The rules of output

If one word is given then the program has to return the string between quotation marks.

If the input string has 2 or more words, it first returns the initial input, but the first word is in quotation marks. Then on the next line, it returns the initial input, but with the second word in quotes. And so on for the remaining words.

In general, the program has to return as many lines as there are words in the input.

Examples:

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"

This is , so the least byte answer wins!

krinistof

Posted 2019-05-10T20:54:07.983

Reputation: 431

7Will there be duplicate words? – Embodiment of Ignorance – 2019-05-10T22:26:28.920

10Can we assume the input string will not contain " characters? – Doorknob – 2019-05-10T23:00:11.073

1

Re "Strive to be lazy": I think this is a misrepresentation of what Larry Wall said. - "Most folks see laziness as a synonym for slacker or couch potato, but Wall's definition is about efficiency."

– Peter Mortensen – 2019-05-11T02:47:20.260

14This "problem" should be "fun" to "golf". – Lyxal – 2019-05-11T06:26:03.677

3Can we use different quotes, like '', ‘’, or “”, rather than ""? – Giuseppe – 2019-05-13T17:59:52.123

Answers

10

vim, 38 bytes

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

Try it online!

Requires the vim-surround plugin.

If the input does not contain " characters, this can be done in 19 bytes:

qqysW"Ypds"W@qq@qdk

Here, we record a recursive macro (qq ... @qq@q) that surrounds a word with quotation marks (ysW"), duplicates the line (Yp), deletes the quotation marks (ds"), and moves to the next word (W) before calling itself recursively. After it terminates, there are two extraneous lines, which are deleted with dk.

The full solution simply wraps this with :s/"/<C-d>/g at the beginning, which replaces existing " characters with an unprintable character, and :%s/<C-d>/"/g at the end, which undoes the replacement.

Doorknob

Posted 2019-05-10T20:54:07.983

Reputation: 68 138

2I actually made the examples with the same method :D – krinistof – 2019-05-11T11:41:56.240

8

Haskell, 65 bytes

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

Returns a list of lines.

Try it online!

nimi

Posted 2019-05-10T20:54:07.983

Reputation: 34 639

This seems to fail when the input contains quotation marks, newlines or other escaped charcters. – Post Rock Garf Hunter – 2019-05-12T15:14:33.430

@SriotchilismO'Zaic: fixed. Thanks for pointing out. Regarding the shorter version: xnor already posted this as an answer.

– nimi – 2019-05-13T19:17:20.810

Not quite fixed, since words considers \n to be whitespace it behaves inproperly when it is present. – Post Rock Garf Hunter – 2019-05-14T03:19:43.683

@SriotchilismO'Zaic: "The input only contains printable ASCII characters", which is Space to ~. "The input may contain spaces" - not "whitespace". – nimi – 2019-05-14T05:08:32.273

7

Retina 0.8.2, 17 bytes

 
" $'¶$` "
^|$
"

Try it online! Link includes test suite. Explanation:

 
" $'¶$` "

Expand each space by duplicating the line and then inserting quotation marks.

^|$
"

Fix the first and last lines.

Neil

Posted 2019-05-10T20:54:07.983

Reputation: 95 035

7

Jelly,  15  14 bytes

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

Try it online!

How?

Ḳ⁾""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

Jonathan Allan

Posted 2019-05-10T20:54:07.983

Reputation: 67 804

Easy save. (Decided to comment here because you were the first to post similar code. :P) – Erik the Outgolfer – 2019-05-11T15:31:27.190

@EriktheOutgolfer thanks, came back to post a similar improvement myself. – Jonathan Allan – 2019-05-11T16:26:27.257

6

Java, 235 183 132 bytes

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 bytes by abusing a variety of things (static access, list vs array, print instead of returning, etc. Thanks @ValueInk!)
-51 bytes by beung lazy and letting @KevinCruijssen do the work for me
Try it online

Benjamin Urquhart

Posted 2019-05-10T20:54:07.983

Reputation: 1 262

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 – 2019-05-11T01:17:43.440

@ValueInk thanks! I also replaced String.join with s.join for those extra IDE warnings (and -10 bytes). – Benjamin Urquhart – 2019-05-11T17:44:47.687

132 bytes – Kevin Cruijssen – 2019-05-13T09:24:58.797

@KevinCruijssen thanks – Benjamin Urquhart – 2019-05-13T12:23:10.173

Beaten with 117 bytes! Your turn ;) – Olivier Grégoire – 2019-05-13T12:59:48.180

1@OlivierGrégoire no thank you :^) – Benjamin Urquhart – 2019-05-13T13:01:28.320

2

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

– Kevin Cruijssen – 2019-05-14T15:55:23.747

1@KevinCruijssen Nice! I haven't even thought regex would do the job. Well done ;-) – Olivier Grégoire – 2019-05-14T16:26:25.843

@OlivierGrégoire Yeah, at first I wasn't sure it was possible. Took a bit of fiddling around with the positive look-behind and look-ahead before I got it to work, which was both annoying and fun to do (and kind of distracting from my actual job-work, haha xD). And the 71 byte version wasn't too efficient I now notice, since I'm now at 62 bytes. :) – Kevin Cruijssen – 2019-05-14T19:55:01.583

6

JavaScript (ES6),  43 42 41  38 bytes

Saved 3 bytes thanks to @mazzy

Uses the non-standard but widely supported RegExp.left​Context and RegExp.rightContext. That's a lot of different quotes...

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

Try it online!

Arnauld

Posted 2019-05-10T20:54:07.983

Reputation: 111 334

Smart! But see on the comma in the test case This is a significantly "longer,"... – mazzy – 2019-05-12T08:20:37.890

Wouldn't /(\S+)/g work? – Shaggy – 2019-05-12T10:50:03.750

1@mazzy Oh, thanks. I actually did it that way on purpose because I misread the test case with a comma. Now fixed. – Arnauld – 2019-05-12T11:00:22.260

@Shaggy I think we need to capture the space so that it doesn't appear in the left context of the next word. – Arnauld – 2019-05-12T11:01:03.383

(@Shaggy But your comment brought to light that I forgot to remove the /i. Thanks!) – Arnauld – 2019-05-12T11:21:59.987

The code appends tail empty line. Why not add an extra space to the last line? s.replace(/(\S+) ?/g,$\"$1" $' – mazzy – 2019-05-12T12:32:50.357

1@mazzy I guess that's fine indeed. Thanks! – Arnauld – 2019-05-12T12:39:55.173

The only problem with using just /\S+/g is that it adds a leading space to all but the first line. It's been asked in the comments whether that's allowed.

– Shaggy – 2019-05-13T13:22:55.203

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!

Quinn

Posted 2019-05-10T20:54:07.983

Reputation: 1 153

4

05AB1E, 14 bytes

ð¡©ε®y…"ÿ"Nǝ}»

Try it online!


+1 byte (and it works for the edge case) thanks to Emigna. -1 byte thanks to Kevin!

Magic Octopus Urn

Posted 2019-05-10T20:54:07.983

Reputation: 19 422

1Unfortunately you need to use ð¡ to handle input such as test. – Emigna – 2019-05-11T11:08:30.223

1-1 byte by using a map and ». – Kevin Cruijssen – 2019-05-13T09:30:32.210

4

Ruby with -an, 53 bytes

The flags -an are read each line and split to $F.

$F.size.times{|i|a=$F.dup;a[i]=?"+a[i]+?";puts a*' '}

Try it online!

Value Ink

Posted 2019-05-10T20:54:07.983

Reputation: 10 608

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.)

traktor53

Posted 2019-05-10T20:54:07.983

Reputation: 299

278 bytes – Shaggy – 2019-05-11T07:22:19.577

1The snippet doesn't run because you defined the f function. Otherwise verified. Good job! – krinistof – 2019-05-13T10:24:45.493

@krinistof fixed it, thx! – traktor53 – 2019-05-13T14:16:48.710

Words after the quoted word are separated by commas instead of spaces (Firefox, not sure if that's a browser issue) – wastl – 2019-05-13T15:16:04.477

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 – 2019-05-13T15:36:05.067

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.

Андрей Ломакин

Posted 2019-05-10T20:54:07.983

Reputation: 309

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 – 2019-05-11T06:43:08.290

Even better, use Extended Iterable Unpacking.

– xnor – 2019-05-11T06:52:42.513

265 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 – 2019-05-11T15:18:50.857

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

Kevin Cruijssen

Posted 2019-05-10T20:54:07.983

Reputation: 67 575

2You have just paved the way for a multitude of regex answers. Well done. – Benjamin Urquhart – 2019-05-14T17:17:33.123

I tried to port this to Python. Sometimes I wish regex parsers were consistent across languages. – Benjamin Urquhart – 2019-05-15T17:00:18.290

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 – 2019-05-15T17:09:03.283

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!

snowe

Posted 2019-05-10T20:54:07.983

Reputation: 131

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 – 2019-05-11T00:04:10.280

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 – 2019-05-11T00:17:16.540

3

Haskell, 64 bytes

map unwords.g.words
g(h:t)=(('"':h++"\""):t):map(h:)(g t)
g _=[]

Try it online!

Outputs a list of strings. Based on nimi's answer.

xnor

Posted 2019-05-10T20:54:07.983

Reputation: 115 687

This answer like nimi's doesn't work properly when the input contains escaped characters like \n or ". – Post Rock Garf Hunter – 2019-05-14T03:18:52.440

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

Jo King

Posted 2019-05-10T20:54:07.983

Reputation: 38 234

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.

wastl

Posted 2019-05-10T20:54:07.983

Reputation: 3 089

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

Robin Ryder

Posted 2019-05-10T20:54:07.983

Reputation: 6 625

76 bytes – Giuseppe – 2019-05-13T15:16:01.300

@Giuseppe Thanks! How did I not see that I didn't need two calls to scan?? – Robin Ryder – 2019-05-13T16:47:07.917

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

– Giuseppe – 2019-05-13T18:01:19.377

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

recursive

Posted 2019-05-10T20:54:07.983

Reputation: 8 616

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` `)

fəˈnɛtɪk

Posted 2019-05-10T20:54:07.983

Reputation: 4 166

62 bytes – Shaggy – 2019-05-12T09:02:11.330

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!

r3wt

Posted 2019-05-10T20:54:07.983

Reputation: 121

5If the input contains duplicate words, subsequent copies never get quoted. – recursive – 2019-05-12T00:08:39.443

Splitting on spaces would be shorter. – Shaggy – 2019-05-12T08:56:49.983

@recursive should be fixed. – r3wt – 2019-05-13T18:05:50.013

@Shaggy thanks, i incorporated your suggestion – r3wt – 2019-05-13T18:06:00.843

1Still doesn't work for duplicate words – Jo King – 2019-05-14T22:14:34.753

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!

ErikF

Posted 2019-05-10T20:54:07.983

Reputation: 2 149

Swapping "\""+!!(i-++j) for i-++j?"":"\"" saves you a byte. – gastropner – 2019-05-16T20:53:58.870

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' '
}

mazzy

Posted 2019-05-10T20:54:07.983

Reputation: 4 832

Neither works if the input words contain tabs or other whitespace. From the challenge, only spaces delimit words. – AdmBorkBork – 2019-05-13T20:31:31.467

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 – 2019-05-13T20:54:23.253

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 – 2019-05-14T12:26:03.493

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

Shaggy

Posted 2019-05-10T20:54:07.983

Reputation: 24 623

12 bytes – Oliver – 2019-05-15T13:26:01.183

D'oh! Of course! Thanks, @Oliver. – Shaggy – 2019-05-15T17:30:38.147

2

Java (JDK), 104 bytes

t->{var w=t.split(" ");int i=0;for(var s:w){w[i]='"'+s+'"';System.out.println(s.join(" ",w));w[i++]=s;}}

Try it online!

Olivier Grégoire

Posted 2019-05-10T20:54:07.983

Reputation: 10 647

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

Evgeniy Malyutin

Posted 2019-05-10T20:54:07.983

Reputation: 141

2

C# (Visual C# Interactive Compiler) with /u:System.Text.RegularExpressions.Regex flag, 59 40 bytes

s=>Replace(s,"(\\S+) ?","$`\"$1\" $'\n")

Port of my Java 8 answer, so look there for an explanation.
-19 bytes by porting @Arnauld's regex, since the $` and $' are supported in C# .NET.

Try it online.

Kevin Cruijssen

Posted 2019-05-10T20:54:07.983

Reputation: 67 575

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.

KGlasier

Posted 2019-05-10T20:54:07.983

Reputation: 211

4This doesn't work if you have a duplicate word in the test string. – snowe – 2019-05-10T23:14:03.180

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

Neil

Posted 2019-05-10T20:54:07.983

Reputation: 95 035

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

Conor O'Brien

Posted 2019-05-10T20:54:07.983

Reputation: 36 228

1

Perl 6, 46 bytes

{map {.prematch~"\"$_\""~.postmatch},m:g/\S+/}

Try it online!

bb94

Posted 2019-05-10T20:54:07.983

Reputation: 1 831

The match part can just be m:g/\S+/, and I think the pre/post match part can be shorter too – Jo King – 2019-05-11T06:33:18.813

/\S/ doesn't match the tab character. I'm actually not sure how whitespace other than space should be treated. – bb94 – 2019-05-11T06:47:55.420

The question says printable ASCII, which only includes spaces, not tabs or newlines – Jo King – 2019-05-11T06:48:54.330

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!

my pronoun is monicareinstate

Posted 2019-05-10T20:54:07.983

Reputation: 3 111

118 bytes – Innat3 – 2019-05-13T16:43:30.517

110 bytes – dana – 2019-05-15T03:48:17.510

Port of Java answer - 104 :)

– dana – 2019-05-15T04:05:17.030

1

@dana My port is shorter, though ;)

– Kevin Cruijssen – 2019-05-15T12:06:43.240

@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 – 2019-05-15T12:20:04.773

1

Jelly, 15 bytes

⁾""j$€⁹¦K
ḲçⱮL$

Try it online!

Thanks to @JonathanAllan for saving 4 bytes

Nick Kennedy

Posted 2019-05-10T20:54:07.983

Reputation: 11 829

I'm pretty sure you need to count the Y unless you get the OP to allow a list of lines as function output. You can then save 4 like this (although mine is then just a one Link version of that).

– Jonathan Allan – 2019-05-11T11:07:17.437

@JonathanAllan it says a list of lines is ok as output. I’ve added in your improvements - hope that’s ok. Thanks. – Nick Kennedy – 2019-05-11T11:15:29.320

Ah so it does! :) – Jonathan Allan – 2019-05-11T11:54:01.007

1

Red, 113 bytes

func[s][repeat i length? u: split s" "[j: 1
foreach w u[prin rejoin[t: pick[{"}""]i = j w t sp]j: j + 1]prin lf]]

Try it online!

Galen Ivanov

Posted 2019-05-10T20:54:07.983

Reputation: 13 815

1

APL+Win, 59 bytes

(⌽⍳⍴s)⊖((¯1 0+⍴s)⍴s)⍪(('"',¨s←(+\' '=s)⊂s←' ',⎕),¨'"')~¨' '

Prompts for string

Try it online! Courtesy of Dyalog Classic

Graham

Posted 2019-05-10T20:54:07.983

Reputation: 3 184

1

J, 45 bytes

   f =: ' 'joinstring"1(]`(dquote&.>])@.=($~$@=))@cut
   f 'this is a test string'
"this" is a test string
this "is" a test string
this is "a" test string
this is a "test" string
this is a test "string"

If the input can be a list of boxes, then my solution can be 30 bytes:

   f =: (]`(dquote&.>])@.=($~$@=))@cut
   f 'this is a test'
┌──────┬────┬───┬──────┐
│"this"│is  │a  │test  │
├──────┼────┼───┼──────┤
│this  │"is"│a  │test  │
├──────┼────┼───┼──────┤
│this  │is  │"a"│test  │
├──────┼────┼───┼──────┤
│this  │is  │a  │"test"│
└──────┴────┴───┴──────┘

hoosierEE

Posted 2019-05-10T20:54:07.983

Reputation: 760

+1 from me, but I think you need to make it a verb to comply with the PPCG rules:

Try it online:

– Galen Ivanov – 2019-05-13T10:53:35.690

1Ah I didn't realize that was a rule. Fixed. – hoosierEE – 2019-05-13T12:58:56.033

1

Python 3, 107 bytes

import re
def f(s):
 for w in re.finditer('[^ ]+',s):p=w.span();print(f'{s[:p[0]]}"{w.group()}"{s[p[1]:]}')

Try it online!

I... decided to use regex against my better judgement. This is the result.

Artemis still doesn't trust SE

Posted 2019-05-10T20:54:07.983

Reputation: 525

1

Oracle SQL, 92 bytes

select regexp_replace(s,'(\S+)','"\1"',1,level)from t connect by level<regexp_count(s,' ')+2

Assuming there is a table in a form

create table t as select 'This is a significantly longer, but not the longest testcase' s from dual;

Test in SQL*Plus

SQL> select regexp_replace(s,'(\S+)','"\1"',1,level)from t connect by level<regexp_count(s,' ')+2
  2  /

REGEXP_REPLACE(S,'(\S+)','"\1"',1,LEVEL)
--------------------------------------------------------------------------------
"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"

10 rows selected.

Dr Y Wit

Posted 2019-05-10T20:54:07.983

Reputation: 511

1

SNOBOL4 (CSNOBOL4), 93 bytes

	S =' '
	I =INPUT S
S	I ARB . R S REM . I	:F(END)
	OUTPUT =L '"' R '"' S I
	L =L R S	:(S)
END

Try it online!

Each line ends with an additional space.

Giuseppe

Posted 2019-05-10T20:54:07.983

Reputation: 21 077

0

Python 2, 108 bytes

def f(s):
 W=s.split();n=len(W)
 for x in range(n*n):print[W[x%n],'"'+W[x%n]+'"'][x%-~n==0]+'\n'*(x%n==n-1),

Try it online!

Chas Brown

Posted 2019-05-10T20:54:07.983

Reputation: 8 959

0

PHP, 134 bytes

<?php $i=explode(' ',file_get_contents('php://stdin'));for($x=0;$x<count($i);$x++){$o=$i;$o[$x]='"'.$i[$x].'"';echo join(' ',$o).'
';}

Try it online!

Scoots

Posted 2019-05-10T20:54:07.983

Reputation: 679