30
\$\begingroup\$

This idea is loosely based upon @TùxCräftîñg's chat message.

Take a look at the below example sequence:

INVALID0, INVALID1, INVALID2 INVALID3, INVALID4... INVALID9

After INVALID9, it goes on like this:

INVALI0, INVALI1, INVALI2, INVALI3... INVALI9

And after INVALI9, it's like this:

INVAL0,INVAL1, INVAL2, INVAL3... INVAL9

After, INVAL9, it's like this:

INVA0, INVA1, INVA2, INVA3, ... INVA9

Notice how we we kept removing a letter from the word INVALID each time.

You'll keep repeating this until you reach a single letter, that is, the letter I:

I0, I1, I2, I3, I4 ... I9

Now, your task is, to take an input of a word, and produce a sequence from it like the above example. Your code must also work with single letters, and in that case the resulting sequence will be shorter.

You may choose any input and output format that you prefer (with or without a separator, as you wish), but you must specify which one you have chosen.

The sequence needs to be in the exact specified order.

The shortest code, in bytes, that successfully completes this challenge, wins the challenge.

Full sequence in the above example:

INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9

Other examples:

Input: MAYBE (Uppercase and lowercase don't matter)

Output:

MAYBE0, MAYBE1, MAYBE2, MAYBE3, MAYBE4, MAYBE5, MAYBE6, MAYBE7, MAYBE8, MAYBE9, MAYB0, MAYB1, MAYB2, MAYB3, MAYB4, MAYB5, MAYB6, MAYB7, MAYB8, MAYB9, MAY0, MAY1, MAY2, MAY3, MAY4, MAY5, MAY6, MAY7, MAY8, MAY9, MA0, MA1, MA2, MA3, MA4, MA5, MA6, MA7, MA8, MA9, M0, M1, M2, M3, M4, M5, M6, M7, M8, M9


Input: AFTER

Output:

AFTER0, AFTER1, AFTER2, AFTER3, AFTER4, AFTER5, AFTER6, AFTER7, AFTER8, AFTER9, AFTE0, AFTE1, AFTE2, AFTE3, AFTE4, AFTE5, AFTE6, AFTE7, AFTE8, AFTE9, AFT0, AFT1, AFT2, AFT3, AFT4, AFT5, AFT6, AFT7, AFT8, AFT9, AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9


Input: WHAT ARE YOU DOING

WHAT ARE YOU DOING0, WHAT ARE YOU DOING1, WHAT ARE YOU DOING2, WHAT ARE YOU DOING3, WHAT ARE YOU DOING4, WHAT ARE YOU DOING5, WHAT ARE YOU DOING6, WHAT ARE YOU DOING7, WHAT ARE YOU DOING8, WHAT ARE YOU DOING9, WHAT ARE YOU DOIN0, WHAT ARE YOU DOIN1, WHAT ARE YOU DOIN2, WHAT ARE YOU DOIN3, WHAT ARE YOU DOIN4, WHAT ARE YOU DOIN5, WHAT ARE YOU DOIN6, WHAT ARE YOU DOIN7, WHAT ARE YOU DOIN8, WHAT ARE YOU DOIN9, WHAT ARE YOU DOI0, WHAT ARE YOU DOI1, WHAT ARE YOU DOI2, WHAT ARE YOU DOI3, WHAT ARE YOU DOI4, WHAT ARE YOU DOI5, WHAT ARE YOU DOI6, WHAT ARE YOU DOI7, WHAT ARE YOU DOI8, WHAT ARE YOU DOI9, WHAT ARE YOU DO0, WHAT ARE YOU DO1, WHAT ARE YOU DO2, WHAT ARE YOU DO3, WHAT ARE YOU DO4, WHAT ARE YOU DO5, WHAT ARE YOU DO6, WHAT ARE YOU DO7, WHAT ARE YOU DO8, WHAT ARE YOU DO9, WHAT ARE YOU D0, WHAT ARE YOU D1, WHAT ARE YOU D2, WHAT ARE YOU D3, WHAT ARE YOU D4, WHAT ARE YOU D5, WHAT ARE YOU D6, WHAT ARE YOU D7, WHAT ARE YOU D8, WHAT ARE YOU D9, WHAT ARE YOU 0, WHAT ARE YOU 1, WHAT ARE YOU 2, WHAT ARE YOU 3, WHAT ARE YOU 4, WHAT ARE YOU 5, WHAT ARE YOU 6, WHAT ARE YOU 7, WHAT ARE YOU 8, WHAT ARE YOU 9, WHAT ARE YOU0, WHAT ARE YOU1, WHAT ARE YOU2, WHAT ARE YOU3, WHAT ARE YOU4, WHAT ARE YOU5, WHAT ARE YOU6, WHAT ARE YOU7, WHAT ARE YOU8, WHAT ARE YOU9, WHAT ARE YO0, WHAT ARE YO1, WHAT ARE YO2, WHAT ARE YO3, WHAT ARE YO4, WHAT ARE YO5, WHAT ARE YO6, WHAT ARE YO7, WHAT ARE YO8, WHAT ARE YO9, WHAT ARE Y0, WHAT ARE Y1, WHAT ARE Y2, WHAT ARE Y3, WHAT ARE Y4, WHAT ARE Y5, WHAT ARE Y6, WHAT ARE Y7, WHAT ARE Y8, WHAT ARE Y9, WHAT ARE 0, WHAT ARE 1, WHAT ARE 2, WHAT ARE 3, WHAT ARE 4, WHAT ARE 5, WHAT ARE 6, WHAT ARE 7, WHAT ARE 8, WHAT ARE 9, WHAT ARE0, WHAT ARE1, WHAT ARE2, WHAT ARE3, WHAT ARE4, WHAT ARE5, WHAT ARE6, WHAT ARE7, WHAT ARE8, WHAT ARE9, WHAT AR0, WHAT AR1, WHAT AR2, WHAT AR3, WHAT AR4, WHAT AR5, WHAT AR6, WHAT AR7, WHAT AR8, WHAT AR9, WHAT A0, WHAT A1, WHAT A2, WHAT A3, WHAT A4, WHAT A5, WHAT A6, WHAT A7, WHAT A8, WHAT A9, WHAT 0, WHAT 1, WHAT 2, WHAT 3, WHAT 4, WHAT 5, WHAT 6, WHAT 7, WHAT 8, WHAT 9, WHAT0, WHAT1, WHAT2, WHAT3, WHAT4, WHAT5, WHAT6, WHAT7, WHAT8, WHAT9, WHA0, WHA1, WHA2, WHA3, WHA4, WHA5, WHA6, WHA7, WHA8, WHA9, WH0, WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8, WH9, W0, W1, W2, W3, W4, W5, W6, W7, W8, W9

Leaderboard

var QUESTION_ID=92156,OVERRIDE_USER=58717;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Could you post the full sequence all at once? Possibly with some more samples? Also, what may the input possibly contain? \$\endgroup\$
    – DJMcMayhem
    Commented Sep 3, 2016 at 20:55
  • 1
    \$\begingroup\$ Is a lack of separator (e.g. INVALID0INVALID1INVALID2) a valid output format? \$\endgroup\$
    – DLosc
    Commented Sep 3, 2016 at 21:02
  • \$\begingroup\$ @DLosc Yes, it is. \$\endgroup\$ Commented Sep 3, 2016 at 21:03
  • 3
    \$\begingroup\$ Just so you know, it is generally discouraged to accept an answer so quickly after posting the challenge. Accepting too early can discourage users from posting new answers. That's not to say you can't keep the accepted answer, but I'd encourage you to wait longer next time. \$\endgroup\$
    – DJMcMayhem
    Commented Sep 4, 2016 at 4:21
  • \$\begingroup\$ @DJMcMayhem Okay! \$\endgroup\$ Commented Sep 4, 2016 at 16:47

45 Answers 45

9
\$\begingroup\$

Javascript (ES6), 53 47 bytes

f=(s,n=0)=>s&&s+n+f(n-9?s:s.slice(0,-1),++n%10)

Saved 6 bytes thanks to Peanut & Neil

Output: all words as a single string with no separator.

Example

var f=(s,n=0)=>s&&s+n+f(n-9?s:s.slice(0,-1),++n%10)

document.getElementsByTagName('div')[0].innerHTML = f('INVALID')
<div style="word-wrap:break-word"></div>

\$\endgroup\$
10
  • \$\begingroup\$ Saves you one byte, reducing it to 52 bytes, to not use separators (which is allowed) by not appending a space between items in the pattern. Try it here! \$\endgroup\$ Commented Sep 4, 2016 at 13:26
  • \$\begingroup\$ Can you not use s&& instead of s?...:''? \$\endgroup\$
    – Neil
    Commented Sep 4, 2016 at 13:34
  • \$\begingroup\$ Also, you can reduce it to 49 bytes by removing the +'' part from the last code I posted. Try it here! \$\endgroup\$ Commented Sep 4, 2016 at 13:34
  • \$\begingroup\$ I'm using Firefox, and the text isn't separated by spaces. It's not required for the question, but I thought I'd let you know. \$\endgroup\$ Commented Sep 4, 2016 at 16:55
  • 1
    \$\begingroup\$ @TheBitByte - My bad. There's no separator anymore (as suggested by Peanut) but I forgot to update my answer accordingly. Thanks for noticing! \$\endgroup\$
    – Arnauld
    Commented Sep 4, 2016 at 16:58
8
\$\begingroup\$

05AB1E, 10 8 bytes

.pžmâ€JR

Explanation

.p        # get prefixes of input
  žmâ     # cartesian product with [9..0]
     €J   # join each
       R  # reverse

Try it online!

Saved 2 bytes thanks to Adnan

\$\endgroup\$
2
  • 1
    \$\begingroup\$ .p is equivalent to Œ¹g£ :). \$\endgroup\$
    – Adnan
    Commented Sep 3, 2016 at 21:18
  • 1
    \$\begingroup\$ @Adnan: Seriously, how could I have forgot that again! Thanks! Seems like I should take a break :P \$\endgroup\$
    – Emigna
    Commented Sep 3, 2016 at 21:26
