Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Word Wrap Problem
A sequence of words is given, there is a limit on the number of characters for each line. By putting line breaks, in such a way that lines are printed clearly.
The lines must be balanced, when some lines have lots of extra spaces and some lines are containing a small number of extra spaces, it will balance them to separate lines. It tries to use the same number of extra spaces to make them balanced.
This algorithm will produce how many words can be placed in one line, and how many lines are needed.
Input and Output
Input:
The length of words for each line. {3, 2, 2, 5}. The max width is 6.
Output:
Line number 1: Word Number: 1 to 1 (only one word)
Line number 2: Word Number: 2 to 3 (Second and 3rd word)
Line number 3: Word Number: 4 to 4 (4th word)
Algorithm
wordWrap(wordLenArr, size, maxWidth)
Input − The word length array, size of the array and the maximum width of the word.
Output − List of how many words will place per line.
Begin define two square matrix extraSpace and lineCost of order (size + 1) define two array totalCost and solution of size (size + 1) for i := 1 to size, do extraSpace[i, i] := maxWidth – wordLenArr[i - 1] for j := i+1 to size, do extraSpace[i, j] := extraSpace[i, j-1] – wordLenArr[j - 1] - 1 done done for i := 1 to size, do for j := i+1 to size, do if extraSpace[i, j] = 0, then lineCost[i, j] := 0 else linCost[i, j] := extraSpace[i, j]^2 done done totalCost[0] := 0 for j := 1 to size, do totalCost[j] := ∞ for i := 1 to j, do if totalCost[i-1] ≠∞ and linCost[i, j] ≠ ∞ and (totalCost[i-1] + lineCost[i,j]Example
#includeusing namespace std; int dispSolution (int solution[], int size) { int k; if (solution[size] == 1) k = 1; else k = dispSolution (solution, solution[size]-1) + 1; cout = 0) lineCost[i][j] = 0; else lineCost[i][j] = extraSpace[i][j]*extraSpace[i][j]; } } totalCost[0] = 0; for (int j = 1; j Output
Line number 1: Word Number: 1 to 1 Line number 2: Word Number: 2 to 3 Line number 3: Word Number: 4 to 4
Advertisements
