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
Find middle point segment from given segment lengths in C++
In this problem, we are given an array arr[] of size m representing the lengths of line segments.
The line segments are from 0 to arr[0] , arr[0] to arr[1] and so on. Our task is to find the segment which is at the middle of all segments.
Let’s take an example to understand the problem,
Input
arr[] = {5, 7, 13}
Output
3
Explanation
Segments are : (0, 5) , (5, 12), (12, 25)
Solution Approach
To solve the problem, we will find the middle point of the line by (arrSum/2). If this middle point is a starting or ending point of a line segment then print -1. Else, print the segment number.
Program to illustrate the working of our solution,
Example
#include <iostream>
using namespace std;
int findSegmentWithMidPoint(int n, int m, int segment_length[]) {
double centerPoint = (1.0 * n) / 2.0;
int sum = 0;
int segment = 0;
for (int i = 0; i < m; i++) {
sum += segment_length[i];
if ((double)sum == centerPoint) {
segment = -1;
break;
}
if (sum > centerPoint) {
segment = i + 1;
break;
}
}
return segment;
}
int main() {
int m = 3;
int segment_length[] = { 5, 7, 13 };
int arrSum = segment_length[0];
for(int i = 0; i < m; i++)
arrSum += segment_length[i];
int ans = findSegmentWithMidPoint(arrSum, m, segment_length);
cout<<"The segment number where middle point lies is "<<ans;
return 0;
}
Output
The segment number where middle point lies is 3
Advertisements