7
\$\begingroup\$

Perl, 29 bytes

Includes +1 for -n

Run with input on STDIN:

perl -nE '/^.+(?{map{say$&.$_}0..9})^/' <<< PERL

Just the code:

/^.+(?{map{say$&.$_}0..9})^/
\$\endgroup\$
5
  • \$\begingroup\$ Very nice code. I don't understand that last ^ though... It looks like it does the same job as (*FAIL), but I don't see why. Could you explain? \$\endgroup\$
    – Dada
    Commented Sep 5, 2016 at 11:45
  • \$\begingroup\$ @Dada Yes, forcing a fail is exactly what it does. Since it matched at least 1 character from the start of the string it can't be at the start anymore so the ^ causes the match to fail which forces the regex before that to backtrack \$\endgroup\$
    – Ton Hospel
    Commented Sep 5, 2016 at 12:10
  • \$\begingroup\$ Ok thanks. I was expecting it to work with any character that isn't in the input, but it seems to only work with ^... I mean with your example, why ,/ doesn't work, but ^/ does? \$\endgroup\$
    – Dada
    Commented Sep 5, 2016 at 12:15
  • \$\begingroup\$ It's an implementation detail of the regex optimizer.. If you put a specific character not in the string it is smart enough to know that the regex can never match and the real regex matching is not even started. ^ is beyond the current understanding of the optimizer. Either of the two behaviours might change in the future.. \$\endgroup\$
    – Ton Hospel
    Commented Sep 5, 2016 at 12:46
  • \$\begingroup\$ Ok I get it, I thought it was something like that but wasn't sure. Thanks a lot \$\endgroup\$
    – Dada
    Commented Sep 5, 2016 at 13:18
6
\$\begingroup\$

Haskell, 47 43 bytes

f""=[]
f x=map((x++).show)[0..9]++f(init x)

Usage example: f "IN" -> ["IN0","IN1","IN2","IN3","IN4","IN5","IN6","IN7","IN8","IN9","I0","I1","I2","I3","I4","I5","I6","I7","I8","I9"].

Simple recursive approach. Append each digit to the word and append a recursive call with last letter removed.

\$\endgroup\$
6
\$\begingroup\$

Pyth, 9 bytes

sM*_._QUT

A program that takes input of a quoted string on STDIN and prints a list of strings.

Try it online

How it works

sM*_._QUT  Program. Input: Q
    ._     List of prefixes of Q
   _       Reverse
       UT  Unary range up to 10, yielding [0, 1, 2, ..., 9]
  *        Cartesian product of the above two
sM         Map concatenate over the above
           Implicitly print
\$\endgroup\$
5
\$\begingroup\$

Jelly, 7 bytes

ḣJṚp⁵Ḷ¤

Try it online!

How it works

ḣJṚp⁵Ḷ¤  Main link. Argument: s (string)

 J       Yield all (1-based) indices of s.
ḣ        Head; for each index k, take the first k characters of s.
  Ṛ      Reverse the result.
      ¤  Combine the two links to the left into a niladic chain.
    ⁵      Yield 10.
     Ḷ     Unlength; yield [0, ..., 9].
   p     Return the Cartesian product of the prefixes and the range.
         (implicit) Print the Cartesian product without separators.
\$\endgroup\$
1
  • 7
    \$\begingroup\$ 7 bytes. I just want to know how someone came up with the idea of making this exact code work with the code golf. \$\endgroup\$ Commented Sep 4, 2016 at 13:21
5
\$\begingroup\$

Pip, 12 11 bytes

Takes the word as a cmdline argument. Outputs with no separators.

Wa&Oa.,tDQa

Try it online!

Explanation:

             Implicit: a = 1st cmdline arg, t = 10
Wa           While a (i.e. while it's not the empty string)
   Oa.,t     Concatenate range(10) to a and output
               (Pip concatenates a string to a range itemwise)
  &          The output operation is &-ed to the loop condition to save on curly braces
        DQa  Dequeue from a, removing the final character on each iteration
\$\endgroup\$
4
\$\begingroup\$

V, 20 bytes

A0òYpó.10/0/e
$hòd

Try it online!

Since this contains unprintable characters, here is the readable format:

A0<esc>òYp<C-a>ó.10/0/e
$hòd

And here is a hexdump:

0000000: 4130 1bf2 5970 01f3 2e31 302f 302f 650a  A0..Yp...10/0/e.
0000010: 2468 f264                                $h.d

Explanation:

A0<esc>                 "Append a '0' to the input
       ò                "Recursively:
        Yp              "  Yank this line and paste it
          <C-a>         "  Increment the first number on this line
               ó        "  Substitute:
                .10     "    Any single character followed by '10'
                   /0   "    Replace it with a '0'
                     /e "    Ignore errors if this is not found
$h                      "  Move to the end of the end of this line than back one.
                        "  This makes it so the loop ends once there is only one
                        "  character on this line.
  ò                     "End the loop
   d                    "Delete a line (since we create one too many)  
\$\endgroup\$
0
4
\$\begingroup\$

Bash + coreutils, 54 bytes:

for i in `seq ${#1} 1`;{ printf "${1:0:i}%s " {0..9};}

Simply loops through a sequence [Length of Input,1] and during each iteration, outputs the input word to the length of current iteration value 9 times with each number in [0,9] appended to each of the 9 copies of the word. Execute it within a file and the word or words in quotes, i.e. bash A.sh "blah blah blah".

\$\endgroup\$
4
\$\begingroup\$

Floroid - 50 47 31 bytes

f=Ba:aM[a+b KbIhd]+f(a[:-1])H[]

Currently uses a similar method as @JonathanAllan uses on his second recursive method.

Could've been this if I would've implemented the cartesian product more carefully in the language: Bc:ca([c]+[c[:-a-1]KaIw(Z(c)-1)],hd).

Testcases

Input: ABC
Output: ['ABC0', 'ABC1', 'ABC2', 'ABC3', 'ABC4', 'ABC5', 'ABC6', 'ABC7', 'ABC8', 'ABC9', 'AB0', 'AB1', 'AB2', 'AB3', 'AB4', 'AB5', 'AB6', 'AB7', 'AB8', 'AB9', 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']

Input: M
Output: ['M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9']
\$\endgroup\$
3
\$\begingroup\$

(lambdabot) Haskell - 49 bytes

f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]

Lambdabot is a IRC bot over at #haskell; it automatically imports a bunch of modules, including Data.List which is where inits live. And because a language is defined by its implementation, I can call this lambdabot haskell and not pay the bytes for the imports.

Regular Haskell:

import Data.List
f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]
\$\endgroup\$
4
  • \$\begingroup\$ Are you sure tails works? \$\endgroup\$
    – Bergi
    Commented Sep 5, 2016 at 12:17
  • \$\begingroup\$ @Bergi, totally forgot about the imports, thanks for pointing that out :) \$\endgroup\$
    – BlackCap
    Commented Sep 5, 2016 at 12:22
  • \$\begingroup\$ I didn't mean the import, I meant that it produces the wrong output: INVALID, NVALID, VALID, ALID, LID, ID, D, \$\endgroup\$
    – Bergi
    Commented Sep 5, 2016 at 12:33
  • \$\begingroup\$ @Bergi, Yikes! You're right. 8 more bytes for me then \$\endgroup\$
    – BlackCap
    Commented Sep 5, 2016 at 12:41
3
\$\begingroup\$

braingasm, 34 33 31 28 bytes

At its current state, braingasm is just glorified brainfuck with a few (like, 3?) extra features. I've been spending most of the development time making it as "enterprisy" as possible, instead of actually adding features...

Anyways, the following code should work with the latest development snapshot. It takes newline-less input from stdin, like $ echo -n INVALID | braingasm invalid.bg, and prints to stdout.

,[>,]#[48+10[#<[.>]<+]0,<0,]

Explanation:

,[>,]                 lay down the input on the tape
#[                    (length of input - 1) times do
  48+                   add '0' at the end of the tape
  10[                   10 times do
     #<[.>]               move to start of tape, then print the tape
     <+                   increase the number at the end of the tape
  ]                     done printing current word with 0 through 9
  0,                    erase the number by writing 0 onto it
  <0,                   likewise, remove one character
]                     done

edit: Appearantly it's OK to skip use empty string as the delimiter

\$\endgroup\$
2
\$\begingroup\$

Python 2, 53 55 bytes

+2 bytes: declaring f is necessary with recursion (as pointed out by @Destructible Watermelon)

f=lambda s:s and[s+`n`for n in range(10)]+f(s[:-1])or[]

Recurses down to the empty string (yielding an empty list), chops off a character at a time, and prepends with a list of ten of the current string with the digits 0-9 appended to each.

Test on ideone

Python 3, 54 56 bytes

f=lambda s:s and[s+n for n in'0123456789']+f(s[:-1])or[]

Test on ideone

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I'm fairly sure that if your lambda includes a call to itself, you need to have the f= part (a bit like how you can't assume variables have values) \$\endgroup\$ Commented Sep 4, 2016 at 4:03
2
\$\begingroup\$

Swift 3, 150 Bytes

Not quite the shortest solution, but not terrible for Swift

func a(s: String){var c=s.characters,r="";while(c.count>0){var k = "";for d in c{k+=String(d)};for i in 0...9{r+="\(k)\(i) "};c.removeLast()};print(r);}

Test this online in the IBM Swift Sandbox

Ungolfed

func a(s s: String){
    var c = s.characters, r = ""
    while(c.count > 0){
        var k = ""
        for d in c{
            k+=String(d)
        }
        for i in 0...9{
            r+="\(k)\(i) "
        }
        c.removeLast()
    }
    print(r)
}
\$\endgroup\$
2
\$\begingroup\$

Ruby, 51

No separator used.

->s{(10*n=s.size).times{|i|print s[0,n-i/10],i%10}}

Add the following after i%10 for separators:

,$/ for newline, ,?| for | (similar for any printable character), ,' ' for space.

In test program

f=->s{(10*n=s.size).times{|i|print s[0,n-i/10],i%10}}

f[gets.chomp]
\$\endgroup\$
2
\$\begingroup\$

PHP, 64 56 bytes

for($i=9;$a=substr($argv[1].a,0,-++$i/10);)echo$a.$i%10;

for(;$a=substr($argv[1].a,$i=0,-++$l);)for(;$i<10;)echo $a.$i++;

\$\endgroup\$
1
  • \$\begingroup\$ Nice way of preventing another for-loop. You can save a byte by removing the space after echo \$\endgroup\$
    – aross
    Commented Sep 5, 2016 at 14:17
2
\$\begingroup\$

Haskell, 49 46 bytes

f=(>>=(<$>['0'..'9']).snoc).reverse.tail.inits
\$\endgroup\$
3
  • \$\begingroup\$ You can save a byte by infixing the map f=(>>=(map['0'..'9']).snoc).tail.reverse.inits. 3 by using fmap: f=(>>=(<$>['0'..'9']).snoc).tail.reverse.inits \$\endgroup\$
    – BlackCap
    Commented Sep 5, 2016 at 14:25
  • \$\begingroup\$ Oh, and if you do reverse.tail.inits instead of tail.reverse.inits you also get the correct output ;) \$\endgroup\$
    – BlackCap
    Commented Sep 5, 2016 at 14:28
  • \$\begingroup\$ @BlackCap: Thanks, I really wondered why there is no flipped (f)map in the standard library, but didn't think of sections. Regarding tail, I guess I meant init, but swapping it with reverse works fine either :-) \$\endgroup\$
    – Bergi
    Commented Sep 5, 2016 at 14:49
2
\$\begingroup\$

C#, 107 102 Bytes

string f(string i){var o="";while(i!=""){for(int k=0;k<=9;)o+=i+k++;i=i.Remove(i.Length-1);}return o;}

Ungolfed

string f(string i)
{
   string o = "";
   while(i != "")
   {
      for (int k = 0; k <= 9;)
         o += i + k++;
      i = i.Remove(i.Length - 1);
   }
   return o;
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can golf it a bit by removing k++ in the for-loop and add ++ after the usage of k, so like this: string f(string i){var o="";while(i!=""){for(int k=0;k<=9;)o+=i+k+++",";i=i.Remove(i.Length-1);}return o;} Also, the comma's aren't required by OP's challenge, although if you prefer you can of course keep them. Without it's this: string f(string i){var o="";while(i!=""){for(int k=0;k<=9;)o+=i+k++;i=i.Remove(i.Length-1);}return o;} \$\endgroup\$ Commented Sep 5, 2016 at 10:11
2
\$\begingroup\$

Ruby, 90 85 bytes

f=->s{if s=="";return[];end;(0..9).map{|i|s+i.to_s}+f[s.chars.take(s.length-1).join]}

If the string is empty, return a empty array. Otherwise, generate the string + the number in each number from 0 to 9, and call f with the string without the last character.

Saved 5 bytes thanks to @LevelRiverSt

\$\endgroup\$
5
  • \$\begingroup\$ I take it you haven't golfed in Ruby before. Check my answer to this question (or many other Ruby answers on this site) to see the golfy way to define a function without including those wasteful def and end. You can make a lambda so you don't even have do give it a name, so long as you assign to a variable and call it with the arguments in square brackets. \$\endgroup\$ Commented Sep 5, 2016 at 0:18
  • \$\begingroup\$ @LevelRiverSt Using a lambda is 1 byte longer \$\endgroup\$ Commented Sep 5, 2016 at 7:48
  • \$\begingroup\$ Ok, I missed the fact that you do need to name it because it's recursive. But still f=->s{if s=="";return[];end;(0..9).map{|i|s+i.to_s}+f[s.chars.take(s.length-1).join]} is 5 bytes shorter. \$\endgroup\$ Commented Sep 5, 2016 at 17:59
  • \$\begingroup\$ @LevelRiverSt Oh, I didn't know about the -> syntax \$\endgroup\$ Commented Sep 5, 2016 at 17:59
  • \$\begingroup\$ f=->s{s==""&&(return[]);(0..9).map{|i|s+i.to_s}+f[s.chars.take(s.length-1).join]} saves another 4 bytes. Ruby evaluates boolean expressions from left to right and does not evaluate later terms unless necessary to determine the result. The same golfing technique can be used in C. I don't know why the () around return[] are required in this case. \$\endgroup\$ Commented Sep 5, 2016 at 18:11
2
\$\begingroup\$

Perl 6, 32 = 31 bytes + 1 for -p

I'm not all that proficient with Perl 6, so there may be ways to reduce it even more.

$_= ~((~$_,*.chop...^!*)X~ ^10)

It uses -p to evaluate once for each input line. The line is placed into $_ and after the program runs, it prints $_.

The (~$_,*.chop...^!*) is a list where the first element is stringified (~) input, each subsequent element is obtained by chopping the last character off the previous one (*.chop) and that continues until the string is empty (!*), excluding the empty string case (the ^ in ...^).

X~ generates all pairs of the lists on the left and right, using the specified operation, in this case, the string concatenation (~) on them. ^10 is a list of 0, 1, ... 9.

Finally, the list is stringified again with ~, giving the required words with space as a separator.

\$\endgroup\$
2
\$\begingroup\$

PowerShell v2+, 60 bytes

param($n)$n.length..1|%{$i=$_-1;0..9|%{-join$n[0..$i]+"$_"}}

Loops from the length of the input string down to 1. Each iteration, set helper $i equal to the current number minus 1. This is necessary because .length is the total number of characters, but indexing a string is 0-based. Then, we loop from 0 to 9. Each inner loop, slice the input string $n based on the value of our outer loop, -join it back into a string, and string-concatenate on the inner loop count. Each individual loop result is placed on the pipeline, and output is implicit at program completion.

PS C:\Tools\Scripts\golfing> .\invalid-invali-inval.ps1 'foo'
foo0
foo1
foo2
foo3
foo4
foo5
foo6
foo7
foo8
foo9
fo0
fo1
fo2
fo3
fo4
fo5
fo6
fo7
fo8
fo9
f0
f1
f2
f3
f4
f5
f6
f7
f8
f9
\$\endgroup\$
2
\$\begingroup\$

Dyalog APL, 14 11 bytes

Returns list of strings.

,⎕D∘.,⍨⌽,\⍞

, listify (make table into list)

⎕D all digits

∘.,⍨ appended to all of (i.e. making all combinations with)

the reversed list of

,\ the cumulative concatenation of

the text input

TryAPL online!

\$\endgroup\$
1
  • \$\begingroup\$ Fixed. I use a boilerplate and forgot to fill it in. \$\endgroup\$
    – Adám
    Commented Sep 8, 2016 at 5:33
2
\$\begingroup\$

Groovy (58 Bytes)

No idea why I'm even bothering to post a Groovy answer... The minimum required size for a Groovy golf is 2 based on needing a closure, so the best answer here is double my minimum size.

   {s->(s.length()-1..0).each{c->10.times{print s[0..c]+it}}}

Try it here: https://groovyconsole.appspot.com/script/5148433803378688

\$\endgroup\$
2
\$\begingroup\$

Batch, 85 83 bytes

@for /l %%i in (0,1,9)do @echo %1%%i
@set s=%1
@if not "%s:~,-1%"=="" %0 %s:~,-1%
\$\endgroup\$
2
\$\begingroup\$

Java 7, 105 98 bytes

void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

-7 bytes thanks to @Poke.

Ungolfed:

void c(String s){
  for(int x = 0, l = s.length(); x < l*10; ){
    System.out.print(s.substring(0, l - x/10) + x++ % 10);
  }
}

Test code:

Try it here.

class M{
  static void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

  public static void main(String[] a){
    c("INVALID");
    System.out.println();
    c("MAYBE");
    System.out.println();
    c("AFTER");
    System.out.println();
    c("WHAT ARE YOU DOING");
  }
}

Output:

INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALI0INVALI1INVALI2INVALI3INVALI4INVALI5INVALI6INVALI7INVALI8INVALI9INVAL0INVAL1INVAL2INVAL3INVAL4INVAL5INVAL6INVAL7INVAL8INVAL9INVA0INVA1INVA2INVA3INVA4INVA5INVA6INVA7INVA8INVA9INV0INV1INV2INV3INV4INV5INV6INV7INV8INV9IN0IN1IN2IN3IN4IN5IN6IN7IN8IN9I0I1I2I3I4I5I6I7I8I9
MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYB0MAYB1MAYB2MAYB3MAYB4MAYB5MAYB6MAYB7MAYB8MAYB9MAY0MAY1MAY2MAY3MAY4MAY5MAY6MAY7MAY8MAY9MA0MA1MA2MA3MA4MA5MA6MA7MA8MA9M0M1M2M3M4M5M6M7M8M9
AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTE0AFTE1AFTE2AFTE3AFTE4AFTE5AFTE6AFTE7AFTE8AFTE9AFT0AFT1AFT2AFT3AFT4AFT5AFT6AFT7AFT8AFT9AF0AF1AF2AF3AF4AF5AF6AF7AF8AF9A0A1A2A3A4A5A6A7A8A9
WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOIN0WHAT ARE YOU DOIN1WHAT ARE YOU DOIN2WHAT ARE YOU DOIN3WHAT ARE YOU DOIN4WHAT ARE YOU DOIN5WHAT ARE YOU DOIN6WHAT ARE YOU DOIN7WHAT ARE YOU DOIN8WHAT ARE YOU DOIN9WHAT ARE YOU DOI0WHAT ARE YOU DOI1WHAT ARE YOU DOI2WHAT ARE YOU DOI3WHAT ARE YOU DOI4WHAT ARE YOU DOI5WHAT ARE YOU DOI6WHAT ARE YOU DOI7WHAT ARE YOU DOI8WHAT ARE YOU DOI9WHAT ARE YOU DO0WHAT ARE YOU DO1WHAT ARE YOU DO2WHAT ARE YOU DO3WHAT ARE YOU DO4WHAT ARE YOU DO5WHAT ARE YOU DO6WHAT ARE YOU DO7WHAT ARE YOU DO8WHAT ARE YOU DO9WHAT ARE YOU D0WHAT ARE YOU D1WHAT ARE YOU D2WHAT ARE YOU D3WHAT ARE YOU D4WHAT ARE YOU D5WHAT ARE YOU D6WHAT ARE YOU D7WHAT ARE YOU D8WHAT ARE YOU D9WHAT ARE YOU 0WHAT ARE YOU 1WHAT ARE YOU 2WHAT ARE YOU 3WHAT ARE YOU 4WHAT ARE YOU 5WHAT ARE YOU 6WHAT ARE YOU 7WHAT ARE YOU 8WHAT ARE YOU 9WHAT ARE YOU0WHAT ARE YOU1WHAT ARE YOU2WHAT ARE YOU3WHAT ARE YOU4WHAT ARE YOU5WHAT ARE YOU6WHAT ARE YOU7WHAT ARE YOU8WHAT ARE YOU9WHAT ARE YO0WHAT ARE YO1WHAT ARE YO2WHAT ARE YO3WHAT ARE YO4WHAT ARE YO5WHAT ARE YO6WHAT ARE YO7WHAT ARE YO8WHAT ARE YO9WHAT ARE Y0WHAT ARE Y1WHAT ARE Y2WHAT ARE Y3WHAT ARE Y4WHAT ARE Y5WHAT ARE Y6WHAT ARE Y7WHAT ARE Y8WHAT ARE Y9WHAT ARE 0WHAT ARE 1WHAT ARE 2WHAT ARE 3WHAT ARE 4WHAT ARE 5WHAT ARE 6WHAT ARE 7WHAT ARE 8WHAT ARE 9WHAT ARE0WHAT ARE1WHAT ARE2WHAT ARE3WHAT ARE4WHAT ARE5WHAT ARE6WHAT ARE7WHAT ARE8WHAT ARE9WHAT AR0WHAT AR1WHAT AR2WHAT AR3WHAT AR4WHAT AR5WHAT AR6WHAT AR7WHAT AR8WHAT AR9WHAT A0WHAT A1WHAT A2WHAT A3WHAT A4WHAT A5WHAT A6WHAT A7WHAT A8WHAT A9WHAT 0WHAT 1WHAT 2WHAT 3WHAT 4WHAT 5WHAT 6WHAT 7WHAT 8WHAT 9WHAT0WHAT1WHAT2WHAT3WHAT4WHAT5WHAT6WHAT7WHAT8WHAT9WHA0WHA1WHA2WHA3WHA4WHA5WHA6WHA7WHA8WHA9WH0WH1WH2WH3WH4WH5WH6WH7WH8WH9W0W1W2W3W4W5W6W7W8W9
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can save 7 bytes by combining the for loops and doing some extra logic to implicitly determine the suffix and the substring. void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);} \$\endgroup\$
    – Poke
    Commented Jan 21, 2017 at 13:57
1
\$\begingroup\$

Python 3, 62 bytes

lambda x:[(x+" ")[:~i//10]+str(i%10)for i in range(len(x)*10)]

Doesn't use recursion like the other answer.

The reason the " " in x+" " is there: -0 is still zero, and so we can't use minus notation to get all of the string in this way so the highest we can go is minus one, so the " " is to pad the string,

\$\endgroup\$
1
\$\begingroup\$

C, 72, 70 bytes

j;F(char*s,int l){while(l--)for(j=0;j<10;)printf("%.*s%d",l+1,s,j++);}

Takes strings as pointer/size pairs. Test main:

int main() {
  F("INVALID", 7); putchar('\n');
  F("MAYBE", 5); putchar('\n');
  F("AFTER", 5); putchar('\n');
  F("WHAT ARE YOU DOING", 18); putchar('\n');
}
\$\endgroup\$
1
\$\begingroup\$

Retina, 37 bytes

Byte count assumes ISO 8859-1 encoding.

M&!r`.+
m`$
0
%{`$
¶$%`
T`w`d`.$
G10`

Try it online!

Explanation

M&!r`.+

Get all prefixes of the input by matching and printing all overlapping matches from the right.

m`$
0

Append a 0 to each line.

%{`$
¶$%`

The { indicates that the remaining three stages are executed in a loop until they fail to change the string. The % says that they should be applied to each line separately.

The stage itself simply duplicates the last line (initially this is just the line this is run on, but each iteration of the three stages adds another line).

T`w`d`.$

Increment the digit in the last row by performing the following character substitution:

from: _0123456789AB...
to:   0123456789

And finally:

G10`

Keep only the first 10 lines, so that we remove the line we just added after INPUT9.

\$\endgroup\$
1
\$\begingroup\$

Scala, 73 70 bytes

def g(s:String):String=if(s=="")""else(0 to 9 flatMap(s+_))++g(s.init)

Call it like f("INVALID"). Returns a Sequence of Chars.

Explanation

def g(s:String):String= //defines a method g taking a String as a parameter
                        //and returning a String
if(s=="")""             //guard to prevent infinite recursion
else
    (0 to 9             //create a Range from 0 to 9 (inclusive)
    flatMap(            //map:
        s+_                 //append each number to the string
    ))                  //and flatten
    ++ g(s.init)        //concatenate with g applied to everything but the last element of s

Alternative solution, 73 bytes

(s:String)=>s.scanLeft("")(_+_).tail.reverse.flatMap(x=>(0 to 9)map(x+_))

defines an anonymous function. To call it, write

val f = ...

and call it like this

f("INVALID")

It returns a sequence of strings, which will look like this when printed:

Vector(INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9)

Explanation

s.scanLeft("")(_+_)    //accumulate letters from left to right -> Vector("", "I", "IN", "INV", "INVA", "INVAL", "INVALI", "INVALID")
.tail                  //drop the first element
.reverse               //reverse it
.flatMap(x =>          //map each element called x
    (0 to 9)           //create a Range from 0 to 9 (inclusive)
    map(x+_)           //append each number to x
)                      //and flatten
\$\endgroup\$
2
  • \$\begingroup\$ Your recursive solution is 3 bytes less than the iterative one \$\endgroup\$ Commented Sep 4, 2016 at 15:35
  • \$\begingroup\$ You're right, I must've optimised it after counting. \$\endgroup\$
    – corvus_192
    Commented Sep 4, 2016 at 15:37
1
\$\begingroup\$

CJam, 29 28 bytes

ls_,,:)W%]~{_[X<aA*A,]zo}fX;

Explanation:

ls                              read input as string
  _                             duplicate input
   ,,                           create range of length input
      :)W%]                     add 1 to all elements and reverse
           ~                    dump array on stack
            {            }fX    for loop
             _                  duplicate input string
              [X<aA*            slice input string and multiply by 10
                    A,]         range(10)
                       zo       zip array and print (no separator)
                            ;   clear stack
            

Try it online

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.