Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Introduction

As an example, let's take the number 7. We then duplicate this and place 7 spaces in between. We get this:

7_______7

After that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7:

7_______7    
 6543210

Then, we just merge the two of them, so:

7_______7    
 6543210  becomes

765432107

This will be out output for N = 7.

Looks easy, right? Now let's take N = 12. We again insert 12 spaces between the two numbers, which gives us:

12____________12

Then we start the decrement:

12____________12
  111098765432

And this finally gives us:

1211109876543212

As you can see, the descending part ends at 2, not at 0.

Task

Given an integer, greater than 1, output the descending sequence as shown above.

Test cases

Input   Output

2       2102
3       32103
4       432104
5       5432105
6       65432106
7       765432107
8       8765432108
9       98765432109
10      10987654321010
11      111098765432111
12      1211109876543212
13      13121110987654313
14      141312111098765414
15      1514131211109876515
20      201918171615141312111020
99      9998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150499
100     1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100

This is , so the submission with the fewest number of bytes wins!

share|improve this question
    
The inner space must be filled with whole numbers or we should chop numbers if needed? There is not a test case about that (for instance 99) – edc65 Feb 27 at 11:31
    
@edc65 You should chop the numbers if needed. I have added 99 as a test case. – Adnan Feb 27 at 12:40

21 Answers 21

up vote 8 down vote accepted

CJam, 11 10 bytes

q4*~,W%s<\

Try it online. Assumes there is a trailing newline in the input. (Thanks to @jimmy23013 for saving a byte.)

Explanation

At the end of each line is what the stack looks like at that point (using 4 as an example).

q4*  e# Push input x 4 times, separated by newlines. ["4\n4\n4\n4\n"]
~    e# Evaluate, separating the 4's and converting them to numbers. [4 4 4 4]
,W%  e# Take the range of x and reverse it. [4 4 4 [3 2 1 0]]
s<   e# Cast to string and take the first x characters. [4 4 "3210"]
\    e# Swap the top two to get the final result. [4 "3210" 4]
share|improve this answer

Julia, 30 bytes

n->"$n"join(n-1:-1:0)[1:n]"$n"

This is an anonymous function that accepts an integer and returns a string. To call it, assign it to a variable.

We construct and join the descending sequence from n-1 to 0, and take the first n characters from the resulting string. We prepend and append this with the input as a string.

Verify all test cases online

share|improve this answer

Haskell, 44 bytes

s=show
f n=s n++take n(s=<<[n-1,n-2..])++s n

Usage example: f 14 -> "141312111098765414".

share|improve this answer

JavaScript (ES6), 55 52 bytes

n=>n+[...Array(m=n)].map(_=>--m).join``.slice(0,n)+n

Edit: Saved 3 bytes thanks to @WashingtonGuedes.

share|improve this answer
    
@WashingtonGuedes Bah, I never seem to get to use .keys(). – Neil Feb 27 at 10:17
    
.keys() is like .reduce. The right tool for the job, but you always find something that can do better in that particular case – edc65 Feb 27 at 11:40

Python 2, 82 72 58 53 bytes

lambda x:`x`+''.join(map(str,range(x)[::-1]))[:x]+`x`

Try it here!

Thanks to @Alex for teaching me that repr(x) = `x` saving me a bunch of bytes!

share|improve this answer

Pyth, 11 bytes

++Q<jk_UQQQ

Two alternative versions, which are all also 11 bytes (sigh):

s[Q<jk_UQQQ
pQp<jk_UQQQ
  Q           the input
       UQ     [0, 1, ..., input-2, input-1]
      _       reverse
    jk        join on empty string
   <     Q    first (input) characters
          Q   the input again
++            concatenate everything so it prints on one line

Try it here.

share|improve this answer

Japt, 13 bytes

U+Uo w ¬¯U +U

Test it online!

How it works

               // Implicit: U = input integer
  Uo           // Create the range [0..U).
     w         // Reverse.
       ¬       // Join.
        ¯U     // Slice to the first U chars.
U+         +U  // Append U on either end.
share|improve this answer

Jelly, 10 bytes

Ȯ’r0DFḣ³Ḍ³

Try it online!

How it works

Ȯ’r0DFḣ³Ḍ³  Main link. Input: n

Ȯ           Print n.
 ’          Decrement to yield n - 1.
  r0        Create a range from n - 1 to 0.
    D       Convert each integer to base 10 (array of decimal digits).
     F      Flatten the resulting array.
      ḣ³    Keep the first n elements.
        Ḍ   Convert from base 10 to integer.
         ³  Print the integer and set the return value to n.
            (implicit) Print the return value.
share|improve this answer

Retina, 98 110

Longest answer so far :-/

.+
$&;$&$*:
+`:(:+)$
$& $1
 (:)*
$#1
\d+$
$&0 $&0
T`d`,`\d+$
+`:(.*),
$1
+`. ,

(.+);(.*) 
$1$2$1

Try it online.

share|improve this answer
    
You can beat Java! – randomra Feb 27 at 13:00

Vitsy, 35 bytes

Since Vitsy isn't aware of how to make strings out of numbers, I implemented finding the length of the number in decimal places in the second line.

V0VVNHVv[XDN1mv$-DvD);]VN
1a/+aL_1+

Explanation:

V0VVNHVv[XDN1mv$-DvD);]VN
V                          Save the input as a global final variable.
 0V                        Push 0, push input.
   VN                      Output the input.
     H                     Push the range 0...intput.
      Vv                   Push the input, then save it as a temp variable.
        [             ]    Do the stuff in brackets infinitely or until exited.
         X                 Remove the top item of the stack.
          DN               Duplicate, then pop as output.
            1m             Calls the first line index, retrieving length.
              v            Pop the temp var and push it to the stack.
               $           Switch the top two items of the stack. 
                -          Subtract them.
                 Dv        Duplicate, then pop one as a temp var.
                   D);     If it's zero, exit the loop.
                       VN  Output the global var.

1a/+aL_1+
1a/+       Add .1. This makes sure we don't throw errors on input 0.
    a      Push ten.
     L     Pop the top item as n, push the log base n of second to top.
      _    Make it an int.
       1+  Add 1.

Try it Online!

Verbose mode for lols:

save top as permanent variable;
push 0;
save top as permanent variable;
save top as permanent variable;
output top as number;
push all ints between second to top and top;
save top as permanent variable;
save top as temporary variable;
begin recursive area;
remove top;
duplicate top item;
output top as number;
push 1;
goto top method;
save top as temporary variable;
switch the top two items;
subtract top two;
duplicate top item;
save top as temporary variable;
duplicate top item;
if (int) top is not 0;
generic exit;
end recursive area;
save top as permanent variable;
output top as number;
:push 1;
push 10;
divide top two;
add top two;
push 10;
push ln(top);
replace top with int(top);
push 1;
add top two;
share|improve this answer
    
Looks like verbose mode is wrong in its definition of L, fixing that now (won't update the question though). – VTCAKAVSMoACE Feb 27 at 1:39
    
Just curious, how do you prevent the method from being executed at the end of the program? Is the newline character a signal to return/exit the program? – LegionMammal978 Feb 27 at 11:44
    
@LegionMammal978 Imagine that the first line of every Vitsy program is the "main" method, and all other lines are public static void methods. The main ends the program when it is finished. As for how it does this, the instructions are held in a type ArrayList<ArrayList<String[]>>, where each line is a String[]. Every method is split at the newline by how the file is loaded, causing the main method to be separated from all other methods. – VTCAKAVSMoACE Feb 27 at 13:04
    
That explains why three levels are needed. So Strings are instructions, String[]s are methods (first one is main method), and ArrayList<String[]>s are classes (first one is main class), correct? – LegionMammal978 Feb 27 at 13:09
    
@LegionMammal978 That's all correct. :) – VTCAKAVSMoACE Feb 27 at 13:56

Pure Bash, 49

eval printf -va %s {$[$1-1]..0}
echo $1${a::$1}$1

Or:

Bash + coreutils, 48

echo $1$(seq $[$1-1] -1 0|tr -d \\n|head -c$1)$1
share|improve this answer
    
I'm not certain these are evaluating the range properly. Upon testing both print only half of the range. ie for $1=90, the range is only down to 45. My effort was " for i in $(eval echo {$1..0});do echo -n $i;done;echo $1" – rcjohnson Feb 27 at 6:17
    
@rcjohnson I think that is the required behaviour. What do you expect the output to be for N=90? – Digital Trauma Feb 27 at 6:19
    
@rcjohnson e.g. for N=12, the output should be 12, then the first 12 chars of 11..0 (or 111098765432), and then finally 12 – Digital Trauma Feb 27 at 6:22
    
Well upon re-reading the description I see that you are correct. The problem states "spaces" not integers. – rcjohnson Feb 27 at 6:35
    
@rcjohnson Yes, I think the "spaces" part only applies to intermediate steps. The final output should be just a string of digits. – Digital Trauma Feb 27 at 6:43

Retina, 63 bytes

.+
$0,y$0$*y$0$*x
x
$'_
(x)*_
$#1
+`(y+)y(.)
$2$1
,(\d+).*
$1$`

There is still quite some room for golfing...

Try it online!

share|improve this answer
    
Hm, I'm considering to make the $0 in $0$* optional as well, when the preceding token is a literal which is not a number (as your ys are)... seeing this I might actually implement that. – Martin Ender Feb 27 at 15:47
    
@MartinBüttner I thought that was the new feature but turned out not really. :) – randomra Feb 27 at 18:33
    
No, currently that only works at the beginning of the substitution. That said, maybe you can switch the roles of the first and last number to make use of that? – Martin Ender Feb 27 at 18:44

MATL, 15 bytes

VG:qPVXvG:)GVhh

EDIT (May 20, 2016) The code in the link uses Xz instead of Xv, owing to recent changes in the language.

Try it online!

V                 % input n. Convert to string
 G:               % range [1,2,...,n]
   qP             % convert into [n-1,n-2,...,0]
     VXv          % convert to string, no spaces
        G:)       % take first n characters only
           GV     % push input as a string, again
             hh   % concat horizontally twice    
share|improve this answer

Java, 93 bytes

String x(int v){String o=""+v;for(int i=v-1,c=o.length();o.length()-c<v;i--)o+=i;return o+v;}
share|improve this answer

Ruby, 41 bytes

->n{[n]*2*(r=0...n).to_a.reverse.join[r]}
share|improve this answer

Milky Way 1.6.5, 27 25 bytes

I'::%{K£BCH=}<ΩHG<+<;+!

Explanation

I                        ` empty the stack
 '::                     ` push 3 copies of the input
    %{K£BCH=}            ` dump digits of reversed range(n) as strings [n-1...0]
             <ΩHG<+<;+   ` select the first nth digits and pad them with n
                      !  ` output

Usage

$ ./mw <path-to-code> -i <input-integer>
share|improve this answer
    
What encoding does Milky Way use? – Adnan Feb 27 at 15:44
    
Uhhh.. UTF-8, I think haha. @AandN – Zach Gates Feb 27 at 17:08
    
I got this error (yes, I'm a Windows scumbag :p) while trying to run this. I pasted this: I'::%{K£BCH=}<OHG<+<;+! into an UTF-8 encoded file, but it doesn't work. – Adnan Feb 27 at 17:37
    
Here's a link to the file I'm using. @AandN – Zach Gates Feb 28 at 5:36

Perl 6, 31 bytes

{$_~([R~] ^$_).substr(0,$_)~$_}
{
  $_ # input
  ~  # string concatenated with
  ([R~] ^$_)    # all numbers up to and excluding the input concatenated in reverse
  .substr(0,$_) # but use only up to the input number of characters
  ~
  $_
}

Usage:

for 2,3,7,12,100 {
  say {$_~([R~] ^$_).substr(0,$_)~$_}( $_ )
}
2102
32103
765432107
1211109876543212
1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100
share|improve this answer

Perl, 43 + 2 = 45 bytes

I'm happy that I didn't used reverse and neither substr:

"@{[1-$_..0]}"=~s.\D..gr=~/.{$_}/;$_.=$&.$_

Requires the -pl flags.

$ perl -ple'"@{[1-$_..0]}"=~s.\D..gr=~/.{$_}/;$_.=$&.$_' <<< 12
1211109876543212

How it works:

                                            # '-p' read first line into `$_` and
                                            # auto print at the end
"@{[1-$_..0]}"                              # Create a list from -1-n..0 and
                                            # join it on space. This becomes:
                                            #   "-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0"
              =~s.\D..gr                    # Remove all but digits:
                                            #   "11109876543210"
                        =~/.{$_}/;          # Match the n first characters from
                                            # the generated string
                                  $_.=$&.$_ # Append the match and the input
share|improve this answer

C, 130 125 bytes

#define p(x) printf("%i",x);
i,y,h;f(x){for(i=y=x;(i-=h)>=0;){p(y--)h=floor(log10(y))+1;}if(i+=h)p(h=floor(y/pow(10,i)))p(x)}

Ungolfed version (with explanation):

#define p(x) printf("%i",x);     // alias to print an integer
i,y,h;                           // helper variables
f(x){                            // function takes an integer x as arg
    for(i=y=x;(i-=h)>=0;){       // i -> the remaining space
                                 // y -> the current descending number
        p(y--)                   // print y (at first y==x)
        h=floor(log10(y))+1;     // h -> the number of digits in y-1
    }                            // do it until there is no more empty space
    if(i+=h)                     // if needs to chop the last number
        p(h=floor(y/pow(10,i)))  // chop and print (implicitly cast of double to int)
    p(x)                         // print x at the end
}                                // end function

The implicitly cast from double to int in h=floor(...) allowed the use of #define p(x) saving 5 bytes.

Test on ideone.

share|improve this answer

R, 67 bytes (as function)

# usage example : f(7)
f=function(i)cat(i,substr(paste((i-1):0,collapse=''),1,i),i,sep='')

R, 63 bytes (input from STDIN)

i=scan();cat(i,substr(paste((i-1):0,collapse=''),1,i),i,sep='')
share|improve this answer

Brainfuck, 265 Bytes

This is only going to work with numbers < 10

Try the golfed version here:

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

Ungolfed. Try it here:

>
,
---------- Convert to base 10
----------
----------
----------
-------- 


[->+>+<<]>>[-<<+>>]<

Fill up the grid
[
[->+>+<<]>>[-<<+>>] //duplicate number like [5][0] -> [5][5]
<-
]

<[<]> Go to cell 1
[

>[>] Scan for zero
> Move one more
+ Add one
<< Move two back
[<] Scan for zero
> Move one forward
- Subtract One
]

> Move one forward into actual numbers
[
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
]
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
share|improve this answer
    
,>>++++++[<++++++++>-]<[-<->]< This can subtract 48 with shorter code length – Leaky Nun May 21 at 6:11
    
This is way shorter. – Leaky Nun May 21 at 6:23
    
This is even shorter. – Leaky Nun May 21 at 6:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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