AlgoDaily Solution

1var assert = require('assert');
2
3function textJustification(words, maxWidth) {
4  const res = [[]];
5  res[0].letters = 0;
6  for (let word of words) {
7    let row = res[res.length - 1];
8    if (row.length && row.letters + row.length + word.length > maxWidth) {
9      res.push([]);
10      row = res[res.length - 1];
11      row.letters = 0;
12    }
13    row.push(word);
14    row.letters += word.length;
15  }
16  for (let r = 0; r < res.length; r++) {
17    let row = res[r];
18    if (row.length === 1 || r === res.length - 1) {
19      res[r] =
20        row.join(' ') + ' '.repeat(maxWidth - row.letters - row.length + 1);
21      continue;
22    }
23    let line = row[0];
24    let spaces = maxWidth - row.letters;
25    let minSpaces = ' '.repeat(Math.floor(spaces / (row.length - 1)));
26    let addSpace = spaces % (row.length - 1);
27    for (let w = 1; w < row.length; w++) {
28      line += minSpaces + (w <= addSpace ? ' ' : '') + row[w];
29    }
30    res[r] = line;
31  }
32  return res.join('\n');
33}
34
35try {
36  const wordsLonger = [
37    'algodaily',
38    'is',
39    'awesome',
40    'and',
41    'you',
42    'can',
43    'text',
44    'justify',
45    'all',
46    'types',
47    'of',
48    'text',
49    'and',
50    'words',
51  ];
52  const result =
53    'algodaily  \n' +
54    'is  awesome\n' +
55    'and you can\n' +
56    'text       \n' +
57    'justify all\n' +
58    'types    of\n' +
59    'text    and\n' +
60    'words      ';
61
62  assert.equal(textJustification(wordsLonger, 11), result);
63
64  console.log(
65    'PASSED: `textJustification(wordsLonger)` should return `algodaily  \nis  awesome\nand     you\ncan    text\njustify all\ntypes    of\ntext    and\nwords      `'
66  );
67} catch (err) {
68  console.log(err);
69}

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.