Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

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

Given a list of N non-negative integers, output those numbers with each left-padded by spaces to a length of N. (Alternatively, return a character/string list.) You may assume that N is greater than or equal to the number of digits of the largest number in the list. Trailing spaces are allowed in the output.

You may also take a string containing these numbers, but N is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. ["1", "2", "3"].

This is a code-golf, so the shortest program in bytes wins.

Test cases

input => 'output'
0 => '0'
1 => '1'
2 3 => ' 2 3'
2 10 => ' 210'
4 5 6 => '  4  5  6'
17 19 20 => ' 17 19 20'
7 8 9 10 => '   7   8   9  10'
100 200 300 0 => ' 100 200 300   0'
1000 400 30 7 => '1000 400  30   7'
1 33 333 7777 => '   1  33 3337777'
0 0 0 0 0 0 => '     0     0     0     0     0     0'
share|improve this question
    
@LuisMendo Yes. – Conor O'Brien 42 mins ago
    
Can the numbers be printed one on each line (with the proper padding)? – Luis Mendo 33 mins ago

13 Answers 13

Python, 32 bytes

lambda l:'%%%ds'%len(l)*len(l)%l

An anonymous function that takes a tuple as input. Either numbers or strings work.

Example:

l=(1,33,333,7777)

'%%%ds'
## A "second-order" format string

'%%%ds'%len(l)           -> '%4s'
## Inserts the length as a number in place of '%d'
## The escaped '%%' becomes '%', ready to take a new format argument
## The result is a format string to pad with that many spaces on the left

'%%%ds'%len(l)*len(l)    -> '%4s%4s%4s%4s'
## Concatenates a copy per element

'%%%ds'%len(l)*len(l)%l  -> '   1  33 3337777'
## Inserts all the tuple elements into the format string 
## So, each one is padded with spaces
share|improve this answer

Bash, 14

printf %$#d $@

Input list given at the command line.

Not much to explain here. Simply uses built-in printf facilities to do the necessary padding, based off the number of passed args.

Ideone.

share|improve this answer

Vim, 19 bytes

YPPG!{<C-F>|R%ri<CR>djVGgJ

Takes a list of numbers one-per-line. Relies on :set expandtab, which is popular, but not universal.

You clearly want to use :right for this. The question is how to get the number of lines onto the command line. The traditional way is :%ri<C-R>=line('$'), but all that text is long.

The shorter, more enterprising approach is to form the command line using the normal mode ! command. It involves some weird workarounds, expanding the file by 2 lines then removing them again, but it comes out 2 bytes shorter. And I'm kinda shocked the garbled command line I get (like :%ri+4!) actually works, but it does.

share|improve this answer
    
I don't think you can rely on a feature that is off by default. – DJMcMayhem 38 mins ago
    
Although, validity aside, I think Ypp!{... is one byte shorter than YPPG!{... – DJMcMayhem 22 mins ago

Ruby, 40 36 bytes

->m{m.map{|i|$><<i.rjust(m.length)}}

Can be worked on more.

Call as a lambda.

Explanation:

->m{m.map{|i|$><<i.rjust(m.length)}}
-> {                               } # lambda function
  m                                  # argument, in form of an array
    m.map{                        }  # map over array (used to iterate)
          |i|                        # using variable i
             $><<                    # output to $> (stdout)
                 i.rjust(m.length)   # right justify to m's length
share|improve this answer

PHP, 59 Bytes

<?foreach($a=$_GET[a]as$i)echo str_pad($i,count($a)," ",0);
share|improve this answer

PowerShell v2+, 36 bytes

param($a)$a|%{"{0,$($a.count)}"-f$_}

Takes input $a as an array of integers. Loops through them with $a|%{...}. Each iteration, uses the -format operator with the optional Alignment Component (based on $a.count) to left-pad the appropriate number of spaces. That resultant string is left on the pipeline. At end of program execution, the resulting strings are all left on the pipeline as an array.


Examples

Output is newline-separated on each run, as that's the default Write-Output at program completion for an array.

PS C:\Tools\Scripts\golfing> @(0),@(1),@(2,3),@(2,10),@(4,5,6),@(17,19,20),@(7,8,9,10),@(100,200,300,0),@(1000,400,30,7),@(1,33,333,7777),@(0,0,0,0,0,0)|%{""+($_-join',')+" -> ";(.\spaced-out-numbers $_)}
0 -> 
0
1 -> 
1
2,3 -> 
 2
 3
2,10 -> 
 2
10
4,5,6 -> 
  4
  5
  6
17,19,20 -> 
 17
 19
 20
7,8,9,10 -> 
   7
   8
   9
  10
100,200,300,0 -> 
 100
 200
 300
   0
1000,400,30,7 -> 
1000
 400
  30
   7
1,33,333,7777 -> 
   1
  33
 333
7777
0,0,0,0,0,0 -> 
     0
     0
     0
     0
     0
     0
share|improve this answer

JavaScript, 49 bytes

a=>a.map(n=>" ".repeat(a.length-n.length)+n)

Takes the arguments as a list of strings and also returns a list of strings.

Explanation:

a=>                                                   An unnamed function, which takes one argument, a
   a.map(n=>                               )          Do the following to each element n in a:
            " ".repeat(a.length-n.length)             Generate the spaces needed to justify the number
                                         +n           Append the number
share|improve this answer
    
An array of strings is acceptable, so .join("") is not needed. – Conor O'Brien 41 mins ago

JavaScript (ES7), 37 bytes

a=>a.map(v=>v.padStart(a.length,' '))

Input: Array of strings
Output: Array of strings

f=
  a=>a.map(v=>v.padStart(a.length,' '))
;
console.log(f(['0']))
console.log(f(['1']))
console.log(f(['2','3']))
console.log(f(['2','10']))
console.log(f(['4','5','6']))
console.log(f(['17','19','20']))
console.log(f(['7','8','9','10']))
console.log(f(['100','200','300','0']))
console.log(f(['1000','400','30','7']))
console.log(f(['1','33','333','7777']))
console.log(f(['0','0','0','0','0','0']))

share|improve this answer

05AB1E, 3 bytes

Code:

Dgj

Explanation:

D    # Duplicate the input array
 g   # Get the length 
  j  # Left-pad with spaces to the length of the array

Try it online! or Verify all test cases.

share|improve this answer

Perl, 30 bytes

An anonymous subroutine which takes an array as parameter.

sub{printf"%*s",~~@_,$_ for@_}

Run with :

perl -e 'sub{printf"%*s",~~@_,$_ for@_}->(10,11,12)'

It's unusual for perl golfs to be subroutine rather than conventional onliner with -n or -p. But in that case, it makes it shorter to count the number of element.

Still, a more perlian way isn't much longer (32 bytes) :

perl -nE 's/\S+/printf"%*s",1+y% %%,$&/ge' <<< "10 11 12"
share|improve this answer

Jelly, 7 6 bytes

L⁶xaUU

Input is an array of strings. Try it online! or verify all test cases.

How it works

L⁶xaUU  Main link. Argument: A (array of strings)

L       Yield the l, the length of A.
 ⁶x     Repeat ' ' l times.

    U   Upend; reverse all strings in A.
   a    Perform vectorizing logical AND, replacing spaces with their corresponding
        digits and leaving spaces without corresponding digits untouched.
     U  Upend; reverse the strings in the result to restore the original order of
        its digits, moving the spaces to the left.
share|improve this answer

CJam, 11 bytes

lS%_,f{Se[}

Try it online! (As a test suite.)

Explanation

l      e# Read input.
S%     e# Split around spaces.
_,     e# Copy and get length.
f{     e# Map this block over the list, passing in the length on each iteration.
  Se[  e#   Left-pad to the given length with spaces.
}
share|improve this answer

Kotlin, 81 Bytes

Golfed:

fun main(a:Array<String>){a.forEach{b->for(i in 1..a.size){print(" ")};print(b)}}

Ungolfed:

fun main(a: Array<String>) {
    a.forEach { b ->
        for (i in 1..a.size) {
            print(" ")
        }
        print(b)
    }
}
share
    
I don't know Kotlin, but wouldn't this print N spaces in front of each element instead of padding each element to width N? – Martin Ender 4 mins ago
    
you are correct, will fix – Psyduck77 1 min ago

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.