Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just so no one thinks I'm trying to have them do my homework for me, this is my (working, I think) solution.</p> <p>I'm not sure I could have possibly been expected to write this much code on a whiteboard on demand, however, so I'm mostly curious to see how others would tackle it without looking at my code. (I made it to around the foreach in the interview before they called 'time' on me, so to speak)</p> <pre><code>function justify($str, $to_len) { $str = trim($str); $strlen = strlen($str); if($str == '') return ''; if($strlen &gt;= $to_len) { return substr($str, 0, $to_len); } $words = explode(' ', $str); $word_count = count($words); $space_count = $word_count - 1; if($word_count == 1) { return str_pad($str, $to_len, ' ', STR_PAD_BOTH); } $space = $to_len - $strlen + $space_count; $per_space = $space/$space_count; if(is_int($per_space)) { return implode($words, str_pad('', $per_space, ' ')); } $new_str = ''; $spacing = floor($per_space); $new_str .= $words[0] . str_pad('', $spacing); foreach($words as $x =&gt; $word) { if($x == $word_count - 1 || $x == 0) continue; if($x &lt; $word_count - 1) { $diff = $to_len - strlen($new_str) - (strlen(implode('', array_slice($words, $x)))); $new_str .= $word . str_pad('', floor($diff/($space_count - $x)), ' '); } } $new_str .= $words[$x]; return $new_str; } $tests = array(' hello world there ok then ', 'hello', 'ok then', 'this string is almost certainly longer than 48 I think', 'two words', 'three ok words', '1 2 3 4 5 6 7 8 9'); foreach($tests as $word) { print $word . ' = ' . str_replace(' ', '_', justify($word, 48)) . '&lt;br&gt;'; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload