# Output integers in negative order, increase the maximum integer everytime

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! • 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 Dec 19 '16 at 14:46 • If the output has to be a single number, how can it be "arrays"? – smls Dec 19 '16 at 15:50 • 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 Dec 19 '16 at 16:00 • I'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 Dec 19 '16 at 16:19 • Your regex allow output of mickey321211mouse. Really the \D parts have no reason to be there – edc65 Dec 20 '16 at 13:45 ## 53 Answers # 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) } }  • 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 Dec 19 '16 at 14:57 • Looks like there is already a policy on this: meta.codegolf.stackexchange.com/questions/10360/… – VisualMelon Dec 19 '16 at 15:04 • 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: stackoverflow.com/a/61206/6649825 – adrianmp Dec 19 '16 at 15:25 • 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 Dec 19 '16 at 15:27 • 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 Dec 19 '16 at 15:33 # 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. • 0 is not exactly a special case, if the code will error, thats valid. – devRicher Dec 19 '16 at 16:19 • @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 Dec 19 '16 at 16:26 • I see, yes, 101 is invalid. – devRicher Dec 19 '16 at 16:34 ## JavaScript, 53 bytes f=(n,s='',x=n)=>{while(n)s+=n--;return x?f(--x)+s:''} Thanks Titus for saving me bytes! • At n>0 and x>0, the >0 is unnecessary. Can You save a byte with for(x=n;n;)s+=n--;? – Titus Dec 19 '16 at 16:09 # 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 )  # 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!

• 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 Dec 19 '16 at 20:23 • @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 Dec 19 '16 at 22:25 # 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. # PHP, 52 49 bytes <?for(;$k++<$argv[1]+2;$j=$k)while(--$j>0)echo$j;  • Don't you need to outroduce your code with a > or ?>? – devRicher Dec 20 '16 at 12:46 • 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 Dec 20 '16 at 13:21 • @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 Dec 20 '16 at 13:25 • @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 Dec 20 '16 at 13:33 • @primo Thanks, edited. – Dexa Dec 20 '16 at 13:42 # Ruby, 37 34 bytes ->n{a=p;(1..n).map{|i|p a=[i,a]}*''}  Saved 3 bytes thanks to G B. • 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 Dec 23 '16 at 23:55 • Very clever! Added it. – Seims Dec 24 '16 at 14:56 ## 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$


# 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

• 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 Mar 28 '17 at 17:31
• @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 Mar 28 '17 at 17:47
• @HughNolan Answer updated, you can try it online. – rahnema1 Mar 28 '17 at 19:20
• Nice thanks for the update, good to know about assignment in lambdas - a good push for octave! – Hugh Nolan Mar 28 '17 at 21:19

# Keg, 11 bytes (SBCS)

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

¿Ï_^'(Ï_')"


Try it online!

# 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,


# 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


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

# Python, 80 bytes

r=''.join;lambda b:r([r([ifor 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.

# C, 52 bytes

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


Call with:

int main()
{
f(6);
}


## 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

• There 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 Dec 22 '16 at 12:16

## Clojure, 9484 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))))))


## Clojure, 57 bytes

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


reductions is perfect for incrementally producing outputs like this.

# 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


# 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]--);
}
}

• You could save a few bytes by making a function instead (e.g. void f(int i){}). – devRicher Mar 29 '17 at 9:45
• 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 Nov 14 '17 at 12:33

## Wjf, 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
$$$$


# GolfScript, 12 bytes

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


Try it online!