Helloellolloloo Worldorldrldldd

50

13

Make a program that takes the word you input, and adds that word to the back of itself minus its first letter, then repeats until all letters are gone. For example, cat would become catatt, and hello would become helloellolloloo.

Input
Any of the 26 letters of the English alphabet. There may be multiple words separated by spaces, and the change should be applied to every word.

Output
The word(s) inputted, with each word put after itself with its first letter missing, and then with its second letter missing, and so on until there are no more letters to add.

More examples:

ill eel outputs illlll eelell

laser bat outputs laserasersererr batatt

darth vader outputs dartharthrththh vaderaderdererr

This is code golf, so the shortest code wins.

Clarification:
You can treat the input or output as a list. You can separate words using newline instead of space. You can add a trailing space to the input.

qazwsx

Posted 2018-09-18T22:25:04.353

Reputation: 1 048

22honestly, the multiple words thing is kinda annoying. All it does is require a split, apply the function on each word, and then join again. It's also quite debilitating for lots of esolangs which have to check for a space manually – Jo King – 2018-09-18T22:44:39.537

Can I require a trailing space in the input? – Jonathan Frech – 2018-09-18T23:20:17.377

sure, you can require a trailing space – qazwsx – 2018-09-18T23:36:45.303

4Can we take in input as a list of words and output as such? – Quintec – 2018-09-18T23:53:54.370

1yes you can Quintec – qazwsx – 2018-09-19T00:24:51.400

4What length words do you need to handle? – MickyT – 2018-09-19T01:14:47.417

5Is it OK for words to be separated by a newline in the output(instead of a space)? – JayCe – 2018-09-19T01:37:38.937

1Off topic, but FWIW, this is the exact output you would normally get when you type stuff on the new Macbook, the one with the butterfly keyboard. – SeaWarrior404 – 2018-09-19T08:03:41.037

Does it need to handle blank input – u_ndefined – 2018-09-19T08:27:53.283

101. Please update the spec with the new allowances (array I/O, trailing space, etc.) 2. Please inform the existing solutions in case any can save bytes by taking advantage of them. – Shaggy – 2018-09-19T08:36:55.423

Can the program take input on separate lines, one word per line? – Doorknob – 2018-09-19T18:57:51.113

Can we assume a word is not longer than the range of the native integer? – NieDzejkob – 2018-09-20T17:14:11.660

yes niedzejkob extra character – qazwsx – 2018-09-20T17:43:48.607

Hello, Welcome to PPCG! If you want to reply to a question asked by a commenter and ensure they're notified, you can use @. Also, as @Shaggy mentioned, make sure to edit the question with this new information to make sure it's always up-to-date. – JayCe – 2018-09-20T18:22:16.443

2@JoKing: so you only want simple puzzles and you're worried that you need 3 bytes more, 1 for splitting, 1 for looping and 1 for joining? Sorry, I implement in C# and I need 200 bytes just for keywords. – Thomas Weller – 2018-09-25T19:52:39.013

You never answered @MickyT's comment, is 9223372036854775807 characters as an upper limit for string length okay? – ბიმო – 2018-10-01T16:33:30.253

@BMO I thought there was a meta consensus that you didn't need to worry about reasonable implementation limits, but finding things again on meta is a black art. – Ørjan Johansen – 2018-10-02T03:47:33.923

Answers

33

Japt -m, 6 3 bytes

Input and output are arrays of words.

£sY

Try it


Explanation

        :For each word in the input array
£       :Map each letter at index Y
 sY     :  Slice the current word from index Y

Shaggy

Posted 2018-09-18T22:25:04.353

Reputation: 24 623

1Thats really compact. Nice! – qazwsx – 2018-09-18T23:37:53.990

9@qazwsx: Now 50% more compact! – Shaggy – 2018-09-19T10:38:05.713

1Isn't £ two bytes in UTF-8? – Vi. – 2018-09-20T16:12:23.180

7@Vi, I'm not using UTF-8 here. – Shaggy – 2018-09-20T16:16:37.100

36

brainfuck, 60 56 bytes

,[>++++++++[-<----<++++>>]<[>>]<[[<]>.[[-]>[.>]<[<]>]],]

Try it online!

Requires a trailing space and prints a leading space. Both of these could be circumvented, but that ends up at 112 bytes.

Explanation

,[  Loop over each byte of input
  Tape: 32 w o r-32 d'
  >++++++++[-<----<++++>>]   Subtract 32 from the character and add 32 to the previous char
  Tape: 32 w o r d-32 0'
  <[>>]<   If the last character was a space
  Tape: 32 w o r d-32 0'
  or
  Tape: 32 w o r d' space-32
  [
    [<]>.   Move to the end of the word and print out the space
    [   Loop over each letter
      [-]    Remove the first letter (initially space)
      >[.>]  Print the rest of the word
      <[<]>  Move back to the first letter
    ]
    Tape: clear
  ]
,]  Get the next byte of input

Jo King

Posted 2018-09-18T22:25:04.353

Reputation: 38 234

21

Haskell, 36 21 bytes

map$concat.scanr(:)""

Try it online!

Edit: -15 bytes, because of new IO format (list of words instead of space separated words)

nimi

Posted 2018-09-18T22:25:04.353

Reputation: 34 639

You could shave off 5 characters by replacing scanr (:) "" with tails. – Frerich Raabe – 2018-09-20T11:56:54.127

1@FrerichRaabe: yes, but that would require an import Data.List which adds 17 bytes to the score. – nimi – 2018-09-20T16:37:37.403

18

Perl -p, 36 25 23 bytes

s!\b|\S!$'=~s/ .*//r!eg

Try it online!

This is a single regsub. First, it matches all word boundaries or non-space characters:

[][H][e][l][l][o] [][W][o][r][l][d]

Note that each of these matches should be replaced with the rest of the word:

[→Hello][H→ello][e→llo][l→lo][l→o][o→] (...)

We can accomplish this with the special variable $', which stores the part of the string after the match. However, we need to apply the nested regsub s/ .*// to it, which removes everything past the first space in $', in order to get rid of the remaining words in the input.

