20
\$\begingroup\$

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'
\$\endgroup\$
  • \$\begingroup\$ Can the numbers be printed one on each line (with the proper padding)? \$\endgroup\$ – Luis Mendo Oct 18 '16 at 16:28
  • \$\begingroup\$ @LuisMendo yes. \$\endgroup\$ – Conor O'Brien Oct 18 '16 at 22:17

25 Answers 25

8
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Oh. Well that was finished quickly. Nice job! \$\endgroup\$ – Conor O'Brien Oct 19 '16 at 21:25
16
\$\begingroup\$

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

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']))

\$\endgroup\$
5
\$\begingroup\$

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

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
\$\endgroup\$
  • 1
    \$\begingroup\$ An array of strings is acceptable, so .join("") is not needed. \$\endgroup\$ – Conor O'Brien Oct 18 '16 at 16:20
  • 1
    \$\begingroup\$ a=>a.map(n=>(" ".repeat(l=a.length)+n).slice(-l)) is the same length but works on integers as well as strings. \$\endgroup\$ – Neil Oct 18 '16 at 17:49
5
\$\begingroup\$

Perl, 26 bytes

-4 bytes thanks to @Ton Hospel

25 bytes of code + -a flag.

printf"%*s",~~@F,$_ for@F

Run with :

perl -ae 'printf"%*s",~~@F,$_ for@F' <<< "10 11 12"

(On some older version of Perl, you might need to add -n)

\$\endgroup\$
  • 1
    \$\begingroup\$ Using the -a option will make your code shorter... \$\endgroup\$ – Ton Hospel Oct 18 '16 at 17:12
  • \$\begingroup\$ @TonHospel hum, that sounds fairly obvious, silly me.. Thanks for the reminder \$\endgroup\$ – Dada Oct 18 '16 at 17:32
  • \$\begingroup\$ Slightly different method avoids the loop and saves a byte: Try it online! \$\endgroup\$ – Xcali Sep 29 '17 at 18:37
5
\$\begingroup\$

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:

  • $# is the number of args passed
  • %<n>d is a printf format specifier that prints an integer with up to n leading spaces
  • $@ is the list of all args passed
  • The format specifier is reused for each member of $@.

Ideone.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I don't think you can rely on a feature that is off by default. \$\endgroup\$ – DJMcMayhem Oct 18 '16 at 16:23
  • \$\begingroup\$ @DJMcMayhem I've spent far too many hours of my life fighting bad indent settings in vimgolf. Explicitly setting expandtab adds 7 strokes to this solution. The reason that's a problem is that I have to check for other approaches for avoiding/removing tabs that might now win. It's a lot of time, not at all fun, makes the quality of my solution worse, and doesn't even affect any of the test cases provided (none have 8+ numbers). If that's the rule, that's the rule, but I'd rather mark non-compete than do this without expandtab. \$\endgroup\$ – udioica Oct 18 '16 at 17:20
  • \$\begingroup\$ @DJMcMayhem About Ypp!{. It is indeed shorter. It also doesn't work. It would always bring the number 1 into the command line, regardless of the length of the file. \$\endgroup\$ – udioica Oct 18 '16 at 17:24
4
\$\begingroup\$

Ruby, 40 36 34 bytes

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

Can be worked on more.

Call as a lambda.

Explanation:

->m{m.map{|i|$><<i.rjust(m.size)}}
->m{                             } # lambda taking array m
    m.map{|i|                   }  # map over array using variable i
             $><<                  # output to $> (stdout)
                 i.rjust(m.size)   # right justify i to m's length
\$\endgroup\$
2
\$\begingroup\$

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

Mathematica, 25 bytes

#~StringPadLeft~Length@#&

Both input and output are lists of strings.

Explanation

Length@#

Get the length of the input (number of element).

#~StringPadLeft~...

Pad left each element in the input so that their lengths match the length of the input.

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 47

Anonymous function, input: array of strings, output: array of strings
Using a recursive padding function

a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

For an integer/string array as input, 49 bytes:

a=>a.map(x=>p(x),p=x=>(y=' '+x)[a.length]?x:p(y))

Test

f=
a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

function update() {
  var l=I.value.match(/\d+/g)||[]
  O.textContent = f(l)
}

update()
 
<input id=I oninput='update()' value='1000,400,30,7'>
<pre id=O></pre>

\$\endgroup\$
2
\$\begingroup\$

PHP, 55 Bytes

<?foreach($a=$_GET[a]as$i)printf("%".count($a)."s",$i);

Pevious Version 59 Bytes

<?foreach($a=$_GET[a]as$i)echo str_pad($i,count($a)," ",0);
\$\endgroup\$
  • 1
    \$\begingroup\$ Why using str_pad, when printf is enough ? foreach($a=$_GET[a]as$i)printf("%".count($a)."s",$i); \$\endgroup\$ – Crypto Oct 19 '16 at 6:41
2
\$\begingroup\$

J, 4 bytes

":~#

Try it online!

Unary function taking the list of numbers on the right as an array and returning the padded string.

Here it is in use at the REPL. Note that input lines are indented three spaces.

   f=: ":~#
   f 2 3
 2 3
   f 2 10
 210
   f 1111 222 33 4
1111 222  33   4
\$\endgroup\$
  • \$\begingroup\$ Wow. You beat my reference solution in J! Very nice. \$\endgroup\$ – Conor O'Brien Oct 19 '16 at 22:24
1
\$\begingroup\$

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

Kotlin, 90 bytes

Golfed:

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

Ungolfed:

fun main(a: Array<String>) {
    a.forEach { b ->
        for (i in 1..a.size - b.length) {
            print(" ")
        }
        print(b)
    }
}
\$\endgroup\$
1
\$\begingroup\$

Haskell, 47 bytes

k=length
f l=map(\s->replicate(k l-k s)' '++s)l

That’s a function from a list of strings to a list of strings, like the JavaScript answers. replicate allows one to get a list (Haskell strings are lists of characters) of a given size, so I use it — and the bolded assumption in the problem — to generate the padding (its length is N − <length of element>, for each element of the input list). I would have preferred to use a printf based solution rather than this one with replicate (it would have been shorter, for one thing) but the import statement kills any savings done on the function itself.

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

Java, 83 82 bytes

a->{String s="";for(int i=a.length,j=i;i-->0;)s+="%"+j+"s";return s.format(s,a);};

Constructs a format string designed to pad the given arguments by a number of spaces equal to the length of the array. The format string is used as an argument for String.format, and the result is then returned. The functional interface can accept either a String[] or an Integer[] or similar.

Full class:

public class Test {
    public static void main(String[] args) {
        java.util.function.Function<Integer[], String> f = a -> {
            String s = "";
            for (int i = a.length, j = i; i-- > 0;)
                s += "%" + j + "s";
            return s.format(s, a);
        };

        System.out.println(f.apply(new Integer[] {0}));
        System.out.println(f.apply(new Integer[] {2, 10}));
        System.out.println(f.apply(new Integer[] {7, 8, 9, 10}));
        System.out.println(f.apply(new Integer[] {1, 33, 333, 7777}));
        System.out.println(f.apply(new Integer[] {0, 0, 0, 0, 0, 0}));
    }
}

Try it on Ideone.

-1 byte thanks to @KevinCruijssen.

\$\endgroup\$
  • \$\begingroup\$ Nice approach, +1. You can golf it by 1 byte by putting the int ... and s+=... inside the if like this: for(int i=a.length,j=i;i-->0;s+="%"+j+"s"); \$\endgroup\$ – Kevin Cruijssen Oct 19 '16 at 8:02
1
\$\begingroup\$

Groovy, 36 Bytes

{a->a.collect{it.padLeft(a.size())}}

Takes in array of strings only, outputs array of padded strings.

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

MATL, 14 bytes

'%%%dd'inYDGYD

Try it out at MATL Online

This uses formatted string creation by first constructing the format string: %(NUM)d and then applies string formatting again using this format string and the input.

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

JavaScript 33 bytes

similar to @Hedi - but the default padding is ' ', so its 4 chars less

a=>a.map(s=>s.padStart(a.length))

f=a=>a.map(s=>s.padStart(a.length))

console.log(f(["0"]))
console.log(f(["1"]))
console.log(f(["2","3"]))
console.log(f(["2","10"]))
console.log(f(["17" ,"19" ,"2"]))
console.log(f(["1000" ,"400" ,"30" ,"7"]))

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

K (oK), 11 bytes

Solution:

,/(-#x)$$x:

Try it online!

Explanation:

Interpretted right-to-left. Convert to string, and left-pad with length of list, then flatten:

,/(-#x)$$x: / the solution                      | example:
         x: / save as 'x'                       |
        $   / string                            | $10 20 30 -> "10","20","30"
       $    / pad right by left                 | 5$"abc" -> "abc  "
  (   )     / do the stuff in brackets together |
    #x      / count x                           | #10 20 30 -> 3
   -        / negate                            |
,/          / flatten (concatenate-over)        | ,/" a"," b"," c" -> " a b c"
\$\endgroup\$
0
\$\begingroup\$

Pyth - 7 bytes

Straightforward answer using padding builtin.

sm.[;lQ

Test Suite.

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

C#, 39 bytes

s=>s.ConvertAll(c=>c.PadLeft(s.Count));

Takes a List<string> and outputs a List<string>.

Explanation:

/*Func<List<string>, List<string>> Lambda =*/ s =>
    s.ConvertAll(c =>                                // Create a new List<string> by...
        c.PadLeft(s.Count)                           // ...padding each element by 'N'
    )
;

Would've been a few bytes shorter to use LINQ if the import isn't counted and then returning IEnumerable<string> instead of a full blown list:

C#, 35+18 = 53 bytes

using System.Linq;s=>s.Select(c=>c.PadLeft(s.Count));
\$\endgroup\$
0
\$\begingroup\$

R, 47 bytes

cat(sprintf("%*.f",length(n<-scan()),n),sep="")

Reads input from stdin and uses C-style formating with sprintf. There should be some way the cat function is not needed but couldn't find a way to suppress the quotes on each element without it. If we only want start and end quotes we could use the slightly longer option:

paste0(sprintf("%*.f",length(n<-scan()),n),collapse="")
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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