Output integers in negative order, increase the maximum integer everytime

45

2

Main task

Your task is to print out integers in descending order, starting from 1, and increasing as you keep hitting 1 again, up until the given input is reached, then, print out the rest until you hit 1 again. Example with input 6:

1
21
321
4321
54321
654321
Without newlines (valid output):
121321432154321654321
Side note: this is A004736 in the OEIS. Also, the first example (with newlines) is an invalid output, as specified in the rules.

Input

Your code may take any kind of input (graphical, STDIN) in the form of an integer or number.

Output

Your code should output the above described sequence, up until the input number is reached, then finish to output until it reaches 1 again. The output may be anything, therefore numbers, strings, integers, or graphical output. It is required to print out a single number (no newlines if it's a string). Your output can be in- and outroduced with as many characters as you need (e.g. []).

Since there was some misunderstanding, here's a regex pattern you can try your outputs on.

^(\D*(\d)+\D*)$

Rules

  • The output must be a full number, not split up by anything, not even newlines.
  • The algorithm shouldn't check for the first instance of N appearing in any way (e.g. the 21 in 121321), but rather for the first instance of N as the actual number.
  • A single trailing newline is allowed.
  • The handling for negative input is fully your choice, negative numbers aren't cases you should test.

Test cases

Input: 6
Output: 121321432154321654321

Input: 1 Output: 1

Input: 26 Output: 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321222120191817161514131211109876543212322212019181716151413121110987654321242322212019181716151413121110987654321252423222120191817161514131211109876543212625242322212019181716151413121110987654321

Input: 0 Output: 0, Empty, or Error

Input: 21 Output: 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321

Thanks @Emigna, I used his algorithm to calculate these test cases.

Winner

The winner has been chosen! It was ErikGolfer's answer with an impressive 5 bytes! Congratulations!

devRicher

Posted 2016-12-19T13:05:02.903

Reputation: 1 609

The output must be a full number ... Do you mean the entire sequence, or only the different substrings (1, 2-1, 3-1 ...)? Your first example doesn't seem to match this statement. – steenbergh – 2016-12-19T14:46:23.010

1If the output has to be a single number, how can it be "arrays"? – smls – 2016-12-19T15:50:15.173

Would this array be acceptable as output? [1, 21, 321, 4321, 54321, 654321]

How about this one? [1,2,1,3,2,1,4,3,2,1,5,4,3,2,1,6,5,4,3,2,1]

Or are you just talking about arrays with a single element, like [121321432154321654321] ? – smls – 2016-12-19T16:00:00.597

Can we assume that input is always positive? – Titus – 2016-12-19T16:06:33.727

Ah, so it's okay to write a lambda that outputs an array, only if the array's default stringification as used by the language's standard IO routines would turn it into that single number without anything to separate the digits? – smls – 2016-12-19T16:06:47.880

1I'm confused about the output format. Can you give examples of what is acceptable? Array of numbers? String with numbers separated by spaces? – Luis Mendo – 2016-12-19T16:19:29.750

I'm going to delete my comments to clean this up. All of your questions should've been answered in the question after editing. – devRicher – 2016-12-19T17:43:24.120

1Your regex allow output of mickey321211mouse. Really the \D parts have no reason to be there – edc65 – 2016-12-20T13:45:06.273

@edc65 It actually allows for an empty output too. The regex is ^(\D*(\d)*\D*|)$, and if you note the last pipe|, you will realize that empty output would have been allowed too. – Erik the Outgolfer – 2016-12-24T08:43:15.063

Still allowing mickey123mouse after the edit. But now at least a digit is required – edc65 – 2016-12-24T10:56:43.530

@edc65 It is on purpose, so outputs like [123] or 123\n are accepted. – devRicher – 2016-12-24T11:46:48.093

Does this answer your question? Create an array with repeated numbers

– None – 2020-02-01T03:59:40.430

Answers

13

Jelly, 5 bytes

RRUVV

Try it online!

Formula not mine.

I suspect there is too much going on here...

[ANSWER ACCEPTED] I'd have given some 5 rep to Dennis, but this is not Reputation Exchange. Dennis showed me the VV behavior. To my surprise, this is shorter than 05AB1E.

Erik the Outgolfer

Posted 2016-12-19T13:05:02.903

Reputation: 38 134

Congratulations, this code has the least amount of code! – devRicher – 2016-12-23T11:16:59.157

19

05AB1E, 6 bytes

L€LíJJ

Try it online!

Explanation

Example input 4

L       # range [1 ... input]
        # STACK: [1,2,3,4]
 €L     # map: range
        # STACK: [[1],[1,2],[1,2,3],[1,2,3,4]]
   í    # reverse each
        # STACK: [[1],[2,1],[3,2,1],[4,3,2,1]]
    J   # join inner lists
        # STACK: ['1','21','321','4321']
     J  # join list
        # OUTPUT: 1213214321

Emigna

Posted 2016-12-19T13:05:02.903

Reputation: 50 798

13

JavaScript (ES6), 37 bytes

f=(n,k=1)=>k>n?n--?f(n):'':f(n,k+1)+k

Demo

f=(n,k=1)=>k>n?n--?f(n):'':f(n,k+1)+k

console.log(f(6))

Alternate method for n < 10, 34 bytes (non-competing)

f=(n,s='1')=>--n?s+f(n,++s[0]+s):s

In JavaScript, strings are immutable. Therefore, it's impossible to alter the content of the Nth character of a string s by assigning a new value to s[N].

However, the expression ++s[N] is valid and does evaluate as one would expect, even if the string remains unchanged. For instance:

++"1"[0] // equals 2

And by extension:

s = "21"
++s[0] + s // equals "321"

Arnauld

Posted 2016-12-19T13:05:02.903

Reputation: 111 334

Does not seem to work for n > 9 – edc65 – 2016-12-20T13:49:15.900

@edc65 You're right, of course. I don't know why I thought it was OK to stop at 9. – Arnauld – 2016-12-20T14:06:06.367

12

V, 29 28 27 23 19 17 16 bytes

8 bytes saved thanks to @DJMcMayhem

3 bytes saved thanks to @nmjcman101

"apÀ­ñÄòy$jpkgJ

Hidden characters:

"apÀ<C-x>ñÄ<C-x>òy$jpkgJ

C-x is Ctrl+x.

Try it online! takes input via command-line arguments

Hexdump:

0000000: 2261 70c0 adf1 c418 f279 246a 706b 674a  "ap......y$jpkgJ

Explanation

"ap            Paste the argument
À<C-x>         Argument minus 1 times (so that we exclude the 0)
ñ ... ò        Loop (for some weird reason the ò closes the ñ)
Ä<C-x>         paste current line above and decrement it

Now it looks like:

1
2
...
n

continued...

ò             recursively do (until a breaking error)
y$             yank this line
  jp           paste it down
    kgJ        go up and join
              implicit ò end

GIF (outdated)

(for arg 6)

gif

user41805

Posted 2016-12-19T13:05:02.903

Reputation: 16 320

I got a few by changing your loop to a) end implicitly and b) join the lines as it goes (rather than at the end) òy$jpkgJ – nmjcman101 – 2016-12-19T16:28:20.340

@nmjcman101 Thanks for helping me save 2 bytes! – user41805 – 2016-12-19T16:43:18.863

This is pretty well golfed. I've been racking my brains for a good 20 minutes, and I can't think of anything shorter. :) – James – 2016-12-19T19:45:42.817

@DJMcMayhem It's because I've had some great help :) – user41805 – 2016-12-19T19:47:33.543

I did it! You can get down to 16 bytes. If you paste the arg, and then duplicate/decrement upwards, you get to remove the H. Then if you use the decrement operator on your À, you won't have the 0 at the top so you can remove the x. Then APPARENTLY a ò will close a ­ñ so you can remove the second ­ñ (which is the byte you save). Link because that made no sense

– nmjcman101 – 2016-12-19T20:17:11.157

@nmjcman101 I never knew the argument would be stored in the "a register. Thanks again! – user41805 – 2016-12-20T09:18:57.000

11

C#, 72 69 65 bytes

n=>{for(int i=0,j;i<n;)for(j=++i;j>0;)System.Console.Write(j--);}

If the output can just be returned as opposed to being Written to the console

C#, 71 68 64 bytes

n=>{var s="";for(int i=0,j;i<n;)for(j=++i;j>0;)s+=j--;return s;}

Thanks to @VisualMelon for saving a lot of bytes

Test it here (Humourously the online compiler breaks at any number above 420)

Alfie Goodacre

Posted 2016-12-19T13:05:02.903

Reputation: 321

That was really fast. – devRicher – 2016-12-19T13:09:40.437

@devRicher What can I say, I was waiting for something to be posted :P – Alfie Goodacre – 2016-12-19T13:10:03.150

2There is never a reason to use a while loop in C# code golf, a for-loop will always perform as well if not better. In this case, you can include the assignment of j=1 in the for-loop, and save a semi-colon. You can also declare j along with i, to save the int. The i++ can also be moved to the j=i assignment, saving a byte. You should also be able to replace the i<=n with i<n if you make it j=++i instead and start i at 0. – VisualMelon – 2016-12-19T15:02:24.527

@VisualMelon edited it, saved 3 bytes! Declaring the ints together actually made no difference to the byte count but it makes the loops look a bit nicer – Alfie Goodacre – 2016-12-19T15:10:03.460

@AlfieGoodacre if you declare them together in the for loop, then you'll save 2 more bytes for(int i=0,j;i<n;) ;) There is also no need for the {} around the inner for loop. – VisualMelon – 2016-12-19T15:15:10.783

@VisualMelon right you are. There is no {} on the inner loop as it stands anway – Alfie Goodacre – 2016-12-19T15:17:16.580

@AlfieGoodacre around the for loop (i.e. the block for the outer for-loop; you don't need it because it only contains one statementy thing) – VisualMelon – 2016-12-19T15:18:52.427

@VisualMelon thanks, I didn't actually know that - I thought the for and its statement would count as two and therefore need braces – Alfie Goodacre – 2016-12-19T15:26:11.747

8

Perl, 21 bytes

Uses -E at no extra cost.

say map$}=$_.$},1..<>

Usage

perl -E 'say map$}=$_.$},1..<>' <<< 6
121321432154321654321

Dom Hastings

Posted 2016-12-19T13:05:02.903

Reputation: 16 415

8

Pure bash, 34

eval eval printf %s \\{{1..$1}..1}

Two levels of brace expansion. With input 6, the first level expands to {1..1} {2..1} {3..1} {4..1} {5..1} {6..1}. This then expands to 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 6 5 4 3 2 1, which is smushed together to one string with printf %s. eval's are required at both levels of expansion - for the first level so that the $1 parameter is expanded first, and for the second level so that it expands after the first level.

Try it online

Digital Trauma

Posted 2016-12-19T13:05:02.903

Reputation: 64 644

7

Pyth, 7 bytes

jks}R1S

A program that takes input of an integer and prints the result.

Try it Online!

How it works

jks}R1S   Program. Input: Q
jks}R1SQ  Implicit input fill
    R     Map
      SQ  over [1, 2, 3, 4, ..., Q] with i:
   } 1     Yield [i, i-1, i-2, i-3, ..., 1]
  s       Merge
jk        Join
          Implicitly print

TheBikingViking

Posted 2016-12-19T13:05:02.903

Reputation: 3 674

Personally I'm very disappointed that jk_hC.:S is longer, but nice work! – FryAmTheEggman – 2016-12-19T19:10:54.683

7

GeoGebra, 67 bytes

1
InputBox[a]
Sum[Join[Sequence[Sequence[Text[j],j,i,1,-1],i,1,a]]]

Each line is entered separately into the input bar. Input is taken from an input box.

Here is a gif of the execution:

Program execution

How it works

Entering 1 implicitly assigns a to 1, and the InputBox command associates an input box with a. Then, for each i in {1, 2, 3, ..., a}, the list {i, i-1, i-2, ..., 1} is created using the Sequence command, and each j in that list is converted to a string using Text. Finally, Join merges all the lists, and Sum concatenates all the elements to one text object, which is displayed.

TheBikingViking

Posted 2016-12-19T13:05:02.903

Reputation: 3 674

@devRicher That seems reasonable. Thanks! – TheBikingViking – 2016-12-19T18:42:16.550

7

Retina, 26 22 bytes

Byte count assumes ISO 8859-1 encoding.

.+
$*

$`¶
1
$.%'
0?¶

Try it online!

Explanation

.+
$*

Convert input to unary.


$`¶

At each position, insert the prefix up to that point, as well as a linefeed. This creates a unary range from 2 to n+1, one value per line.

1
$.%'

Replace each 1 with the number of characters after it on the same line. This turns something like 11111 into 43210.

0?¶

Remove all linefeeds and the zeros preceding them.

Martin Ender

Posted 2016-12-19T13:05:02.903

Reputation: 184 808

7

Python 2, 51 bytes

r=s=''
n=0
exec'n+=1;s=`n`+s;r+=s;'*input()
print r

Mitch Schwartz

Posted 2016-12-19T13:05:02.903

Reputation: 4 899

5

GameMaker Language, 65 bytes

b=""for(i=1;i<=argument0;i++){c=i while(j)b+=string(c--)}return b

Timtech

Posted 2016-12-19T13:05:02.903

Reputation: 12 038

5

Actually 8 bytes

RR♂RΣRεj

First time posting an answer in Actually so it probably can be golfed.

How it works

Program takes implicit input, implicit print at EOF
R           Takes the input and creates a range (1, input)   
                STACK = [1,2,..,n]
 R          Reverse the top stack item (our range)
                STACK = [n,..,2,1]
  ♂R        For each item in our range, create a range (1, rangeitem)
                STACK = [[1,2,..,n], .., [1,2], [1]]
    Σ       Stitch the items of the list together
                STACK = [n,..,1,2,3,1,2,1]
     R      Reverse the top stack item again (our answer)
                STACK = [1,2,1,3,2,1,..n]
      εj    Create an empty string and append each item from the list to it.
            (turns non string items into strings)

Try it online!

Teal pelican

Posted 2016-12-19T13:05:02.903

Reputation: 1 338

1

I'm not sure that there is a shorter solution, but I've proven myself wrong before. In any case, here's a Try It Online link for your answer.

– Sherlock9 – 2016-12-19T16:31:09.567

1The code R♂R♂RΣεj is the same number of bytes, but it may be easier to write an explanation for. – Sherlock9 – 2016-12-19T16:35:58.470

@Sherlock9 your way is a little more elegant, I've added the link and an explanation which I forgot to add on yesterday to try explain it a bit more. – Teal pelican – 2016-12-20T09:28:22.790

5

APL, 10 bytes

∊⍕¨∘⌽∘⍳¨∘⍳

E.g.:

      (∊⍕¨∘⌽∘⍳¨∘⍳)6
121321432154321654321

Explanation:

  • : get the numbers from 1 to N.
  • ⍳¨∘: for each of those, get the numbers from 1 to N.
  • ⌽∘: reverse that list
  • ⍕¨∘: get the character representation of each item (so it does not output the numbers with spaces in between)
  • : flatten the resulting array

marinus

Posted 2016-12-19T13:05:02.903

Reputation: 30 224

So it's parsing the code backwards? – devRicher – 2016-12-19T15:17:19.257

is function composition, I gave the explanation in the order that the functions are actually evaluated – marinus – 2016-12-19T15:18:51.747

1

Here's the parse tree, for the curious: http://tryapl.org/?a=%u220A%u2355%A8%u2218%u233D%u2218%u2373%A8%u2218%u2373&run

– marinus – 2016-12-19T15:20:21.027

5

Python 2, 71 68 bytes

I bet a recursive solution could be shorter, but I'm having a hard time formulating this into one.

n=input()
i=0
o=""
while i<n:
    i+=1;j=i
    while j:o+=`j`;j-=1
print o

Try it online

mbomb007

Posted 2016-12-19T13:05:02.903

Reputation: 21 944

4

Python 3, 87 92 83 74 bytes

lambda n:"".join(["".join([str(i)for i in range(1,k)][::-1])for k in range(1,n+2)])

Shorter answer using recursion :

f=lambda n:f(n-1)+"".join([str(i)for i in range(1,n+1)][::-1])if n>0else""

Maybe not the shortest one but it's only made with Python's list comprehension !

(Edited to add the print function and remove the \n)

(Edited to remove the print function, and change n+1, k+1 to n,k+2)

Sygmei

Posted 2016-12-19T13:05:02.903

Reputation: 1 137

Works with k, n+2 but not with k+2, n, thanks though for the idea :) – Sygmei – 2016-12-22T09:16:16.577

The code that you're scoring should be first. Also, you should use Python 2 and then use \i`` instead of str(i). And you can use "".join(...) instead of "".join([...]), and range(1,k,-1) to remove the [...][::-1]. – mbomb007 – 2016-12-22T14:52:03.970

Also, n>0 can be n. And I meant range(n,0,-1). And use n and f(n-1)+...)or"". – mbomb007 – 2016-12-22T14:58:37.060

162 bytes. Actually, this may be getting too close to this answer. – mbomb007 – 2016-12-22T15:03:55.463

Yes this is getting pretty close, I saw that after doing my second version :( – Sygmei – 2016-12-22T16:05:51.797

4

Brachylog, 8 bytes

yb@[rcw\

Try it online!

Explanation

yb         The list [1, ..., Input]
  @[       Take a prefix of that list
    rc     Reverse it and concatenate into an integer
      w    Write to STDOUT
       \   Backtrack: try another prefix

Fatalize

Posted 2016-12-19T13:05:02.903

Reputation: 32 976

4

C89, 54 bytes

i,j;f(n){for(i=1;j<=n;j=i++)while(j)printf("%d",j--);}

56 -2 = 54 thanks to ErikGolfer!

cat

Posted 2016-12-19T13:05:02.903

Reputation: 4 989

I think you can do (j=i++) instead of (j=i) and remove the last i++ (untested). – Erik the Outgolfer – 2016-12-19T15:00:29.357

Here's a shorter recursive version: i,j;f(n){j=++i;while(j)printf("%d",j--);i-n?f(n):0;} (52 bytes) – Steadybox – 2016-12-19T16:33:30.813

@Steadybox You can add that as your own answer if you like, but thanks! – cat – 2016-12-20T14:01:30.800

@cat Ok, thanks, just did. Wasn't sure if I should since I only edited your solution. – Steadybox – 2016-12-20T22:35:57.557

4

Perl 6, 22 bytes

{[~] flat [\R,] 1..$_}

A lambda that returns a string.

(Try it online.)

Explanation:

  • 1..$_: Range of integers... (1 2 3 4)
  • [,] 1..$_: Reduce ("fold") over comma operator... (1 2 3 4)
  • [\,] 1..$_: With intermediate results (triangular reduce)... ((1) (1 2) (1 2 3) (1 2 3 4))
  • [\R,] 1..$_: Apply reversing meta-operator to the comma... ((1) (2 1) (3 2 1) (4 3 2 1))
  • [~] flat ...: Remove list nesting, and fold over string concat operator... 1213214321

smls

Posted 2016-12-19T13:05:02.903

Reputation: 4 352

4

Haskell, 35 bytes

f x=[1..x]>>= \y->[y,y-1..1]>>=show

Usage example: f 6 -> "121321432154321654321".

For all numbers x in 1 ... x make a list x,x-1, ... ,1, turn the numbers into a string and concatenate them into a single string. Again, concatenate those strings into a single string.

nimi

Posted 2016-12-19T13:05:02.903

Reputation: 34 639

3

Pyth, 8 bytes

jks_M._S

Explanation

jks_M._SQ   Implicit input
       SQ   Get the range [1, 2, ..., N]
     ._     Get each prefix
   _M       Reverse each prefix
jks         Join everything as a string

user48543

Posted 2016-12-19T13:05:02.903

Reputation:

3

05AB1E, 6 bytes

LR.sJJ

Try it online!

Adnan

Posted 2016-12-19T13:05:02.903

Reputation: 41 965

3

R, 38 33 44 bytes

if((n=scan())>0)for(i in 1:n)cat(i:1,sep="")

Takes input to STDIN, and loops from 1 to n, creating the sequence i to 1 for each step and printing it.

Edit: replaced seq(i,1) by i:1 saving 5 bytes and showing why I shouldn't golf during meetings.

JAD

Posted 2016-12-19T13:05:02.903

Reputation: 2 898

This produces 101 if the input is 0. if((n=scan())>0)for(i in 1:n)cat(i:1,sep="") does the trick. – Frédéric – 2016-12-19T17:44:27.200

Damn, assumed non-zero input :( – JAD – 2016-12-19T18:19:04.200

if(n<-scan()) should be sufficient. – Giuseppe – 2017-11-09T16:16:23.557

3

Mathematica, 36 bytes

ToString/@(""<>Range[Range@#,1,-1])&

Throws a bunch of warnings which can be safely ignored.

Explanation

Using input 5 as an example:

Range@#

Creates a range {1, 2, 3, 4, 5}.

Range[...,1,-1]

Range is listable so we can give it a list for any of its arguments and it will automatically thread over that argument. So this gives us a bunch of reversed lists:

{{1}, {2, 1}, {3, 2, 1}, {4, 3, 2, 1}, {5, 4, 3, 2, 1}}

Next:

(""<>...)

This joins the nested list with the empty string. Since the nested list doesn't actually contain any strings, it can't really join the values (which is where the warnings are generated), but ""<> has the side-effect of flattening the list. So this gives us

1 <> 2 <> 1 <> 3 <> 2 <> 1 <> 4 <> 3 <> 2 <> 1 <> 5 <> 4 <> 3 <> 2 <> 1

Now comes Mathematica's beautiful feature that Map doesn't care about the structure it's mapping over. You normally apply it to a list, but it works with any head. f /@ h[a, b, c] simply gives you h[f[a], f[b], f[c]]. In our case, the head is StringJoin and the values are the integers.

ToString/@...

So this simply turns the integers into strings. At that point StringJoin[...] knows what to do with them and joins them all into a single string:

"121321432154321"

Martin Ender

Posted 2016-12-19T13:05:02.903

Reputation: 184 808

1That's just plain nasty. :) – Greg Martin – 2016-12-20T00:59:01.963

3

GolfScript, 14 bytes

~,{),{)}%-1%}%

Try it online!

Usual method of course, but this is GolfScript.

Explanation for this VAST piece of code:

~,{),{)}%-1%}% # Code
               # Initial stack.      ["n"]
~              # Eval ToS.           [n]
 ,             # ToS' lowered range. [[0..n)]
  {),{)}%-1%}  # Block. 1 argument.  [a]
   )           # Increment.          [a+1]
    ,          # Range.              [[0..a)]
     {)}       # Block. 1 argument.  [b]
      )        # Increment.          [b+1]
        %      # Map.                [[1..a]]
         -1    # Integer. -1         [[1..a] -1]
           %   # Each nth element.   [[a..1]]
             % # Map.                [[[1],[2,1],...,[n..1]]]
               # Implicit output.    121...n..1

Note that output is as a single number. Trailing \n.

Erik the Outgolfer

Posted 2016-12-19T13:05:02.903

Reputation: 38 134

3

MATL, 14 11 bytes

:"@:P]v!VXz

Try it online!

Explanation

:      % Input N implicitly. Push range [1 2 ...N]
"      % For each k in [1 2 ...N]
  @:   %   Push range [1 2 ... k]
  P    %   Reverse
]      % End
v!     % Concatenate all arrays horizontally
V      % Convert to string
Xz     % Remove spaces. Display implicitly

Luis Mendo

Posted 2016-12-19T13:05:02.903

Reputation: 87 464

not split up by anything, don't think the second one is allowed. – JAD – 2016-12-19T16:24:01.633

2@JarkoDubbeldam I'll delete that one until OP clarifies – Luis Mendo – 2016-12-19T16:26:02.310

1@Jarko The OP clarified. Current solution conforms to spec – Luis Mendo – 2016-12-19T19:37:03.280

3

Python, 63 57 59 bytes

A recursive solution that works in both Python 2 and 3. This can probably be golfed further. Golfing suggestions welcome! Try it online!

Edit: -6 bytes thanks to Jonathan Allan. +2 bytes with thanks to mbomb007 for pointing out a problem with my answer.

f=lambda n:n and f(n-1)+"".join(map(str,range(n,0,-1)))or""

Ungolfing

def f(n):
    s = ""
    for i in range(n+1):
        m = map(str, range(n, 0, -1))
        s += "".join(m)
    return s

Sherlock9

Posted 2016-12-19T13:05:02.903

Reputation: 11 664

2Use a map to save 6 bytes: lambda n:n and f(n-1)+"".join(map(str,range(n,0,-1)))or"" – Jonathan Allan – 2016-12-19T19:26:56.827

3

brainfuck, 17 bytes

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

Explanation

>           keep the first cell at 0
 ,          input of the decimal number into the cell
  [>        start a conditionnal loop and go to the next cell
   [+.>]    while it don't find 0, increment each cells and output the value
    +.      increment the new cell and output
     [<]    go to the first cell
      >-]   decrement the second cell and restart

Try it online!

Milihhard

Posted 2016-12-19T13:05:02.903

Reputation: 41

Welcome to PPCG! Have you read the tour page and the hottest meta questions yet? I advise you to, they're helpful! Also, wrap your code in code formatting! Have you read the formatting help? You should also explain how your code works, if you can! – devRicher – 2016-12-21T18:53:30.827

@muddyfish I've just added the explanation – Milihhard – 2016-12-21T19:10:05.770

I've used a mobile app. You can see the screen of the result. – Milihhard – 2016-12-21T19:21:12.780

No it's fine. But in the link, the ouput is in ascii and not in decimal, so you don't really see the output – Milihhard – 2016-12-21T20:13:39.843

@muddyfish Your permalink is a tad confusing. There's an invisible 0x06 in the input, followed by the decimal digit 6. – Dennis – 2016-12-21T20:14:24.870

2

PHP, 35 34 33 bytes

Saved a byte because I miscounted, thanks Titus! And another!

while($i++<$argv[1])echo$s=$i.$s;

Run from command line with -r.

Pretty simple answer, loops from 1 through our input n, tacking the number onto the beginning of the string and printing it out.

Xanderhall

Posted 2016-12-19T13:05:02.903

Reputation: 1 236

I count 34. One byte shorter with post-increment. – Titus – 2016-12-19T16:01:47.657

33 bytes: while($i++<$argv[1])echo$s=$i.$s; – aross – 2016-12-20T10:51:30.583

1

CJam, 13 bytes

ri,:){,:)W%}%

interpreter

Erik the Outgolfer

Posted 2016-12-19T13:05:02.903

Reputation: 38 134

You can save 2 bytes: ri{),:)W%}% – Luis Mendo – 2016-12-19T16:25:16.873

@LuisMendo Neat, thanks for that! – Erik the Outgolfer – 2016-12-19T17:21:16.330

1

C#, 67 65 bytes

f=n=>{int x=n;var r="";while(n>0)r+=n--;return x>0?f(x-1)+r:"";};

