Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count of lines required to write the given String in C++
We are given a string Str of alphabets and an array widths[]containing width of all English alphabets. The goal is to find the number of lines required to print this string on a page which has a width of 10 characters. Also print remaining characters.
We will traverse the string check width of the current character and add it, if this sum >=10 increment number of lines.
Let’s understand with examples.
Input
Str = "ababababab"
widths[] = {2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1};
Output
Count of lines: 2 Remaining width: 6
Explanation
line 1 : ababab ( 2+1+2+1+2+1 = 3+3+3=9) line 2 : abab (2+1+2+1)
Input
Str = "bbbbbbbbbbdd"
widths[] = {2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1};
Output
Count of lines: 2 Remaining width: 2
Explanation
line 1 : bbbbbbbbbb (1+1+1+1+1+1+1+1+1+1=10) line 2 : dd (1+1)
Approach used in the below program is as follows
We have a string Str and array widths[] of space of each alphabet.
Function numberOfLines(string str,int len, int w[]) displays number of lines in page and width of characters in the last line.
Take initial count of lines as numoflines=0.
Take initial last line width as remain=0
Traverse string str using for loop.
Take current character c as str[i].
Check width of c as num=width[c-’a’].
Add this num to remain.
If remain >=10 increment line count and update remain as num.
Print results at the end of for loop.
Example
#include <bits/stdc++.h>
using namespace std;
// Function to return the number of lines required
void numberOfLines(string str,int len, int w[]){
int numoflines = 0;
int remain = 0;
//traversing string
for (int i=0;i<len;i++){
char c=str[i]; //current character
int num = w[c - 'a']; //units for current character remain += num;
if (remain >= 10){
numoflines+=1;
remain = num;
}
}
cout<<"Count of lines: "<<numoflines;
cout<<endl<<"Remaining width: "<<remain;
}
int main(){
string Str = "abcdefghijklmnop";
int length=Str.length();
int widths[] = {2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1};
numberOfLines(Str,length,widths);
return 0;
}
Output
If we run the above code it will generate the following output −
Count of lines: 3 Remaining width: 1