anilak

Console Justification

May 15th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(args) {
  2.     var n = args[0] | 0,
  3.         maxWidth = args[1] | 0,
  4.         all = args.slice(2).join(' '),
  5.         words = all.split(' '),
  6.         i,
  7.         j,
  8.         result = [],
  9.         spacesCount = 0,
  10.         wordsCount = 0,
  11.         currentWidth = 0;
  12.  
  13.     function repeat(string, count) {
  14.         return (new Array(count + 1)).join(string);
  15.     }
  16.  
  17.     function clean(arr) {
  18.         var p,
  19.             arrNew = [];
  20.         for (p = 0; p < arr.length; p++) {
  21.             if (arr[p] !== '') {
  22.                 arrNew.push(arr[p]);
  23.             }
  24.         }
  25.         return arrNew;
  26.     }
  27.  
  28.     words = clean(words);
  29.     for (i = 0; i <= words.length; i++) {
  30.         if (i !== words.length && currentWidth + wordsCount + words[i].length  <= maxWidth) {
  31.             currentWidth += words[i].length;
  32.             wordsCount++;
  33.         } else if (wordsCount === 1) {
  34.             result += words[i - 1] + '\n';
  35.             currentWidth = (words[i] || '').length;
  36.         } else {
  37.             spacesCount = ((maxWidth - currentWidth) / (wordsCount - 1)) | 0;
  38.  
  39.             for (j = 0; j < wordsCount; j++) {
  40.                 if (j !== wordsCount - 1) {
  41.                     result += words[j + i - wordsCount] + repeat(' ', spacesCount);
  42.                 } else {
  43.                     result += words[j + i - wordsCount];
  44.                 }
  45.                 if (j < (maxWidth - currentWidth) % (wordsCount - 1)) {
  46.                     result += ' ';
  47.                 }
  48.             }
  49.  
  50.             result += '\n';
  51.             wordsCount = 1;
  52.             currentWidth = (words[i] || '').length;
  53.         }
  54.     }
  55.  
  56.     result = result.substring(0, result.length - 1);
  57.     return result;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment