Computer Science, asked by barinder2600065, 7 months ago

Street Lights
One of the streets in your city has a total of L street lights. Each light i covers the street from
Xi to Yi distance. Find the length of street covered with light.
Input Specification:
input1: L, denoting the number of street lights.
input2: An array of L* 2 elements. For each row i, (Xi, Yi) denote that the
street light i covers the distance from Xi to Yi.
Output Specification:
Your function should return the length of the street covered with light.
Example 1:
input1: 1,
input2: {{5,10 } }
Output: 5​

Answers

Answered by purohityash99
38

Answer:

import java.util.Scanner;

class main

{

   public static void main(String args[])

   {

       int [][] myarray = {{1,4},{7,10},{11,13},{16,17},{17,18}};

       int sum=0,diff=0;

       for(int i =0;i<myarray.length;i++){

           sum = sum +(myarray[i][1]-myarray[i][0]);

           if(i<myarray.length-1){

               if(myarray[i][1] > myarray[i+1][0] || (myarray[i][1] - myarray[i+1][0]) == -1){

                   diff = diff +(myarray[i][1] - myarray[i+1][0]);

               }

           }

       }

       System.out.println(sum-diff);

   }

}

Explanation:

Answered by dreamrob
9

Program in C++:

#include <bits/stdc++.h>

using namespace std;

int main()

{

int L;

cout<<"Enter total number of street lights : ";

cin>>L;

int A[L][2];

for(int i = 0; i < L; i++)

{

 cout<<"Light "<<i+1<<" covers the street from X"<<i+1<<" to Y"<<i+1<<". Please enter the value of X and Y : ";

 for(int j = 0 ; j < 2; j++)

 {

  cin>>A[i][j];

 }

}

int length = 0;

for(int i = 0; i < L; i++)

{

 int S = A[i][1] - A[i][0];

 length = length + S;

 if(A[i][1] > A[i+1][0] && i < L-1)

 {

  int C = A[i][1] - A[i+1][0];

  length = length - C;

 }

}

cout<<"Length of street = "<<length;

return 0;

}

Output 1:

Enter total number of street lights : 1

Light 1 covers the street from X1 to Y1. Please enter the value of X and Y : 5 10

Length of street = 5

Output 2:

Enter total number of street lights : 2

Light 1 covers the street from X1 to Y1. Please enter the value of X and Y : 5 10

Light 2 covers the street from X2 to Y2. Please enter the value of X and Y : 8 12

Length of street = 7

Similar questions