-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_028.js
73 lines (60 loc) Β· 1.97 KB
/
problem_028.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Returns a list of strings which represents each line, fully justified
* @param {String[]} wordList
* @param {Number} k
* @return {String[]}
*/
function justifyText(wordlist, k) {
const justifiedList = [];
let currLength = -1;
let currWords = [];
for(let i = 0; i < wordList.length; i++) {
const word = wordList[i];
if(currLength + word.length + 1 > k) {
// Add justified line
const justifiedLine = justify(currWords, currLength, k);
justifiedList.push(justifiedLine);
// reset values
currLength = -1;
currWords = [];
}
currLength += word.length + 1;
currWords.push(word);
}
// Last check
if (currWords.length > 0) {
const justifiedLine = justify(currWords, currLength, k);
justifiedList.push(justifiedLine);
}
return justifiedList;
}
/**
* Returns the justified line based on the current words, current length, and the max length of the line
* @param {string[]} currWords
* @param {number} currLength
* @param {number} k
* @return {string}
*/
function justify(currWords, currLength, k) {
const spacesToAdd = k - currLength;
const guaranteedSpaces = 1 + Math.floor(spacesToAdd / (currWords.length - 1));
const bonusSpaceRecipients = spacesToAdd % (currWords.length - 1);
let line = '';
// not include the last word
for (let i = 0; i < currWords.length - 1; i++) {
const word = currWords[i];
line += word;
for (let j = 0; j < guaranteedSpaces; j++) {
line += ' ';
}
if (i < bonusSpaceRecipients) line += ' ';
}
line += currWords[currWords.length - 1]; // add the last word
return line;
}
console.log(justifyText(["the", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"], 16));
// ['the quick brown',
// 'fox jumps over',
// 'the lazy dog']
console.log(justifyText(["the", "quick"], 16)); // ['the quick']