Thanks to @nwellnhof for 2 bytes.

Doorknob

Posted 2018-09-18T22:25:04.353

Reputation: 68 138

You can replace [^ ] with \S. – nwellnhof – 2018-09-19T10:21:59.153

17

Jelly, 3 bytes

ḊƬ€

Try it online!

Don’t need the Ks anymore since array input/output is now allowed.

ḊƬ€
  €   For each word:
Ḋ       Remove the first letter
 Ƭ      until there are none left.

dylnan

Posted 2018-09-18T22:25:04.353

Reputation: 4 993

I think you need ḊƬẎ) (or ḊƬF), if you prefer). – Erik the Outgolfer – 2018-09-19T15:10:45.647

@EriktheOutgolfer I don't think so. Each word is represented by a separate array in the output – dylnan – 2018-09-19T16:46:32.350

1I'm not sure if you can claim that, since the arrays are nested, and nothing is specified in the question to allow it. – Erik the Outgolfer – 2018-09-19T17:44:21.060

17

Python 3, 49 bytes

d=lambda s:' '.join(n+d(n[1:])for n in s.split())

Try It Online!

This takes advantage of the fact that "".split() returns an empty array so that acts as the check for the base case in the recursion.

Cameron Aavik

Posted 2018-09-18T22:25:04.353

Reputation: 723

15

JavaScript (ES6), 33 bytes

Saved 1 byte thanks to @ShieruAsakoto

I/O format: array of words.

a=>a.map(g=w=>w&&w+g(w.slice(1)))

Try it online!


JavaScript (ES6), 35 bytes

I/O format: array of words.

a=>a.map(w=>w.replace(/./g,"$&$'"))

Try it online!

Arnauld

Posted 2018-09-18T22:25:04.353

Reputation: 111 334

244: s=>s.replace(/\S+/g,g=s=>s&&s+g(s.slice(1))) – Shieru Asakoto – 2018-09-19T00:43:14.530

1Thanks for my "something new" for today; never knew about $' (or $<backtick>). – Shaggy – 2018-09-19T22:07:56.357

15

APL(Dyalog), 19 9 bytes

{⌽∊,\⌽⍵}¨

thanks to @H.PWiz for jogging my brain

This works because all strings in APL are character arrays.

{⌽∊,\⌽⍵}¨ 
        ¨ - for each string
      ⍵} - string argument - ex. "hello"
     ⌽ - reverse - "olleh"
   ,\ - scan magic - "o" "ol" "oll" "olle" "olleh"
  ∊ - enlist(join together) "oolollolleolleh"
{⌽ - reverse - "helloellolloloo"

TIO

Quintec

Posted 2018-09-18T22:25:04.353

Reputation: 2 801

13

R, 82 75 67 bytes

write(sapply(x<-scan(,""),substring,1:(y=max(nchar(x))),y),1,y,,"")

Try it online!

Several bytes saved thanks to JayCe

Separates output with newlines.

The sapply(...) expression generates a matrix/column vector of the appropriate substrings, padding with "" as needed. write then prints the elements of the matrix, y per line, separating them with "".

Giuseppe

Posted 2018-09-18T22:25:04.353

Reputation: 21 077

4Golfed a different approach while holding a sleepy baby; will add an explanation later. – Giuseppe – 2018-09-19T00:30:34.670

2If the length of the words are restricted, eg 99 chars or ~1e6 then you can knock of a bunch of bytes with ...substring,1:1e6,1e6)... or similar – MickyT – 2018-09-19T01:30:47.447

2

If you can separate words by a newline: tio. I have asked this in a comment. Can work with@MickyT ‘s comment

– JayCe – 2018-09-19T01:39:47.563

@JayCe looks like that could be 67 bytes before incorporating MickyT's suggestion

– Giuseppe – 2018-09-19T13:18:59.700

8

brainfuck, 94 93 bytes

-[-[-<]>>+<]>-<<+[[[-]<,[->+>+<<]>[-<+>]>>[-<->>+<]<]<<[>>+<<[-]]<[<]>[[.>]<[<]>[-]>]>>>>.<<]

Try it online!

  • Saved one byte thanks to Nitrodon -- golfing .[-]>[.>]<[<]> to [.>]<[<]>[-]>.

Explanation

[[[ (dynamic) tape layout: ... NUL STR ... STR CHR FLG BUF SPC NUL ... ]]]

load a 32 into SPC
-[-[-<]>>+<]>-

while FLG
<<+[

 read a word
 [
  clear FLG; read CHR
  [-]<,
  copy CHR to BUF (using FLG as a temporary)
  [->+>+<<]>[-<+>]
  subtract SPC from BUF and save SPC
  >>[-<->>+<]
  move tape layout one to the right
  <
 ]

 strip trailing space; set FLG to true
 << [>>+<<[-]]
 to STR's first character
 <[<]>
 print word in all reduced forms
 [
  [.>]<[<]>[-]>
 ]

 print SPC; move to FLG
 >>>>.<<
]

Try it online!

Attribution

Esolang's brainfuck constant collection was used for the initial space load.

Jonathan Frech

Posted 2018-09-18T22:25:04.353

Reputation: 6 681

This doesn't seem to terminate. Is that intended? – Jo King – 2018-09-18T23:34:11.663

1@JoKing Yes. In certain implementations it would exceed the tape limit, exiting by error. – Jonathan Frech – 2018-09-18T23:35:53.790

6

Husk, 6 4 bytes

-2 bytes thanks to Jonathan Allan (taking input as a list)!

moΣṫ

Try it online!

Explanation

Takes input as a list of strings and maps the following function:

Σṫ  -- example argument: "abc"
 ṫ  -- tails: ["abc","bc","c"]
Σ   -- concat: "abcbcc"

ბიმო

Posted 2018-09-18T22:25:04.353

Reputation: 15 345

The split & join are possibly no longer required, currently such specification is in a comment. – Jonathan Allan – 2018-09-19T17:23:22.690

6

05AB1E, 5 bytes

€.síJ

Try it online!

Explanation

€.s        # push suffixes of each
   í       # reverse each
    J      # join suffixes

Emigna

Posted 2018-09-18T22:25:04.353

Reputation: 50 798

1

Boring 5-bytes alternative: í€ηJí (since prefixes is a 1-byte builtin instead of 2-bytes like suffixes; still requires an additional reverse-each however at the start however, so the byte-count remains 5).

– Kevin Cruijssen – 2018-09-19T13:19:39.543

6

Vim, 47 bytes (38 key strokes)

Start with your input as the sole line in a Vim buffer.

:s/<Space>/\r/g<CR>ggqaywPlxqqb99@aj0q99@bgg99J

Explanation

This puts each word on its own line, iterates over each line, then rejoins them all. Breaks if words are longer than 99 characters or if your input has more than 99 words.

  1. :s/<Space>/\r/g<CR> replaces spaces with new lines (\r)
  2. gg positions the cursor at the beginning of the first line
  3. qa begins recording macro a:
    • yw yanks the rest of the word
    • P puts it behind the cursor
    • lx removes the first letter of the latter word
    • q stops recording macro a
  4. qb begins recording macro b:
    • 99@a executes macro a ninety-nine times (introduces the character limit)
    • j0 positions the cursor at the start of the next line
    • q stops recording macro b
  5. 99@b executes macro b ninety-nine times (introduces the word limit)
  6. gg positions the cursor at the first line
  7. 99J joins the following ninety-nine lines with spaces (word limit again)

For another 2 bytes (2 key strokes) you could extend the word limit to 999. Another 4 bytes, 9999, etc.

chambln

Posted 2018-09-18T22:25:04.353

Reputation: 81

5

Retina 0.8.2, 15 bytes

 
¶
.
$&$%'
¶
 

Try it online! Note: trailing spaces. Explanation:

Split on spaces.

.
$&$%'

Append its suffix to each letter. The % means that we only get the word's suffix.

Join with spaces.

Neil

Posted 2018-09-18T22:25:04.353

Reputation: 95 035

5

Pepe, 167 153 bytes

REEerEeeEeeeeeRrEEEEerEEEEEeerEErEEeerreErEEeErreEREEEEEEEreereErEerEEEErEEeerrEEreRRErEEEEreREEreeereReeRerEEEEEErEEEeerreEerEEeerEEEEerEEeEreereErEeree

Try it online!

u_ndefined

Posted 2018-09-18T22:25:04.353

Reputation: 1 253

5

16-bit x86 assembly code, 24 bytes

     47             inc    di
     B020           mov    al,20h
l1:  3806           cmp    [si],al
     7212           jb     l5 ;less means end of string
     7401           je     l2  ;equal means space was seen
     4F             dec    di ;overwrite extra space
l2:  E80300         call   l3
     46             inc    si ;move to next character in word
     75F1           jne    l1
l3:  56             push   si
l4:  3806           cmp    [si],al
     A4             movsb      ;copy character
     77FB           ja     l4  ;until either zero or space is seen
     5E             pop    si
l5:  C3             ret

Call with si = pointer to source string, di = pointer to output buffer.
The source string requires a zero byte to end it.
The code is the same in 16- or 32- or 64-bit (si/di become either esi/edi or rsi/rdi).
32-bit code is two bytes larger because of the expanded call.
64-bit code is three bytes larger still because the inc/dec of rsi/rdi attracts a prefix (but if it is known that they are within 32-bit memory space, then they can be esi/edi again to avoid that penalty).

peter ferrie

Posted 2018-09-18T22:25:04.353

Reputation: 804

4

MATL, 18 16 bytes

"@gXH"HX@Jh)]0&h

Input is a cell array of words. Try it online!

Explanation

"         % Implicit input: cell array of strings. For each cell
  @g      %   Push content of current cell, that is, a word
  XH      %   Copy into clipboard H
  "       %   For each letter
    H     %     Push word
    X@    %     Push iteration index
    Jh)   %     Index from that until the end into current word
  ]       %   End
  0       %   Push 0. Will be cast to char. Char(0) is displayed as space
  &h      %   Concatenate horizontally all elements so far. Implicit display

Luis Mendo

Posted 2018-09-18T22:25:04.353

Reputation: 87 464

4

K4 / K (oK), 9 bytes

Solution:

,/'(1_)\'

Try it online!

Explanation:

,/'(1_)\' / the solution
        ' / apply to each
       \  / scan
   (  )   / do this together
    1_    / drop first
,/'       / flatten (,/) each (')

streetster

Posted 2018-09-18T22:25:04.353

Reputation: 3 635

4

C++ (clang), 174 bytes

#include<map>
#include<string.h>
std::string r(std::string w){while(auto x=strchr(w.c_str(),32))return r(w.substr(0,x-w.c_str()))+" "+r(x+1);return w!=""?w+r(w.substr(1)):w;}

Try it online!

It's my first submission, and i didn't know if returning string instead of printing it is okay :)

QJot

Posted 2018-09-18T22:25:04.353

Reputation: 41

2Welcome to PPCG! Yes, returning a string is okay. Hope you stick around! – Jo King – 2018-09-20T10:27:55.337

You could use the inequality operator's symmetry to remove a space and thus save a byte -- return w!=""? can be return""!=w?. – Jonathan Frech – 2018-09-21T19:27:11.570

4

Stax, 3 bytes

m|]

Run and debug it

Explanation:

m   Map over the lines
 |] Get all suffixes (suffices?)
    Implicit flatten and output

wastl

Posted 2018-09-18T22:25:04.353

Reputation: 3 089

Regarding suffices: https://en.wiktionary.org/wiki/suffices#Etymology_2

– chambln – 2019-02-05T09:15:13.103

3

Charcoal, 14 bytes

⪫E⪪S ⭆ι✂ιμLι¹ 

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

   S            Input string
  ⪪             Split on spaces
 E              Map over each word
      ι         Current word
     ⭆          Map over each character and join
        ι       Current word
         μ      Current index
           ι    Current word
          L     Length
            ¹   Literal 1
       ✂        Slice
⪫               Join with spaces
                Implicitly print

Neil

Posted 2018-09-18T22:25:04.353

Reputation: 95 035

3

C (gcc), 79 bytes

f(s,t)char*s,*t;{for(;*s;printf("%.*s",*s^32?t?t-s:~0:1,s),s++)t=strchr(s,32);}

Try it online!

gastropner

Posted 2018-09-18T22:25:04.353

Reputation: 3 264

3

Pip -s, 11 bytes

J_@>,#_Mq^s

Takes the space-separated list of words from stdin. Try it online!

Explanation

             s is space (implicit)
        q    Read a line of stdin
         ^s  Split it on spaces
       M     Map this lambda function to each word:
 _            The word...
  @>          sliced starting at index...
    ,#_       range(len(word))
              This creates len(word) slices ["word" "ord" "rd" "d"]
J             Join those into a single string
             The resulting list of modified words is printed; the -s flag uses space
             as the separator

DLosc

Posted 2018-09-18T22:25:04.353

Reputation: 21 213

3

Ruby, 42 bytes

->s{s.map{|a|(w=a.b).chars{a[0]='';w<<a}}}

Try it online!

G B

Posted 2018-09-18T22:25:04.353

Reputation: 11 099

3

Python 2, 63 bytes

lambda s:' '.join(map(g,s.split()))
g=lambda s:s and s+g(s[1:])

Try it online!

TFeld

Posted 2018-09-18T22:25:04.353

Reputation: 19 246

It is 64 bytes on my computer, mac OS. – aydinugur – 2018-09-21T23:30:11.433

3

Canvas, 6 bytes

±[±]⇵]

Try it here!

5 bytes with a crazy output format

dzaima

Posted 2018-09-18T22:25:04.353

Reputation: 19 048

3

C#, 111 90 bytes

b=>string.Join(" ",(b.Split(' ').Select(x=>string.Concat(x.Select((y, i)=>x.Substring(i))))))

Try it Online!

By Changing input and output to arrays, I saved a few bytes:

b=>b.Select(x=>string.Concat(x.Select((y,i)=>x.Substring(i)))).ToArray()

Try it Online!

LiefdeWen

Posted 2018-09-18T22:25:04.353

Reputation: 3 381

3

K (oK), 17 13 bytes

{,/|:'|,\|x}'

Try it online!

Prefix anonymous function; Input is taken as a list of strings, which in turn are lists of characters.

Thanks @streetster for 4 bytes.

How:

{,/|:'|,\|x}' //Main function, argument x → ("ill";"eel")
            ' // For each element of the argument
         |x}  // Flip it. x → ("lli";"lee")
       ,\     // Concatenate each element, keeping intermediates. x → (("l";"ll";"lli");("l";"le";"lee")
      |       // Flip it again. x → (("lli";"ll";"l");("lee";"le";"l"))
   |:'        // Now flip each element. x → (("ill";"ll";"l");("eel";"el";"l"))
{,/           // Concatenation scan. x → ("illlll";"eelell")

J. Sallé

Posted 2018-09-18T22:25:04.353

Reputation: 3 233

You can return a list, also take a look at my oK solution

– streetster – 2018-09-20T16:33:39.957

@streetster oh, nice. I'm still in the process of learning K, so my solutions won't be as short or as elegant as I'd like. Thanks for the heads up! – J. Sallé – 2018-09-20T16:35:29.877

Flatten before reverse allows you to omit the "reverse-each", bringing it down to 10 bytes: {|,/,\|x}' – hoosierEE – 2018-10-19T02:39:42.453

3

Common Lisp, 179 bytes

(defun r(s)(cond((endp s)nil)((eql(first s)#\Space)(princ " ")(r(rest s)))(t(q s)(r(rest s)))))(defun q (l)(cond((eql(first l)#\Space)t)((endp l)t)(t(princ(first l))(q(rest l)))))

Try it online!

This is my first try at golfing any edits are welcome

JRowan

Posted 2018-09-18T22:25:04.353

Reputation: 231

Hello and welcome to PPCG. Removing whitespace can save you 29 bytes.

– Jonathan Frech – 2018-09-21T01:20:18.360

@Johnathan Frech thanks i just updated with no spaces – JRowan – 2018-09-21T01:27:48.187

I think you missed four superfluous spaces. – Jonathan Frech – 2018-09-21T01:28:49.380

You can most likely also use car instead of first and cdr instead of rest to further golf your submission. – Jonathan Frech – 2018-09-21T01:30:30.800

Na, im good with it now haha, maybe ill come back and mess with it later. Im just learning lisp now my teacher said to never use car and cdr so they were out of my head while i was doing it – JRowan – 2018-09-21T01:32:59.850

Well, one has not truly done list processing without using these two primitives. :P – Jonathan Frech – 2018-09-21T01:35:50.813

(1) you can use eql instead of equal, even eq seems to work in TIO. (2) The (r(coerce "hello world" 'list)) is testing, not part of the byte count. (Testing is usually put in the TIO footer section.) – Ørjan Johansen – 2018-09-21T01:41:16.640

Oh, I also think nil is redundant. – Ørjan Johansen – 2018-09-21T01:45:10.203

I just edited, i thought eql would test reference thats why i had equal but eql works – JRowan – 2018-09-21T01:45:35.753

3

Lua, 70 bytes

for i=1,#arg do x=arg[i]for i=1,#x do io.write(x:sub(i))end print()end

Try it online!

Explanation

The arguments in Lua are stored in the table arg starting at index 1. The unary operator # returns the size of the table and function s:sub(a,b) returns a substring based on string s delimited by integers a and b, if b is not passed it will return the rest of the string.

I had to use io.write() instead of print() to avoid line breaking, and added print() at the end for the opposite reason.

Marcio Medeiros

Posted 2018-09-18T22:25:04.353

Reputation: 51

2

Python 3, 79 74 bytes

-5 bytes thanks to mypetlion

print(*map(lambda x:''.join(x[n:]for n in range(len(x))),input().split()))

Try it online!

A full program that takes input from stdin and outputs to stdout.

Jo King

Posted 2018-09-18T22:25:04.353

Reputation: 38 234

1print(*map(lambda x:''.join(x[n:]for n in range(len(x))),input().split())) Full program to save 5 bytes. – mypetlion – 2018-09-18T23:13:46.340

2

Perl 6, 44 32 bytes

-12 bytes thanks to nwellnhof!

~*.words>>.&{[~] $_,{S/.//}...0}

Try it online!

An anonymous Whatever lambda that takes a string and returns a string.

Explanation:

 *.words   # Split the given word by spaces
        >>.&{                  }  # Map each word to
                           ...  # A list composed of
                 $_              # The initial string
                   ,{S/.//}      # Remove the first character
                              0  # Until it's empty
             [~]   # All joined together
~   # Convert the list to a string, which joins by spaces

Jo King

Posted 2018-09-18T22:25:04.353

Reputation: 38 234

29 bytes – nwellnhof – 2018-09-19T10:12:25.240

@nwellnhof I can't believe I forgot about .words! – Jo King – 2018-09-19T10:19:05.010

2

JavaScript (Node.js), 33 bytes

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

Try it online!

I don't really know JavaScript, but I just copied Arnauld's syntax with an idea I had for the regex substitution :P

jaytea

Posted 2018-09-18T22:25:04.353

Reputation: 467

2

MathGolf, 6 bytes

ÆÅ_╞↑ 

Try it online!

Outputs a trailing space, though you can add another byte to remove this.

Hopefully 6 bytes when implicit input is implemented. Yay.

Explanation:

        Implicit input
Æ       Implicit for loop over the next 5 instructions
 Å  ↑   While true without popping (empty string is false)
  _╞    Duplicate the top of stack and remove the first letter
        (space) Append a space to the stack
        Implicitly output the stack joined together

Jo King

Posted 2018-09-18T22:25:04.353

Reputation: 38 234

1I can confirm that ÆÅ_╞↑ works in the latest version of MathGolf, with input ['Hello','world']. It is to be pushed today. I've worked on getting typed input and implicit input working properly, and now I can run the program above with correct output. – maxb – 2018-09-19T09:19:41.963

2

Java (JDK 10), 90 bytes

s->{var r="";for(var x:s){for(int i=0;i<x.length();)r+=x.substring(i++);r+=" ";}return r;}

Try it online!

Credits

  • -11 bytes thanks to Kevin Cruijssen, notifying me of the rule change about the input.

Olivier Grégoire

Posted 2018-09-18T22:25:04.353

Reputation: 10 647

1s.split(" ") can be just s. The rules have been changes, so you can take a String-array as input. (I also tried modifying the input array so you can remove the return-statement, but it seems to be longer.) – Kevin Cruijssen – 2018-09-19T13:28:19.357

2

Powershell, 29 23 bytes

Port of Javascript by @Arnauld

$args-replace'.',"$&$'"

Input and output are a list of word. Test script:

$f = {

$args-replace'.',"$&$'"

}

@(
    ,('illlll eelell', 'ill','eel')
    ,('laserasersererr batatt', 'laser','bat')
    ,('dartharthrththh vaderaderdererr', 'darth','vader')
) | % {
    $e,$s = $_
    $r = &$f @s
    $r = "$r"
    "$($r-eq$e): $r"
}

Output:

True: illlll eelell
True: laserasersererr batatt
True: dartharthrththh vaderaderdererr

mazzy

Posted 2018-09-18T22:25:04.353

Reputation: 4 832

2

Scala, 97 bytes

Scala main that takes a single String argument containing all the words.

args(0).split(" ").foreach(x=>{for(i<-0 to x.length)print(x.substring(i,x.length));print(" ")})

Try it online!

Flo

Posted 2018-09-18T22:25:04.353

Reputation: 21

1That's actually 95 bytes, if you remove the unnecessary newlines. – Shikkou – 2018-09-27T10:15:23.510

2

Python3, 86 bytes

Reduced a lot, thanks to @ElPedro and @manatwork

def f(a):return a+f(a[1:])if''<a else'' 
for x in input().split():print(f(x),end=' ')

P.S. I tried removing split but then nothing is printing, its probably required in python3

Vedant Kandoi

Posted 2018-09-18T22:25:04.353

Reputation: 1 955

The question asks for multiple words. Also, you should include your bytecount in the answer – Jo King – 2018-09-19T10:45:18.450

oh my bad will correct it – Vedant Kandoi – 2018-09-19T10:46:56.747

Welcome to PPCG! You can use tryitonline to format your answer nicely and allow people to test it. See my answer as an example.

– ElPedro – 2018-09-19T10:56:07.530

1

And TIO has a character counter too, which will say your solution currently has “106 chars, 106 bytes (UTF-8)”. BTW, unfortunately your code have a small glitch as for “cat” outputs “catat”, not “catatt”. Just change the condition to len(a)>0. Or to a>'' as it is shorter. Or to ''<a as that way you need no space between the if keyword and the expression. See Tips for golfing in Python.

– manatwork – 2018-09-19T11:12:43.740

You don't need the space in the split(). Python splits on space by default. You can also remove the space in return '' to save another one. – ElPedro – 2018-09-19T11:14:53.423

You also don't need the newline and two spaces before return a+f(a[1:]). It can go on the same line as the if. With these and the hints from @manatwork you should be well below 100 :-) – ElPedro – 2018-09-19T11:20:55.273

Don't remove the whole split - just the space in it. Try this link

– ElPedro – 2018-09-19T11:44:04.130

You can also replace the if and 2 returns with return a+f(a[1:])if''<a else'' which can then go on the same line as def f(a) taking it down to 87 bytes

– ElPedro – 2018-09-19T11:53:05.110

2

Python3, 58 bytes

Takes a space-separated string of words from stdin and returns stdout likewise.

f=lambda x:x and x+f(x[1:])
print(*map(f,input().split()))

It works by splitting the string into a list of words and using map() to call the recursive function f on each element. Honestly, I don't know exactly how f works. When the stack reaches the end of the word, x becomes the empty string (''), so the and statement returns False, which I suspect acts as the base case to end recursion.

Here's the same idea but without the functional aspects:

def f(x):
    return x and x + f(x[1:])

print(*( f(word) for word in input().split() ))

chambln

Posted 2018-09-18T22:25:04.353

Reputation: 81

2

q 78 38 bytes

" "sv{r::x;{x,r::1_r}/[count x;x]}each

Thaufeki

Posted 2018-09-18T22:25:04.353

Reputation: 421

2Welcome to PPCG! You can take input as a list of lines and return a list of lines rather than having to use vs and sv to split on whitespace. – streetster – 2018-09-19T21:11:58.510

Oh right, I thought the multiple words necessitated a string split, I`ll give it another go, thank you – Thaufeki – 2018-09-19T21:14:08.370

Also... take a look at the scan operator rather than recursing.

– streetster – 2018-09-19T21:19:14.330

... was thinking along the lines of { raze {1_x} scan x } each which can be golfed down a little more... – streetster – 2018-09-19T22:39:24.653

Used 'over' instead with some recursion, need to find a way to do it without globals – Thaufeki – 2018-09-19T23:27:27.250

" "sv{raze{1_x}scan x}each, your one, comes out to 26, gonna be hard to beat that – Thaufeki – 2018-09-20T00:07:03.060

raze@'((1_)\)@' for 15 bytes :) – streetster – 2018-09-21T08:30:49.640

@streetster raze@'(1_)\' should work too – ngn – 2018-09-28T01:04:56.200

@ngn raze@'((1_)\') works for 14 bytes, need the brackets else q complains about the naked . Can also do (,/')((1_)\') for 13. – streetster – 2018-09-28T12:58:04.767

2

Attache, 28 bytes

Join&sp##Sum@Suffixes=>Split

Try it online!

Alternatives

ReplaceF&(Sum@Suffixes)&/"\\w+"               ?? 31 bytes
ReplaceF«_,/"\\w+",Sum@Suffixes»              ?? 34 bytes, 32 chars
ReplaceF<~_,/"\\w+",Sum@Suffixes~>            ?? 34 bytes

Explanation

Join&sp##Sum@Suffixes=>Split    input, e.g.: "abc defg"
                       Split    split the input on spaces
                                e.g.: ["abc", "defg"]
                     =>         on each word:
                                  e.g.: "abc"
             Suffixes             take the suffixes of that word
                                  e.g.: ["abc", "bc", "c"]
         Sum@                     join them together
                                  e.g.: "abcbcc"
       ##                       then
Join&                           join the result by:
     sp                           spaces

Conor O'Brien

Posted 2018-09-18T22:25:04.353

Reputation: 36 228

2

Scala, 81 bytes

def e(s:List[String])=s.map(_.foldRight(("","")){(a,b)=>(a+b._1,a+b._1+b._2)}._2)

Try it online!

As per comments, this can receive and output a List[String]. This builds the output from right to left, starting with the rightmost letter, then prepending the two rightmost letters, and so on down the line.

Ethan

Posted 2018-09-18T22:25:04.353

Reputation: 271

2

Pyth, 8 6 bytes

m_s.__

Decreased byte(s?) thanks to @Steven H.

Try it online! Input and output are a list.

Expalanation:

        - implicit output
m       - map function d:
      _ -   ...d reversed...
    ._  -   ...get all prefixes of it...
  _s    -   ...joined and reversed
        - ...over implicit Q (input)

u_ndefined

Posted 2018-09-18T22:25:04.353

Reputation: 1 253

1You can save a byte by using m instead of V, since that would make the Q implicit rather than explicit. – Steven H. – 2018-09-21T11:06:31.240

2

Pascal (FPC), 129 bytes

var s:string;i,j:int32;begin read(s);repeat j:=Pos(' ',s);for i:=1to j do write(s[i..j-1]);write(' ');Delete(s,1,j)until s=''end.

Try it online!

Requires that the input ends in space, allowed in this comment.

AlexRacer

Posted 2018-09-18T22:25:04.353

Reputation: 979

2

Twig, 73 bytes

Creates a macro with the function f() that receives an array of words, displaying the words separated by new lines.

{%macro f(a)%}{%for v in a%}{%for i in 0..v|length%}{{v[i:]}}{%endfor%}
{%endfor%}{%endmacro%}

To use it, just import:

{% import 'macro.twig' as a %}

{{ a.f(['a','sentence','is','a','list','of','words']) }}

{# to pass a string, you can split it #}
{{ a.f('a sentence is a list of words'|split(' ')) }}

You can try it on https://twigfiddle.com/8xech1
Warning: due to the way that output is handled in the link, I was forced to add a simple period (.) at the end of the line. This is NOT needed for normal operation.

Ismael Miguel

Posted 2018-09-18T22:25:04.353

Reputation: 6 797

2

Brachylog, 7 bytes

{a₁ᶠc}ᵐ

Try it online!

Explanation

{    }ᵐ          Map for each word:
 a₁ᶠ               Find all suffixes
    c              Concatenate into a single string

Fatalize

Posted 2018-09-18T22:25:04.353

Reputation: 32 976

2

Haskell, 24 bytes

This solution is not optimal in two ways: 1) the other Haskell answer by nimi is 3 bytes shorter and 2) the input is limited to 9223372036854775807 characters (~36 exabytes), though I think it's an interesting find:

map.mconcat$drop<$>[0..]

Try it online! (sets a limit of 255 characters for TIO would time out otherwise)

Explanation

Since drop has type Int -> [a] -> [a] it forces [0..] to be [0..9223372036854775807] which is finite and thus the program terminates (eventually).

And mconcat takes the list of [drop 0, drop 1..] and gives us a function String -> String which is equivalent to:

\str-> drop 0 str ++ drop 1 str ++ .. ++ drop 9223372036854775807 str

Note: Once the argument of drop is greater or equal to the length of str it just appends empty strings.

Practical solution, 40 bytes

This won't take as long as the shorter solution but at a great cost of 16 bytes:

map$mconcat=<<map drop.zipWith pure[0..]

Try it online!

ბიმო

Posted 2018-09-18T22:25:04.353

Reputation: 15 345

1

C (gcc), 94 bytes

f(char*s){char*e=s+strlen(s),*i=s;for(;i<e;*i++=*i-32?*i:0);for(i=s;i<e;i++)printf(*i?i:" ");}

Try it online!

Saves a pointer to the end of the string in char *e, then replaces spaces with null characters, then prints the string starting with each character and ending at the next null character, but printing a space if the current character is a null character.

pizzapants184

Posted 2018-09-18T22:25:04.353

Reputation: 3 174

1

JavaScript (Node.js), 88 bytes

f=s=>s.split(' ').map(e=>[...e].map((_,i,a)=>a.slice(i,a.length).join``).join``).join` `

Try it online!

user58120

Posted 2018-09-18T22:25:04.353

Reputation:

By using flatMap you would save a join. – tsh – 2018-09-19T06:05:30.353

Welcome to PPCG. – Shaggy – 2018-09-19T06:58:26.413

1

C (gcc), 64 bytes

f(s,t)char*s,*t;{for(;*s;t+=*s<33)for(strcpy(t,s++);*t&31;t++);}

Take two char* parameters: The first one for input, and the second one for output. The caller is responsible for malloc and free. Like most string functions in C, this one is designed to be vulnerable by overflow the buffer.

Try it online!

tsh

Posted 2018-09-18T22:25:04.353

Reputation: 13 072

1

Gema, 24 characters

<L>=@x{$0}
x:?*=?*@x{$2}

Sample run:

bash-4.4$ gema '<L>=@x{$0};x:?*=?*@x{$2}' <<< 'darth vader'
dartharthrththh vaderaderdererr

manatwork

Posted 2018-09-18T22:25:04.353

Reputation: 17 865

I assume it's the same amount of bytes, unless there's multi-byte characters in there? – Jo King – 2018-09-19T08:33:47.173

Definitely the same. Gema doesn't use multi-byte characters. – manatwork – 2018-09-19T08:40:03.813

Okay. It was just strange that you used the term characters in the header – Jo King – 2018-09-19T08:47:20.273

1

Red, 67 66 bytes

func[s][foreach w split s" "[until[prin w take w tail? w]prin" "]]

Try it online!

Galen Ivanov

Posted 2018-09-18T22:25:04.353

Reputation: 13 815

1

Kotlin, 87 bytes

fun f(s:String):String=if(s=="")s else s.split(" ").joinToString(" "){it+f(it.drop(1))}

sp0rk

Posted 2018-09-18T22:25:04.353

Reputation: 111

1

Hello and welcome to PPCG; nice first post. You could add a link to an online implementation (like TIO) for ease of verifying your solution.

– Jonathan Frech – 2018-09-19T13:29:05.023

1

Python 2, 55 bytes

for x in input():
 y=""
 while x:y+=x;x=x[1:]
 print y,

Try it online!

Takes input as a list. output is separated by spaces.

ElPedro

Posted 2018-09-18T22:25:04.353

Reputation: 5 301

1

Java, 131 bytes

char[]e(char[]a){int b=0,l=a.length,c,d=0;char[]n=new char[l*(l+1)/2];for(;b<l;b++){for(c=l-b;c>0;c--){n[d]=a[l-c];d++;}}return n;}

I know there is a better Java answer but, wanted to do it just with char arrays

char[] e(char[]a){
    int b=0,l=a.length,c,d=0;      //l to keep length, b for each iteration, c for each letter in iteration 
    char[] n= new char[l*(l+1)/2]; //Create new array with length based in triangular number sequence
    for(;b<l;b++) {
        for(c=l-b;c>0;c--) {
            n[d]=a[l-c];          //Fill it
            d++;                   //d keeps position in new array
        }
    }
    return n;
}

Java Gonzar

Posted 2018-09-18T22:25:04.353

Reputation: 173

1l+1 can most likely be -~l. – Jonathan Frech – 2018-09-19T16:02:32.830

1

Julia 0.7, 75 65 bytes

p(a)=for i in a for j=1:endof(i) print(i[j:end])end;print(" ")end

Try it online!

First codegolf. Yay v0.7 becase it it just deprecates the endof method and 1.0 replaces it with lastindex.

Update: As mentioned in the comments I am not sure if an array of words as input is permitted. So I included the bytes to take a string as input

Update2: Apparently an array of strings is ok so here we go down to 65 bytes. Thx to @JonathanFrech for removing some more whitespace

Huanzo

Posted 2018-09-18T22:25:04.353

Reputation: 11

I do not think taking a string array is valid. Please reflect splitting in your byte count. – Jonathan Frech – 2018-09-19T18:53:02.570

@JonathanFrech Yeah I'm not sure too. I just added the 7 more bytes to take a String as the argument. – Huanzo – 2018-09-19T20:12:48.413

You can remove some whitespace.

– Jonathan Frech – 2018-09-19T20:16:43.477

@JonathanFrech oh thanks didn't know that you don't need the white spaces after). In the comments of the golf somebody asked if a list of words would be alright. And the author permitted that. One could argue that an array of words could count as a list. So my first answer would be alright. – Huanzo – 2018-09-19T20:26:59.553

@johnathan Actually the OP has commented that taking/returning a list of words is valid – Jo King – 2018-09-19T21:12:26.390

@JoKing nice I will update my answer tomorrow when I'm on my pc again – Huanzo – 2018-09-19T21:18:31.990

1

Kotlin, 48 bytes

Lambda takes a List<String> as input and returns a List<String> as output, which is allowed. The extra code in the footer is just so the input can be tested easily.

{it.map{it.indices.fold(""){a,v->a+it.drop(v)}}}

Try it online!

snail_

Posted 2018-09-18T22:25:04.353

Reputation: 1 982

1

GolfScript, 23 bytes

" "/{{""=!}{(;}/}/]" "*

Try it online!

JosiahRyanW

Posted 2018-09-18T22:25:04.353

Reputation: 2 600

1

Multi User Forth(121 bytes), Protomuck variant.

" " explode_array { swap foreach nip { swap  begin dup 1 strcut nip dup not until }cat repeat }list " " array_join .tell

I guess if you want to require that I use entirely standard stuff, then .tell it becomes me @ swap notify which brings it up to 132 bytes. If you want to go the other direction, then I guess that swap could become .s and nip .n, dup .d etc, would turn it into

" " explode_array { .s foreach .n { .s  begin .d 1 strcut .n .d not until }cat repeat }list " " array_join .tell

Which has 113 bytes.

Luckily we can continue further, begin turns into .b, until .u and explode_array .e, if we use our thinking caps we can turn foreach into .f by defining that into foreach nip (who needs the index of the array anyway?) and we end at 94 bytes.

" " .e { .s .f { .s  begin .d 1 strcut .n .d not until }cat repeat }list " " array_join .tell

But, this is getting silly, and probably only hurting any chance of this being seen as a meaningful first post on codegolf.

jaked122

Posted 2018-09-18T22:25:04.353

Reputation: 111

1

C (clang), -DT=t=strtok -DZ=" ") 178 113 106 105 95 91 bytes

i;f(*a){char*t;for(T(a,Z;t;printf(Z,T(0,Z)for(i=0;t[i];)printf(t+i++);}

Try it online!

Logern

Posted 2018-09-18T22:25:04.353

Reputation: 845

This will potentially fail on input longer than $99$ bytes. This is not a platform limitation, but your choice. I do not know if this is a valid answer. – Jonathan Frech – 2018-09-24T17:59:10.257

@JonathanFrech but a dynamically growing array to store input would be much longer code. The only other solution would be passing the input as an argument to the function. – Logern – 2018-09-24T18:04:48.180

Cool that that is also shorter; as I said -- I do not know if the other is invalid; only that it seemed a bit unelegant. – Jonathan Frech – 2018-09-24T19:03:29.950

Suggest T(i=0,Z)for(; instead of T(0,Z)for(i=0; – ceilingcat – 2018-09-25T04:13:25.307

1

Scala, 81 bytes

def x(l:String):String=if(l=="")" "else l+x(l.tail)
println(args.map(x).mkString)

Try it online!

Shikkou

Posted 2018-09-18T22:25:04.353

Reputation: 161

1

Taking input as a predefined variable is not allowed. That would turn the submission into a snippet. Submissions should either be a full program or a function.

– Jo King – 2018-09-26T06:19:48.873

Hello, @JoKing, thanks. I updated the answer. Does this follow the rules now? – Shikkou – 2018-09-27T10:22:19.453

If you're submitting ot as a full program, I'm afraid you're going to have to include the boilerplate as well – Jo King – 2018-09-27T12:34:17.990

1

Elixir, 122 bytes

a = ["Hello","World"]
f = fn n,f -> if(n != "") do "#{n}#{f.(String.slice(n, 1..-1), f)}" end end
Enum.map(a, &(f.(&1,f)))

# OUTPUT
["Helloellolloloo", "Worldorldrldldd"]

Try it online!

DarckBlezzer

Posted 2018-09-18T22:25:04.353

Reputation: 111

1Hi, welcome to PPCG! The input doesn't have to be in the actual code, so you can declare the list in the input section, and reference it by a single letter variable. – Shikkou – 2018-09-25T07:27:50.510

1

@AlexGrigore Actually, taking input as a predefined variable is not allowed. That would turn the submission into a snippet. Submissions should either be a full program or a function.

– Jo King – 2018-09-26T00:12:51.463

1

The input shouldn't be hard-coded, but passed to the program/function. You can see what IO methods are allowed here.

– Jo King – 2018-09-26T05:57:28.927

1

Kotlin Android, 204 bytes

fun f(s:String){ val a=s.split(" ".toRegex()).dropLastWhile{it.isEmpty()}.toTypedArray();for(i in a.indices){var t=0;while(t<a[i].length){for(j in t until a[i].length){print(a[i][j]+"")};t++};print(" ")}

}

Try online

This Program is written in Kotlin Android.

Syed Hamza Hassan

Posted 2018-09-18T22:25:04.353

Reputation: 129

@Keeta, Thank you for your Update. – Syed Hamza Hassan – 2018-10-05T07:39:36.343

Input should not be taken as a predefined variable otherwise this becomes a snippet. Submissions should be a full program or a function equivilant. – Jo King – 2018-10-19T10:25:40.420

Updated my code. – Syed Hamza Hassan – 2018-10-19T10:29:55.370

Err, the program should take the word as input, not jard code "hello world" – Jo King – 2018-10-19T14:04:30.723

Updated my code. – Syed Hamza Hassan – 2018-10-20T05:22:15.530

1

C#, 193 bytes

using System;class a{static void Main(string[]b){foreach(var c in b)d(c, 0);}static void d(string c,int e){if(e==c.Length-1){Console.Write(" ");return;}Console.Write(c.Substring(e++));d(c, e);}}

Try it Online!

Since .NET automatically splits the arguments at spaces, it's possible to loop over them without splitting them manually.
Other than that, this uses recursion to subtract one character at a time using the overload of string.Substring that takes only 1 argument which is the index to start at.

user71809

Posted 2018-09-18T22:25:04.353

Reputation: 21

1

sed, 42 37+2 bytes

s:\b:_:g
:A
s:_(.(\w*_))|__:\1\2:g
tA

Try it online!

Repeatedly match parts of words between underscores:

_hello_ _world_
hello_ello_ world_orld_
helloello_llo_ worldorld_rld_
helloellollo_lo_ worldorldrld_ld_
helloellollolo_o_ worldorldrldld_d_
helloellolloloo__ worldorldrldldd__
helloellolloloo worldorldrldldd

eush77

Posted 2018-09-18T22:25:04.353

Reputation: 1 280

1

Burlesque, 8 bytes

{iS\[}ww

Try it online!

{
 iS # All suffixes
 \[ # Concatenate
}ww # For each word

DeathIncarnate

Posted 2018-09-18T22:25:04.353

Reputation: 916