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 string n, create a pyramid of the string split into pieces relative to the current row.

The first row contains the string unmodified.

The second row contains the string separated into halves by a pipe.

The third row separates it by thirds...

And so on. The length of each substring, where l is the length of string n is equal to

floor(l/n)

Characters left over are put in their own substring. The last row used is the first one where substrings are 2 in length.

Test Cases:

Input: Hello, world.

Output:

Hello, world.

Hello,| world|.

Hell|o, w|orld|.

Hel|lo,| wo|rld|.

He|ll|o,| w|or|ld|.

Input: abcdefghij

Output:

abcdefghij

abcde|fghij

abc|def|ghi|j

ab|cd|ef|gh|ij

Input: 01234567890abcdef

Output:

01234567890abcdef

01234567|890abcde|f

01234|56789|0abcd|ef

0123|4567|890a|bcde|f

012|345|678|90a|bcd|ef

01|23|45|67|89|0a|bc|de|f

Extra rules:

  • You can write a full program or a function, whichever uses less code.

  • Input will always be at least 4 characters in length.

  • You MUST use line breaks if your language supports them. If not possible, replace line breaks with :

  • Input will always be printable ASCII.

  • Minus 100% if your program solves P vs. NP.


Leaderboard:

var QUESTION_ID=104297,OVERRIDE_USER=62384;function answersUrl(e){return"http://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"http://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>

share|improve this question
    
0 bytes: return: false – Gabriel Benamy 6 hours ago
    
Detailed solution required. 😀 – Julian Lachniet 6 hours ago
    
Related 1 ... Related 2. – TimmyD 6 hours ago
1  
Nice first challenge! A few clarification questions -- is the input only printable ASCII (I strongly suggest "yes")? What does "line breaks are necessary when possible" mean? – TimmyD 6 hours ago
    
Just edited original question. – Julian Lachniet 6 hours ago

Perl, 46 + 1 = 47 bytes

Run with the -n flag

say s/.{$=}(?=.)/$&|/gr while($==y///c/++$,)-2

Try it online!

Code breakdown

-n                                              #Reads input into the $_ variable
say s/.{$=}(?=.)/$&|/gr while($==y///c/++$,)-2
                                 y///c          #Transliteration.  Implicitly operates on $_, replacing every character with itself and counting replacements
                                                #y///c effectively returns the length of $_
                                      /++$,     #Increments $, (which starts off at 0) and divides the length of $_ by $,
                              $==               #Stores the result of this division into $=
                                                #$= forces its contents to be an integer, so it truncates any decimal
                             (             )-2  #Returns 0 if $= is equal to 2
                        while                   #Evaluates its RHS as the condition.  If truthy, evaluates its LHS.
    s/          /   /gr                         #Substitution.  Implicitly operates on $_.
                                                #Searches for its first argument and replaces it with its second argument, repeating until it's done, and returns the new string.  $_ is not modified.
      .{$=}                                     #Looks for a string of $= characters...
           (?=.)                                #...that is followed by at least one non-newline character, but does not include this character in the match...
                 $&|                            #...and replaces it with itself followed by a pipe character.
say                                             #Output the result of the substitution.
share|improve this answer

Pyth, 16 bytes

Vh/lQ3j\|cQ/lQhN

V                # For N in range(1, \/ )
 h/lQ3           # 1+lenght(input)/3
      j\|        # join with '|'
         cQ      # chop input in
           /lQhN # lenght(input)/(N+1) pieces

try here

share|improve this answer

Pyth, 17 bytes

jmj\|cQ/lQdSh/lQ3

Explanation

     cQ/lQ         Divide into equal pieces (with the last shorter)
  j\|              Join with pipes
 m        d        Map to each row index...
           Sh/lQ3  ... up to the first row with substrings of length 2
j                  Join with newlines
share|improve this answer

C, 145 131 128 125 bytes

l,n,i=1,j;f(char*s){l=strlen(s);puts(s);do{n=l/++i;for(j=0;j<l;)j&&(j%n||putchar('|')),putchar(s[j++]);puts("");}while(n>2);}

This is a function that takes a string as its argument and prints the output to STDOUT.

l,n,i=1,j;       // declare some variables
f(char*s){       // declare the function
l=strlen(s);     // get the length of the string
puts(s);         // output the initial version, with trailing newline
do{n=l/++i;      // n is the number of characters per "section",
                 //  and we'll do-while n>2 to stop at the right time
for(j=0;j<l;)    // loop through the characters of the string
j&&(             // if j != 0,
j%n||            // and j % n == 0,
putchar('|')),   // insert a | before this character
putchar(s[j++]); // print the character
puts("");        // print a newline after the loop
}while(n>2);}
share|improve this answer

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.