41
\$\begingroup\$

Center The Text!

In this challenge you will be centering various lines.

Examples

Foo
barbaz

 Foo
barbaz
Hello
World

Hello
World
Programming Puzzles
&
Code Golf

Programming Puzzles
         &
     Code Golf

Specifications

Each input line will always have at least one non-whitespace character, you may assume the only whitespace character are spaces () and newlines. Each input line won't have any trailing and/or leading whitespace (except for the newline). Trailing whitespace in the output is not allowed.

You should be centering among the longest line in the input. If that line is even in length, your program/function should prefer to center to the left. The maximum line length is whatever your language can handle but your program should function on lines of at least 500 in length.


Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=66731,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


This is so shortest code in bytes wins!

\$\endgroup\$
12
  • \$\begingroup\$ There will never be more than one inner-space? \$\endgroup\$
    – cat
    Commented Dec 16, 2015 at 1:41
  • \$\begingroup\$ @cat there will never be any leading whitespace or trailing whitespace on a line (expect for the newline if there is one) \$\endgroup\$
    – Downgoat
    Commented Dec 16, 2015 at 1:43
  • \$\begingroup\$ yes, but I mean inner-spaces, like, between words \$\endgroup\$
    – cat
    Commented Dec 16, 2015 at 1:45
  • 1
    \$\begingroup\$ @cat oh, between words there may be more than one whitespace. For example foo(space)(space)(space)bar is a perfectly acceptable input \$\endgroup\$
    – Downgoat
    Commented Dec 16, 2015 at 1:46
  • 1
    \$\begingroup\$ @GamrCorps I'd say no, your program should still work even if only one line is given as input. \$\endgroup\$
    – Downgoat
    Commented Dec 16, 2015 at 1:58

26 Answers 26

31
\$\begingroup\$

vim, 43 36 35 bytes

VGrx:sor
G:let &tw=col("$")
uu:%ce

Too good not to post. Note the trailing newline; it is significant.

Thanks to @Marth for saving a character!

vim-friendly format:

VGrx:sor<cr>G:let &tw=col("$")<cr>uu:%ce<cr>

Explanation:

VGrx                   replace every character with an "x"
:sor<cr>               sort (since all chars are now same, sorts by line length)
G                      go to the very last line
:let &tw=col("$")<cr>  set &tw to column number of last char on this line
                         "let &tw" is equivalent to "set tw"
                         tw is short for textwidth, used in :center
uu                     undo the sort, and the replacing-with-x too
:%ce<cr>               center over entire file (%), using textwidth set earlier
\$\endgroup\$
7
  • 1
    \$\begingroup\$ Surely this should all be done in Insert mode, right? \$\endgroup\$
    – Alex A.
    Commented Dec 16, 2015 at 2:38
  • 9
    \$\begingroup\$ @AlexA. None of it is done in insert mode. ಠ_ಠ \$\endgroup\$
    – Doorknob
    Commented Dec 16, 2015 at 2:40
  • \$\begingroup\$ If you use sor! to reverse the sort order, you can use col("$") to get the length of the first line (now the longest since the order is reversed) instead of using G$, saving a grand total of 1 byte! edit: or you could keep the sort order and use G:let &tw=col("$") instead. \$\endgroup\$
    – Marth
    Commented Dec 16, 2015 at 12:05
  • \$\begingroup\$ @Marth Thanks! I chose the latter (for no particular reason). \$\endgroup\$
    – Doorknob
    Commented Dec 16, 2015 at 12:19
  • \$\begingroup\$ Looking through :h :sort I just found out that you can pass a regex to skip the matching text in the sort, so you can use :sor /./ to sort on length (+4 bytes), which lets you remove the VGrx (-4 bytes) and the second undo (-1 bytes). You can also use | separators instead of <cr> to chain the commands, which lets you skip the : before let (-1 bytes) (note that you have to use the sor! solution then, G is not an ex command). So :sor! /./|let &tw=col("$")|u|%ce (with a trailing <CR>) should save 2 bytes. \$\endgroup\$
    – Marth
    Commented Dec 16, 2015 at 12:42
23
\$\begingroup\$

Mathematica, 96 bytes

StringRiffle[#~StringPadLeft~Floor[Max@(l=StringLength)@a/2+l@#/2]&/@(a=#~StringSplit~"
"),"
"]&

Don't ask me how it worked, I just fiddled with it until it produced the correct output.

\$\endgroup\$
2
  • 27
    \$\begingroup\$ +1 for "Don't ask me how it worked, I just fiddled with it until it produced the correct output" \$\endgroup\$
    – cat
    Commented Dec 16, 2015 at 3:13
  • 4
    \$\begingroup\$ @cat That's how I do all my golfing. \$\endgroup\$
    – lirtosiast
    Commented Dec 17, 2015 at 4:37
15
\$\begingroup\$

Pyth, 19 17 bytes

2 bytes thanks to Jakube

V.ztr+1.[l.T.zNd6

Demonstration

I think this is the first time the center-pad function of .[ has been useful. The length of the longest line is found using non-truncating transpose (.T).

Trailing spaces are removed by adding a non-space character to the front, stripping spaces, then removing the added character.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ We probably need a max length in array. It comes up way too often. +1 \$\endgroup\$
    – Maltysen
    Commented Dec 16, 2015 at 2:28
  • \$\begingroup\$ The specifications say that "Trailing whitespace in the output is not allowed." This appears to have trailing whitespace on each short line in the output, so I'm not sure it counts. \$\endgroup\$
    – potato
    Commented Dec 16, 2015 at 5:55
  • \$\begingroup\$ @potato Thanks - that was added since I answered. \$\endgroup\$
    – isaacg
    Commented Dec 16, 2015 at 6:39
11
\$\begingroup\$

Funciton, non-competitive

This challenge has highlighted the sore lack of a “maximum value” (and minimum value) function for lazy sequences, so... I added them to the core library (they’re called ⊤ and ⊥, respectively). Therefore I didn’t bother to submit this as a golfed answer (it would have to include the ⊤ function declaration to be valid), so here’s just the main program.

Execute (function(){$('pre,code').css({lineHeight:5/4,fontFamily:'DejaVu Sans Mono'});})() in your browser console to get some nicer rendering.

   ╓───╖         ╔════╗  ┌───╖  ╔═══╗
 ┌─╢ ‡ ╟─┐       ║ 10 ╟──┤ ǁ ╟──╢   ║
 │ ╙───╜ │       ╚════╝  ╘═╤═╝  ╚═══╝
 │ ┌───╖ │  ┌──────────────┴──────────────────┐
 └─┤ ‼ ╟─┘┌─┴─╖ ┌───╖ ┌───╖ ┌───╖ ┌───╖       │     │
   ╘═╤═╝  │ ɱ ╟─┤ ⊤ ╟─┤ + ╟─┤ ~ ╟─┤ ℓ ╟───┐ ┌─┴─╖ ┌─┴─╖ ╔════╗
     │    ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╘═══╝ ╘═══╝   │ │ ɱ ╟─┤ ʝ ╟─╢ 10 ║
    ┌───╖ ╔═╧═╕ ╔═══╗ ┌─┴──╖ ┌───╖ ╔════╗ │ ╘═╤═╝ ╘═══╝ ╚════╝
  ┌─┤ ℓ ╟─╢   ├─╢ 1 ║ │ >> ╟─┤ … ╟─╢ 32 ║ │   │
  │ ╘═══╝ ╚═╤═╛ ╚═╤═╝ ╘═╤══╝ ╘═╤═╝ ╚════╝ │ ╔═╧═╕ ╔═══╗
  └─────────┘     └─────┘      │   ┌───╖  ├─╢   ├─╢ 0 ║
                               └───┤ ‡ ╟──┘ ╚═╤═╛ ╚═══╝
                                   ╘═╤═╝      │
                                     └────────┘

Explanation

I believe this may be the first Funciton answer on this site that uses lambda expressions.

  • First, we use ǁ to split the input string at the newlines (ASCII 10). This returns a lazy sequence.
  • We pass that sequence through ɱ (map), giving it a lambda that calculates the length of each string, and then pass the final sequence through to get the length of the longest line.
  • We also pass that sequence through another ɱ, giving it a lambda that calculates the length of each string, subtracts it from the maximum line length calculated earlier, divides that by 2 (actually shift-right 1), generates that many spaces (ASCII 32) and then concatenates the string onto those spaces. (For geometric reasons, I declared a function that calls (string concatenate) with the parameters reversed.)
  • Finally, we use ʝ to put all of the strings back together, using newlines (ASCII 10) as the separator.
\$\endgroup\$
1
9
\$\begingroup\$

Retina, 54 52 bytes

+m`^(.)+$(?<=(?=[^\t]*^..(?<-1>.)+(?(1)^))[^\t]*)
 $0 

The \ts can replaced with actual tabs, but I've used \t here, because otherwise SE will convert the tabs to spaces. Note that there is a leading space on the second line.

Try it online.

Explanation

The basic idea is to match a line which is at least two characters shorter than the longest line (or technically, two characters shorter than any other line), and surround it in two spaces. This is repeated until we can no longer find such a line, which means that all lines are within one character of the maximum length (where the one character is to account for parity mismatches, and guarantees that these lines are shifted to the left off-centre).

As for the actual regex:

^(.)+$

Just matches any one line while pushing one capture onto group 1 for each character.

(?<=...[^\t]*)

Is a lookbehind which is matched right-to-left and moves the cursor to the beginning of the string, so that the lookahead inside can check the entire string. Note that due to a lack of an anchor, the lookahead could be applied from anywhere else, but that does not create additional matches. We know that [^\t] will always match any character in the string, because the input is guaranteed to contain only spaces and linefeeds as far as whitespace is concerned.

(?=[^\t]*^..(?<-1>.)+(?(1)^))

This lookahead tries to find a line which is at least two characters longer than the one we're currently matching. [^\t]* moves through the string in order to be able to match any line. ^ ensures that we're starting from the beginning of the line. .. then matches the two additional characters we require for the longer line. Now (?<-1>.)+ matches individual characters in that line while popping from group 1 (note that . cannot match a linefeed, so this is constrained to one line). Finally, (?(1)^) asserts that we managed to empty the entire group 1. If the line is shorter than required, this is not possible, because there are not enough characters in the line to pop from group 1 often enough to empty it.

\$\endgroup\$
7
\$\begingroup\$

Jolf, 3 bytes

Noncompeting, update postdates question.

Try it here!.

pci
pc  center
  i  string input

¯\_(ツ)_/¯ I thought it'd be a useful function.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This is a standard loophole, and while not explicitly dis-allowed, its bad form unless its built into a language you find, not one you create. \$\endgroup\$ Commented Dec 17, 2015 at 0:36
  • 3
    \$\begingroup\$ @EliasBenevedes I added the feature before the contest. I don't often update my code until it becomes relavent. \$\endgroup\$ Commented Dec 17, 2015 at 0:39
7
\$\begingroup\$

JavaScript (ES6), 93 91 bytes

s=>(m=l=s.split`
`).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join`
`

2 bytes saved thanks to @edc65!

Explanation

s=>(
  m=                // m = max line length (divided by 2)
    l=s.split`
`)                  // l = array of lines
.map(x=>            // for each line
  (v=x.length/2)    // v = current line length / 2
    <m?v:m=v        // set m to the max line length and return v
)
.map((x,i)=>        // for each line length / 2
  " ".repeat(m-x)   // add spaces before
    +l[i]           // add line text
)
.join`
`                   // return lines as a newline-separated string

Test

var solution = s=>(m=l=s.split`
`).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join`
`
<textarea id="input" rows="4" cols="20">Programming Puzzles
&
Code Golf</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>

\$\endgroup\$
1
  • \$\begingroup\$ .repeat accepts and truncates non-integer values, so you don't need |0 \$\endgroup\$
    – edc65
    Commented Dec 16, 2015 at 11:10
7
\$\begingroup\$

CJam, 26 23 19 bytes

qN/_z,f{1$,m2/S*\N}

My first time using CJam! Four bytes saved thanks to Martin Büttner. Try it online.

Explanation

qN/    e# Read input and split each line
_z,    e# Transpose a copy and get its length to find the longest line
f{     e# For each line...
  1$,- e# Subtract its length from the longest length
  2/   e# Divide by two to get just the spaces to add to the left
  S*\  e# Add a string with that many spaces to the beginning
  N    e# Add a newline to go on to the next line
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Here are some suggestions :) qN/_z,f{1$,m2/S*\N} \$\endgroup\$ Commented Dec 16, 2015 at 8:28
6
\$\begingroup\$

LabVIEW, 3 or 35 LabVIEW Primitives

Finds lines until none are left, then calculates how many spaces to add and puts everything together.

Alternatively you could use the built-in center alignment on string indicators, it kinda does feel like cheating though.

\$\endgroup\$
6
\$\begingroup\$

Python 2, 83 81 bytes

def f(s):
 t=s.split('\n')
 for y in t:print(max(len(f)for f in t)-len(y))/2*' '+y  

Thanks to @xnor for saving 2 chars

example input:

f("""Programming Puzzles
&
Code Golf""")

example output:

Programming Puzzles
         &
     Code Golf

And ending in second place with 84 bytes using str.center() and str.rstrip (thanks @J F).

def f(s):
 t=s.split('\n')
 for y in t:print y.center(max(len(f)for f in t)).rstrip()
\$\endgroup\$
3
  • \$\begingroup\$ It doesn't save chars to assign len to a variable you use twice -- that breaks even at 5 chars (like range). Also, you can use map for the list comp. \$\endgroup\$
    – xnor
    Commented Dec 16, 2015 at 5:59
  • \$\begingroup\$ @Willem, you could use str.rstrip() after calling center to get rid of the trailing space. \$\endgroup\$
    – J F
    Commented Dec 19, 2015 at 16:33
  • \$\begingroup\$ You can save 7 bytes with a full program and using len(max(a,key=len)), see this. \$\endgroup\$ Commented Apr 23, 2018 at 12:05
5
\$\begingroup\$

TeaScript, 24 bytes

£p.R((aßln)¯-ln)/2)+l,§)

Loops through lines, adds floor((max line length - line length) / 2) spaces to the beginning.

Ungolfed

£   p.R((aß  ln)¯  -ln)/2)+l,§   )
xl(#p.R((am(#ln)X()-ln)/2)+l,`\n`)

xl(#    // Loops through newlines
    p.R(   // Repeats spaces
      (
       am(#ln)    // Map all line lengths
              X() // Get largest line length
       -ln)       // Subtract current line length
      /2)  // Divide by two
      +l,  // Add current line text
`\n`)

Try it online

\$\endgroup\$
2
  • 6
    \$\begingroup\$ Why do my answers keep getting Downgoated? I think it's time to change the username / avatar :p \$\endgroup\$
    – Downgoat
    Commented Dec 17, 2015 at 4:25
  • \$\begingroup\$ Fixed as of 2016-07-27. :P \$\endgroup\$
    – user48538
    Commented Jul 27, 2016 at 15:51
5
\$\begingroup\$

PowerShell, 58 67 bytes

down to 58 bytes thanks to @mazzy's comments:

param($a)$a|%{$_|% *ft(($a|% le*|sort)[-1]/2+$_.length/2)}


# It takes an array of strings as input
PS C:\Temp> .\center.ps1 'aaa','bb','c'
aaa
bb
 c


# Or here, read from a file
PS C:\Temp> .\center.ps1 (gc t.txt)
info0:info1:info2:info3
      info0:info1
          ttt
          tt
           t
  • It takes an array of strings as $a, loops over each string with |%{...}.
  • calls the string.padleft() method on each string, via % -member shortcut, which takes desired final line length as a parameter.
    • we need array_longest_line_length/2 + current_line_length/2
    • the end part is current_line_length/2 -> $_.length/2
    • the other part is recalculating the array's maximum line length every time through the loop, and it does so with a nested loop making an array of line lengths, sorts that, then takes the last one.
\$\endgroup\$
2
3
\$\begingroup\$

Emacs Lisp, 203 bytes

(let((f 0)(l 0))(dolist(s(split-string(buffer-string)"\n"))(set'l(string-width s))(when(> l f)(set'f l)))(let((fill-column f))(goto-char(point-min))(while(<(point)(point-max))(center-line)(next-line)))))

Ungolfed:

(let ((f 0) (l 0))
  (dolist (s (split-string(buffer-string) "\n"))
    (set 'l (string-width s))
    (when (> l f)
      (set 'f l)))
    (let ((fill-column f))
      (goto-char (point-min))
      (while (< (point) (point-max))
        (center-line)
        (next-line)))))

Centered:

               (let ((f 0) (l 0))
 (dolist (s (split-string(buffer-string) "\n"))
           (set 'l (string-width s))
                 (when (> l f)
                  (set 'f l)))
             (let ((fill-column f))
            (goto-char (point-min))
         (while (< (point) (point-max))
                 (center-line)
                (next-line)))))
\$\endgroup\$
3
\$\begingroup\$

Ruby, 76 68 61 bytes

->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}

Sample run:

2.1.5 :001 > puts ->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}["Programming Puzzles\n&\nCode Golf"]
Programming Puzzles
         &
     Code Golf
\$\endgroup\$
2
  • \$\begingroup\$ 53 bytes: ->t{(s=t.split$/).map{|l|l.center s.map(&:size).max}} \$\endgroup\$
    – daniero
    Commented Dec 16, 2015 at 21:54
  • 1
    \$\begingroup\$ I also tried the center way first, but as I understand, that alone would break the “Trailing whitespace in the output is not allowed” rule. Thank you for the &:size part – I also tried that too, but I certainly banged something around the syntax. \$\endgroup\$
    – manatwork
    Commented Dec 17, 2015 at 7:35
3
\$\begingroup\$

HTML, 40 bytes

<xmp style=float:left;text-align:center>

<xmp style=float:left;text-align:center>
Programming Puzzles
&
Code Golf
</xmp>

Snippet includes </xmp> tag because the code snippet viewer wants my tags to be balanced.

\$\endgroup\$
1
  • \$\begingroup\$ Whoa, xmp is HTML 2.0, that’s dinosaur technology. It’s funny that you’re using style that wasn’t an attribute until HTML 4.0, though. I wonder how HTML can be an (upvoted) eligible submission. It’s a markup language; you know, there is no input/output facility. \$\endgroup\$ Commented Sep 4, 2023 at 20:30
2
\$\begingroup\$

MATL, 22 31 bytes

`jtYz~]xXhc4X4H$ZuZ{Zv

Each line is input with a trailing line (that is, an enter keystroke). An empty line (two enter keystrokes) marks the end of input.

Example

>> matl `jtYz~]xXhc4X4H$ZuZ{Zv
> foo
> barbaz
> 
 foo
barbaz

Explanation

`          % do...
  j        % input one string
  tYz~     % is it not empty?
]          % ...while
x          % delete last input (empty string)
Xh         % concatenate all inputs into a cell array
c          % convert to char (2D array). This fills with spaces to the right
4X4H$Zu    % center justify
Z{         % convert to cell array of strings
Zv         % remove trailing blanks of each string
\$\endgroup\$
2
\$\begingroup\$

Haskell, 111 81 77 bytes

l=length
f s|q<-lines s=unlines[([1..div(maximum(l<$>q)-l w)2]>>" ")++w|w<-q]

Input to the f function, the output is not printed.

Usage: load in interpreter ghci center.hs and then if you want to print the output of f on a given string putStr$f"Programming Puzzles\n&\nCode Golf"

Edit: Thanks to nimi for 34 bytes, great job! :D

\$\endgroup\$
4
  • \$\begingroup\$ Two more things: The latest version of the Prelude includes an infix version of map: <$>. replicate(...)' ' can be replaced by [1.. ...]>>" ". All in all: unlines[([1..div(maximum(l<$>q)-l w)2]>>" ")++w|w<-q]. \$\endgroup\$
    – nimi
    Commented Dec 17, 2015 at 15:38
  • \$\begingroup\$ Ah yes I remember you mentioning the new map infix in a previous submission I made. How does the replicate trick work? \$\endgroup\$ Commented Dec 17, 2015 at 15:45
  • \$\begingroup\$ l1 >> l2 makes (length l1) copies of l2 and concatenates them. E.g. "abcd" >> [1,2] -> [1,2,1,2,1,2,1,2] (<- 4 copies of 1,2 in a single list). In our case it's [1..n]>>" " which is n copies of a space which is the same as what replicate does. \$\endgroup\$
    – nimi
    Commented Dec 17, 2015 at 15:51
  • \$\begingroup\$ Nice, thanks for the explanation! :) \$\endgroup\$ Commented Dec 17, 2015 at 15:52
2
\$\begingroup\$

R, 126 bytes

code

for(z in 1){l=scan(,"");m=sapply(l,nchar);t=max(m[m==max(m)]);for(i in 1:length(m))cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")}

ungolfed

for(z in 1){                          # any way to get rid of this?
  l=scan(,"")
  m <- sapply(l,nchar)
  t <- max(m[m==max(m)])
  for(i in 1:length(m)){
    cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")
  }
}

Probably there are waay better ways to do this, still working on it.

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

Gema, 160 bytes

\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}}
?=
\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o

Written mostly for my curiosity to see what can be done in a language without proper array structure and proper loop instruction.

Sample run:

bash-4.3$ gema '\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}};?=;\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o' <<< $'Programming Puzzles\n&\nCode Golf'
Programming Puzzles
         &
     Code Golf
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 61 bytes

$/=(my@l=lines)».chars.max;for @l {put ' 'x($/-.chars)/2~$_} # 61 bytes

usage:

$ perl6 -e '$/=(my@l=lines)».chars.max;for @l {put " "x($/-.chars)/2~$_}' <<< \
'Programming Puzzles
&
Code Golf'
Programming Puzzles
         &
     Code Golf
\$\endgroup\$
2
  • \$\begingroup\$ Perl 5 would allow you to drop the spaces in things like for @l {, shaving 2 bytes, and to change put " " to put" ", shaving another byte. Is that true for Perl 6? (I don't know Perl 6.) Also, your output as displayed here doesn't match the required output; is that a typo? \$\endgroup\$
    – msh210
    Commented Dec 17, 2015 at 17:42
  • \$\begingroup\$ @msh210 Perl 6 is a bit more restrictive with its syntax. It more than makes up for it in other areas though. \$\endgroup\$ Commented Dec 18, 2015 at 3:08
1
\$\begingroup\$

Japt, 28 25

¡V=VwXl}R;¡Sp½*(V-Xl¹+X}R

Try it online!

How it works

¡     V=VwXl}R;¡     Sp½*(V-Xl¹ +X}R
UmXYZ{V=VwXl}R;UmXYZ{Sp½*(V-Xl) +X}R

           // Implicit: U = input string, V = 0
UmXYZ{  }  // Map each item X in U through this function,
         R // splitting U at newlines beforehand:
  V=VwXl   //  Set V to max(X, Y.length).
           // V is now set to the length of the longest line.

UmXYZ{  }  // Map each item X in U with this function,
         R // again splitting U at newlines beforehand:
 ½*(V-Xl)  //  Take V minus X.length, and multiply by 1/2.
Sp         //  Repeat a space that many times.
        +X //  Concatenate X to the end.
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 2 bytes

.c

Builtins ftw ¯\_(ツ)_/¯

Try it online or verify all test cases.

Explanation:

.c   # Centralize the (implicit) multi-line input-string with preference to the left
     # (output the result implicitly)

(Preference to the right would be with a capital .C instead: see the differences.)

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

PHP, 98 bytes

function($s){foreach($a=explode("
",$s)as$l)echo str_pad($l,max(array_map(strlen,$a)),' ',2),"
";}

Try it online!

Ungolfed:

function str_center( $s ) {
    $a = explode( PHP_EOL, $s );
    $m = max( array_map( 'strlen', $a ) );
    foreach( $a as $l ) {
        echo str_pad( $l, $m, ' ', STR_PAD_BOTH ), PHP_EOL;
    }
}

Output:

Programming Puzzles
         &         
     Code Golf   
\$\endgroup\$
0
\$\begingroup\$

Japt, 1 byte

û

Try it or run all test cases

\$\endgroup\$
1
  • \$\begingroup\$ why was this at -1 votes lol \$\endgroup\$
    – Razetime
    Commented Sep 10, 2020 at 7:57
0
\$\begingroup\$

APL (Dyalog Extended), 25 bytes

{↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵}

There's an APLcart snippet for centering in a field:

Is(⊢↑⍨∘-∘⌊2÷⍨+∘≢)Dv

This answer is partly based on it.

Try it online!

Explanation

{↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵}
      (⌈/≢¨⍵)             Maximum of lengths of each line
             +≢¨⍵         Plus length of each line
     (           )÷2      divided by two
   -⌊(           )        Floor it, and take negative
  (                 )↑¨⍵  Take that much from each line
                          (taking a negative value prepends spaces)
 ↑                        Mix the final array to print on each line
{                       } dfn
\$\endgroup\$
0
\$\begingroup\$

Pascal, 404 bytes

This complete program is suitable for any processor complying with ISO standards 7185 (“Standard Pascal”) or 10206 (“Extended Pascal”). The maximumLineLength algorithm requires that every line has a maximum length of maxInt characters.

program p(input,output);type Z=integer;var b:text;l:file of Z;c,m:Z;begin
m:=0;c:=0;rewrite(b);rewrite(l);while not EOF do begin if EOLn then begin
write(l,c);c:=0;writeLn(b)end else begin c:=c+1;if c>m then
m:=c;write(b,input^)end;get(input)end;reset(b);reset(l);while not EOF(b)do
begin read(l,c);for c:=1 to(m-c)div 2 do write(' ');while not EOLn(b)do
begin write(b^);get(b)end;writeLn;get(b)end end.

Ungolfed:

program centerTheText(input, output);
    type
        integerNonNegative = 0‥maxInt;
    
    var
        { The behavior of `reset(input)` is implementation-defined.
          Using a buffer `text` file avoids relying on specific behavior. }
        buffer: text;
        { Stores the length of a line in `input` (buffered in `buffer`). }
        lineLength: file of integerNonNegative;
        { The length of the currently processed line. }
        currentLineLength: integerNonNegative;
        { The length of the longest line found. }
        maximumLineLength: integerNonNegative;
    
    begin
        maximumLineLength ≔ 0;
        currentLineLength ≔ 0;
        { Open files for writing and set their lengths to zero (“truncate”). }
        rewrite(buffer);
        rewrite(lineLength);
        
        { process and analyze `input` ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ }
        while not EOF(input) do
        begin
            { Invocation of `EOLn(input)` is only valid if `not EOF(input)`. }
            if EOLn(input) then
            begin
                { `input↑` contains a space so we cannot just copy it. }
                writeLn(buffer);
                { Store the determined line length for the centering. }
                write(lineLength, currentLineLength);
                { Prepare `currentLineLength` for the next line. }
                currentLineLength ≔ 0;
            end
            else
            begin
                currentLineLength ≔ currentLineLength + 1;
                { In Extended Pascal you could write: `maximumLineLength ≔
                  card([0‥currentLineLength, 0‥maximumLineLength]) − 1`. }
                if currentLineLength > maximumLineLength then
                begin
                    maximumLineLength ≔ currentLineLength;
                end;
                { For later reference store `input↑` in `buffer`. }
                write(buffer, input↑);
            end;
            { Advance reading cursor. }
            get(input);
        end;
        
        { Open files for reading from the start. }
        reset(buffer);
        reset(lineLength);
        
        { Reproduce `input` but centered. ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ }
        while not EOF(buffer) do
        begin
            read(lineLength, currentLineLength);
            { In Extended Pascal you could also just write:
              `write('':(maximumLineLength − currentLineLength) div 2)` }
            for currentLineLength ≔ 1 to
                (maximumLineLength − currentLineLength) div 2 do
            begin
                write(output, ' ');
            end;
            { Do not enter loop in case of an empty line. }
            while not EOLn(buffer) do
            begin
                write(output, buffer↑);
                get(buffer);
            end;
            { Discard the end-of-line marker character. }
            get(buffer);
            { Emit the implementation-specific end-of-line marker character. }
            writeLn(output);
        end;
    end.

Extended Pascal, 252 bytes

Requiring a processor compliant with ISO standard 10206 “Extended Pascal” the schema data type string becomes available. Lots of operations can be thus abbreviated:

program p(input,output);var b:text;l:string(maxInt);m:integer;begin
m:=0;rewrite(b);while not EOF do begin readLn(l);if m<length(l)then
m:=length(l);writeLn(b,l)end;reset(b);while not EOF(b)do begin
readLn(b,l);writeLn('':(m-length(l))div 2,l)end end.

Ungolfed:

program centerTheText(input, output);
    type
        { `integer…` prefix to facilitate sorting in documentation tools. }
        integerNonNegative = 0‥maxInt;
    
    var
        buffer: text;
        line: string(maxInt);
        maximumLineLength: integerNonNegative value 0;
    
    begin
        { The size of `buffer` immediately becomes zero. }
        rewrite(buffer);
        { Find the length of the longest line in `input`. }
        while not EOF(input) do
        begin
            readLn(input, line);
            { Is the current line longer than the longest line so far? }
            if length(line) > maximumLineLength then
            begin
                maximumLineLength ≔ length(line);
            end;
            { Store the read `input` line in `buffer` for later retrieval. }
            writeLn(buffer, line);
        end;
        
        { (Re‑)open `buffer` and start reading `buffer` from the start. }
        reset(buffer);
        { The `while` loop is not entered in case `buffer` is an empty file. }
        while not EOF(buffer) do
        begin
            readLn(buffer, line);
            { Empty strings (`''`) are only allowed in Extended Pascal.
              For `string` values the `integer` expression after the colon
              dictates the _exact_ width of the string padded with spaces. }
            writeLn('':(maximumLineLength − length(line)) div 2, line);
        end;
    end.
\$\endgroup\$

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.