Anonymous recursive function which returns the required string.

Full program with ungolfed method and test cases:

using System;

public class Program
{
    public static void Main()
    {
        Func<int, string> f = null;
        f = n =>
        {
            int x = n;
            var r = "";
            while (n > 0)
                r += n--;
            return x > 0 ? f(x - 1) + r : "";
        };

        Console.WriteLine(f(6));    // 121321432154321654321
        Console.WriteLine(f(1));    // 1
        Console.WriteLine(f(26));   // 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321222120191817161514131211109876543212322212019181716151413121110987654321242322212019181716151413121110987654321252423222120191817161514131211109876543212625242322212019181716151413121110987654321
        Console.WriteLine(f(0));    // "" (empty string)
    }
}

adrianmp

Posted 2016-12-19T13:05:02.903

Reputation: 1 592

I'm not sure if I could condone anonymous recursive functions, given that you need to declare and assign it beforehand for it to work (you can't call it directly: see test code). (Note: I'm personally not a fan of anonymous methods as answers, but this I think is step too far) – VisualMelon – 2016-12-19T14:57:31.873

Looks like there is already a policy on this: http://meta.codegolf.stackexchange.com/questions/10360/how-should-i-submit-an-anonymous-lambda-that-has-a-self-reference

– VisualMelon – 2016-12-19T15:04:42.740

The function name is actually included in the byte count (f=...). Also, the C# example from the accepted answer in the meta.codegolf link you provided will not compile! You need to declare the anonymous function first, like in this answer: http://stackoverflow.com/a/61206/6649825

– adrianmp – 2016-12-19T15:25:29.500

Indeed. Honestly, I'm not happy with the allowance of code that can't be called directly (e.g. codehere(arguments)) or that doesn't provide a named method to call (actually, I'd prefer that all C# submissions were a complete program). I might bring this up on meta, because it doesn't feel like there is quite a clear consensus on lambdas in general, but it does feel like this is a step too far. If I post something on meta, I'll put a link here, and you can feel free to join in the discussion. – VisualMelon – 2016-12-19T15:27:01.267

I guess anonymous methods are allowed to further reduce the code size - verbose languages like C# or Java 8+ are more competitive this way (however they are no match for a golfing language). Otherwise, we'd still use classic method definitions. – adrianmp – 2016-12-19T15:33:56.800

You're quite right, but I'm miserable and old-fashioned, and like to see code that I can compile and run, not where I have to wrap it in parentheses, and tell the computer what type it expects to make it work. Static Typing is an invaluable feature in C# (and Java, and others) which we shouldn't get it for free. I'm writing up a (probably very long) meta question, we'd probably better defer any further discussion away from this thread. It's an import issue, one I'm sure I'm not going to get my way on (though I think I hold it objectively), but it needs a consensus we can follow nonetheless. – VisualMelon – 2016-12-19T15:45:04.493

Posted: http://meta.codegolf.stackexchange.com/questions/10974/c-lambdas-as-answers-to-questions-asking-for-a-function - no idea how it will be received, but might elicit some sort of discussion. Please do chime in if you have comments (there are relatively few C#ers here, and it's really meant for us).

– VisualMelon – 2016-12-19T17:32:57.033

1

Octave, 47 48 bytes

@(n)num2str((g=meshgrid(n:-1:1)')(g<=1:n)','%d')

Try it online!

Explanation:

meshgrid(n:-1:1)' :create a grid of repeated n:1

   6   6   6   6   6   6
   5   5   5   5   5   5
   4   4   4   4   4   4
   3   3   3   3   3   3
   2   2   2   2   2   2
   1   1   1   1   1   1

(g<=(1:n)) :only select those elements that are under anti-diagonal

   0   0   0   0   0   1
   0   0   0   0   1   1
   0   0   0   1   1   1
   0   0   1   1   1   1
   0   1   1   1   1   1
   1   1   1   1   1   1

rahnema1

Posted 2016-12-19T13:05:02.903

Reputation: 5 435

This doesn't work in matlab or in 2 octave online interpreters I've tried - I've never seen = used in lambdas, it's not valid in Matlab. Did this work for you in octave? Is it new version syntax? – Hugh Nolan – 2017-03-28T17:31:34.737

@HughNolan You are right in the current version of Octave it doesn't work(behavior of ndgrid has changed ). It worked in Octave 3.6.2. I will edit the post. In octave assignment can be done in expressions including lambdas. Some features of octave related to golfing is in Tips for golfing in Octave

– rahnema1 – 2017-03-28T17:47:41.483

1@HughNolan Answer updated, you can try it online. – rahnema1 – 2017-03-28T19:20:15.213

Nice thanks for the update, good to know about assignment in lambdas - a good push for octave! – Hugh Nolan – 2017-03-28T21:19:45.213

1

JavaScript, 53 bytes

f=(n,s='',x=n)=>{while(n)s+=n--;return x?f(--x)+s:''}

Thanks Titus for saving me bytes!

Oliver

Posted 2016-12-19T13:05:02.903

Reputation: 7 160

1At n>0 and x>0, the >0 is unnecessary. Can You save a byte with for(x=n;n;)s+=n--;? – Titus – 2016-12-19T16:09:04.593

1

PowerShell, 41 bytes

1..$args[0]|%{$a+=-join($_..1)};,$a-ne101

Try it online!

(7 bytes to handle the special case of 0 for input)

Loops from 1 up to the input $args[0], each iteration concatenates onto $a the result of a -join operation operating on the range from the current number $_ down to 1. Then, we turn $a into an array , and select those elements of the array that are -notequal to 101 (this filters out the 0 input). That's left on the pipeline and output is implicit.

NB -- Since strings in PowerShell (and .NET) are based on the StringBuilder class which is a char array, the maximum length we can get to is 2^31-1. But, PowerShell on your desktop will likely run out of memory before then, and TIO has an output limit of 256 KiB, so the actual maximum value supported is quite a bit smaller than that.

AdmBorkBork

Posted 2016-12-19T13:05:02.903

Reputation: 41 581

10 is not exactly a special case, if the code will error, thats valid. – devRicher – 2016-12-19T16:19:52.770

@devRicher Zero is indeed a special case, because it's smaller than the loop delimiter of 1. The code above won't error without the handling at the end, instead it will output 101 for input 0. Exiting with an error would actually be longer (but shorter yet would be not worrying about input 0 at all). – AdmBorkBork – 2016-12-19T16:26:41.033

I see, yes, 101 is invalid. – devRicher – 2016-12-19T16:34:18.650

1

QBIC, 25 bytes

:[a|[b,1,-1|A=A+_t!c$|}?A

Sample run:

Command line: 10
12132143215432165432176543218765432198765432110987654321

Explanation:

:           Get 'a' from the command line
[a|         FOR b=1; b<=a; b++
[b,1,-1|      FOR c=b; c>=1; c--
A=A+_t!c$|      Append c to the 'output buffer' A$
}           Close the FOR loops
?A          Print 'a'

Non-competing: five minutes ago, I taught QBIC to do implicit printing on exit of anything stored in Z$. That brings the code for this challenge down to 22 bytes 19 bytes since I've made the cast-to-string autotrim!

:[a|[b,1,-1|Z=Z+!c$

steenbergh

Posted 2016-12-19T13:05:02.903

Reputation: 7 772

1

Scala, 22 bytes

1 to _ map(_ to(1,-1))

Returns a sequence of sequences of ints.

Usage:

val f:(Int=>Seq[Seq[Int]])=1 to _ map(_ to(1,-1))
println(f(6))

Ungolfed:

n=>1 to n map(i=>i to 1 by -1)

Explanation:

1 to _      //create a Range from 1 to the argument of this function
map(        //map each element to...
  _ to(1,-1)  //a range from the number to 1, in steps of -1
)

corvus_192

Posted 2016-12-19T13:05:02.903

Reputation: 1 889

1

bash, 69 bytes

f()([ $1 = 0 ]||(echo -n $1;f $[$1-1]));[ $1 = 0 ]||($0 $[$1-1];f $1)

f is a recursive function, and the entire script is recursive too.

Edit: @DigitalTrauma posted an improved version of this, which you can see in his comment on this answer. I'm not going to take the time to modify the answer, since he also posted a completely different bash solution, using brace expansion, that blows this answer away!

Mitchell Spector

Posted 2016-12-19T13:05:02.903

Reputation: 3 392

Some minor optimizations: f()((($1))&&printf $1&&f $[$1-1]);(($1))&&$0 $[$1-1];f $1. Brace expansions make it much shorter though :)

– Digital Trauma – 2016-12-19T20:23:45.613

1@DigitalTrauma Thank you. Btw, I had tried using brace expansions, but couldn't shorten the code enough, since I didn't know that bash accepted {m..n} with m>n. That was actually something I was going to check out today. Now I don't have to :) – Mitchell Spector – 2016-12-19T22:25:56.593

1

Mathematica, 38 54 bytes

FromDigits@*Flatten@IntegerDigits@Range[Range@#,1,-1]&

I stole Range[Range@#,1,-1] from Martin Ender's (still shorter) answer to save three bytes (dammit, I gotta start remembering that some functions are Listable). IntegerDigits converts the multi-digit numbers in the result to lists of single digits, Flatten removes all the list nesting, and FromDigits reassembles them into an integer. Oh well.

Greg Martin

Posted 2016-12-19T13:05:02.903

Reputation: 13 940

1

PHP, 52 49 bytes

<?for(;$k++<$argv[1]+2;$j=$k)while(--$j>0)echo$j;

Dexa

Posted 2016-12-19T13:05:02.903

Reputation: 236

Don't you need to outroduce your code with a > or ?>? – devRicher – 2016-12-20T12:46:02.400

You can remove the braces around the inner {while...}. @devRicher the closing tag is not necessary, and it is generally considered best practice not to include it in code-only scripts. – primo – 2016-12-20T13:21:44.593

@primo Thanks for suggestion, but I can't since inner while and $j=$k; are both tied to first while condition. @devRicher no that's not necessary – Dexa – 2016-12-20T13:25:11.097

@Dexa you could change the first while to a for, and move the $j=$k into the post-evaluation: for(;$k++<$argv[1]+2;$j=$k). – primo – 2016-12-20T13:33:44.490

@primo Thanks, edited. – Dexa – 2016-12-20T13:42:56.020

1

Ruby, 37 34 bytes

->n{a=p;(1..n).map{|i|p a=[i,a]}*''}

Saved 3 bytes thanks to G B.

Seims

Posted 2016-12-19T13:05:02.903

Reputation: 631

Even better (34 bytes): ->n{a=p;(1..n).map{|i|a=[i,a]}*''} using an accumulator initialized with nil and growing a nested array which is flattened all together at the end. – G B – 2016-12-23T23:55:36.920

Very clever! Added it. – Seims – 2016-12-24T14:56:55.900

1

Keg, 11 bytes (SBCS)

Now I realized that Keg is pretty hard to use...

¿Ï_^'(Ï_')"

Try it online!

user85052

Posted 2016-12-19T13:05:02.903

Reputation:

0

Python 2, 58 Bytes

print[[a for a in range(b+1,0,-1)]for b in range(input())]

Or, if the output of the above is not allowed, then the following code for 59 Bytes:

for i in range(input()+1):
 for j in range(i,0,-1):print j,

sonrad10

Posted 2016-12-19T13:05:02.903

Reputation: 535

0

05AB1E, 6 bytes

LR.sJJ

Uses the CP-1252 encoding. Try it online!

         # Implicit input
 L       # Push [1, 2, ..., n]
  R      # Reverse
   .s    # Get suffixes
     JJ  # Join twice
         # Implicit output

Oliver Ni

Posted 2016-12-19T13:05:02.903

Reputation: 9 650

0

Batch, 68 bytes

@for /l %%i in (1,1,%1)do @for /l %%j in (%%i,-1,1)do @cmd/cset/a%%j

Fortunately not printing newlines only costs 5 bytes.

Neil

Posted 2016-12-19T13:05:02.903

Reputation: 95 035

0

Python, 80 bytes

r=''.join;lambda b:r([r([`i`for i in range(1,a+1)][::-1])for a in range(1,b+1)])

You can easily test this by pasting the above code into a repl and hitting enter, then typing _(6) or whatever input you want to give.

Rɪᴋᴇʀ

Posted 2016-12-19T13:05:02.903

Reputation: 7 410

0

C, 52 bytes

Based on cat's existing answer:

i,j;f(n){j=++i;while(j)printf("%d",j--);i-n?f(n):0;}

Call with:

int main()
{
    f(6);
}

Steadybox

Posted 2016-12-19T13:05:02.903

Reputation: 15 798

0

Java: 141 chars

void c(int in,StringBuilder s){for(int i=1;i<=in;i++){for(int j=i;j>0;j--){s.append(Integer.toString(j));}}System.out.println(s.toString());}

Using c(6,new StringBuilder());:

121321432154321654321

user44904

Posted 2016-12-19T13:05:02.903

Reputation:

1There are many ways you can golf this submission: 1) use a shorter name instead of in 2) use System.out.print instead of println, and you can in your first for-loop do int i=1,j so that you can leave the int out from the second for-loop – user41805 – 2016-12-22T12:16:50.880

0

Clojure, 94 84 74 bytes

-10 bytes by eliminating the redundant for.

-10 bytes by eliminating the let.

Still long, but -20 bytes is nice.

#(loop[r 1 a""](if(> r %)a(recur(inc r)(str a(apply str(range r 0 -1))))))

Generates the reversed range, and concats it to the accumulator, then loops again while necessary.

Ungolfed:

(defn negative-order [n]
  (loop [r 1
         a ""]
    (let [s (apply str (range r 0 -1))]
      (if (> r n)
        a
        (recur (inc r) (str a s))))))

Carcigenicate

Posted 2016-12-19T13:05:02.903

Reputation: 3 295

0

Clojure, 57 bytes

#(apply str(reductions(fn[s i](str(inc i)s))""(range %)))

reductions is perfect for incrementally producing outputs like this.

NikoNyrh

Posted 2016-12-19T13:05:02.903

Reputation: 2 361

0

Stacked, noncompeting, 20 bytes

~>~>reveach flat''#`

Try it online!

I think a few of the features used in this answer were made after this challenge.

Explanation

~>~>reveach flat''#`
~>                    range from [1, n]
  ~>                  vectorized range [[1,1], [1,2], ..., [1, n]]
    reveach           reverses each segment
            flat      flatten
                ''#`  join by nothing

Conor O'Brien

Posted 2016-12-19T13:05:02.903

Reputation: 36 228

0

Java, 99 bytes

void f(int a){int[]f=new int[2];while(++f[0]<=a){f[1]=f[0];while(f[1]>0)System.out.print(f[1]--);}}

EDIT 1: Saved few bytes by changing it from a full program to a function.

Ungolfed:

void f(int a) {
    int[] f = new int[2];
    while (++f[0] <= a) {
        f[1] = f[0];
        while (f[1] > 0) System.out.print(f[1]--);
    }
}

cookie

Posted 2016-12-19T13:05:02.903

Reputation: 271

You could save a few bytes by making a function instead (e.g. void f(int i){}). – devRicher – 2017-03-29T09:45:16.220

You can save some bytes by using for-loops instead of whiles, a Java 8 lambda instead of Java 7 method, and two integers instead of an integer array: a->{for(int f=0,g=0;++f<=a;)for(g=f;g>0;)System.out.print(g--);} (64 bytes) Try it here.

– Kevin Cruijssen – 2017-11-14T12:33:16.073

0

W j f, 3 bytes

It's actually pretty trivial in W ...

M_M

Explanation

a      % Take an input, say 3
     M % Identity map every item in numeric value 3
       % Since it is prohibited, a range is generated,
       % namely [1 2 3]
 a M   % For every item in [1 2 3]:
       % Note that single items are 1, 2, and 3, *not* the whole list
  a    % Generate a range from 1 to that number: [[1] [1 2] [1 2 3]]
    _  % Reverse for lists: [[1] [2 1] [3 2 1]]

Flag:f % Flatten the list: [1 2 1 3 2 1]
Flag:j % Join the list: 121321
```

user85052

Posted 2016-12-19T13:05:02.903

Reputation:

0

GolfScript, 12 bytes

~),(;{),(;}%

Try it online!

user85052

Posted 2016-12-19T13:05:02.903

Reputation: