46
\$\begingroup\$

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!

\$\endgroup\$
12
  • \$\begingroup\$ 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. \$\endgroup\$
    – steenbergh
    Dec 19, 2016 at 14:46
  • 1
    \$\begingroup\$ If the output has to be a single number, how can it be "arrays"? \$\endgroup\$
    – smls
    Dec 19, 2016 at 15:50
  • \$\begingroup\$ 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] ? \$\endgroup\$
    – smls
    Dec 19, 2016 at 16:00
  • 1
    \$\begingroup\$ I'm confused about the output format. Can you give examples of what is acceptable? Array of numbers? String with numbers separated by spaces? \$\endgroup\$
    – Luis Mendo
    Dec 19, 2016 at 16:19
  • 1
    \$\begingroup\$ Your regex allow output of mickey321211mouse. Really the \D parts have no reason to be there \$\endgroup\$
    – edc65
    Dec 20, 2016 at 13:45

57 Answers 57

1
2
2
\$\begingroup\$

Brachylog (v2), 7 bytes

⟦₁⟧₁ᵐcc

Try it online!

Function submission. (The TIO link contains a command-line argument to run a function as though it were a full program.)

This would be just five bytes if the sequences went down to 0 rather than 1 – so it seems that this is one of those questions that's decided by the choice of 0- versus 1-indexing.

Explanation

⟦₁⟧₁ᵐcc
⟦₁       Range from 1 to {the function input}
    ᵐ    On each element of that range,
  ⟧₁       take a descending range from that value to 1
     c   Concatenate the ranges
      c  Concatenate the digits of the resulting numbers
\$\endgroup\$
1
\$\begingroup\$

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)
    }
}
\$\endgroup\$
7
  • \$\begingroup\$ 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) \$\endgroup\$ Dec 19, 2016 at 14:57
  • \$\begingroup\$ Looks like there is already a policy on this: meta.codegolf.stackexchange.com/questions/10360/… \$\endgroup\$ Dec 19, 2016 at 15:04
  • \$\begingroup\$ 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 \$\endgroup\$
    – adrianmp
    Dec 19, 2016 at 15:25
  • \$\begingroup\$ 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. \$\endgroup\$ Dec 19, 2016 at 15:27
  • \$\begingroup\$ 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. \$\endgroup\$
    – adrianmp
    Dec 19, 2016 at 15:33
1
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 0 is not exactly a special case, if the code will error, thats valid. \$\endgroup\$
    – devRicher
    Dec 19, 2016 at 16:19
  • \$\begingroup\$ @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). \$\endgroup\$ Dec 19, 2016 at 16:26
  • \$\begingroup\$ I see, yes, 101 is invalid. \$\endgroup\$
    – devRicher
    Dec 19, 2016 at 16:34
1
\$\begingroup\$

JavaScript, 53 bytes

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

Thanks Titus for saving me bytes!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ At n>0 and x>0, the >0 is unnecessary. Can You save a byte with for(x=n;n;)s+=n--;? \$\endgroup\$
    – Titus
    Dec 19, 2016 at 16:09
1
\$\begingroup\$

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
)
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ Some minor optimizations: f()((($1))&&printf $1&&f $[$1-1]);(($1))&&$0 $[$1-1];f $1. Brace expansions make it much shorter though :) \$\endgroup\$ Dec 19, 2016 at 20:23
  • 1
    \$\begingroup\$ @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 :) \$\endgroup\$ Dec 19, 2016 at 22:25
1
\$\begingroup\$

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.

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

PHP, 52 49 bytes

<?for(;$k++<$argv[1]+2;$j=$k)while(--$j>0)echo$j;
\$\endgroup\$
5
  • \$\begingroup\$ Don't you need to outroduce your code with a > or ?>? \$\endgroup\$
    – devRicher
    Dec 20, 2016 at 12:46
  • \$\begingroup\$ 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. \$\endgroup\$
    – primo
    Dec 20, 2016 at 13:21
  • \$\begingroup\$ @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 \$\endgroup\$
    – Dexa
    Dec 20, 2016 at 13:25
  • \$\begingroup\$ @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). \$\endgroup\$
    – primo
    Dec 20, 2016 at 13:33
  • \$\begingroup\$ @primo Thanks, edited. \$\endgroup\$
    – Dexa
    Dec 20, 2016 at 13:42
1
\$\begingroup\$

Ruby, 37 34 bytes

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

Saved 3 bytes thanks to G B.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – G B
    Dec 23, 2016 at 23:55
  • \$\begingroup\$ Very clever! Added it. \$\endgroup\$
    – Seims
    Dec 24, 2016 at 14:56
1
\$\begingroup\$

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$
\$\endgroup\$
1
\$\begingroup\$

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

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
```
\$\endgroup\$
1
  • \$\begingroup\$ Gosh dang, I never knew you answered this in W. \$\endgroup\$
    – lyxal
    Mar 29, 2023 at 13:17
1
\$\begingroup\$

Keg, 11 bytes (SBCS)

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

¿Ï_^'(Ï_')"

Try it online!

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

Vyxal, 5 bytes

ɾɾRṅṅ

Try it Online!

Tied with first :(

Explained

ɾɾRṅṅ
ɾɾ    # range of range of [1...input]
  R   # reduce (reverse each of list)
   ṅṅ # join by nothing twice
\$\endgroup\$
0
\$\begingroup\$

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,
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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);
}
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – user41805
    Dec 22, 2016 at 12:16
0
\$\begingroup\$

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))))))
\$\endgroup\$
0
\$\begingroup\$

Clojure, 57 bytes

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

reductions is perfect for incrementally producing outputs like this.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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]--);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ You could save a few bytes by making a function instead (e.g. void f(int i){}). \$\endgroup\$
    – devRicher
    Mar 29, 2017 at 9:45
  • \$\begingroup\$ 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. \$\endgroup\$ Nov 14, 2017 at 12:33
0
\$\begingroup\$

GolfScript, 12 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Japt -P, 5 bytes

õõ cÔ

Try it

õõ cÔ     :Implicit input of integer
õ         :Range [1,input]
 õ        :Range [1,each], giving a 2D-array
   c      :Flatten after
    Ô     :Reversing each
          :Implicitly join & output
\$\endgroup\$
0
\$\begingroup\$

Thunno 2 N, 3 bytes

RRṃ

Attempt This Online!

Same as Reversed Iota's, but with the N flag which joins the nested list.

\$\endgroup\$
1
2

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.