Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 변의 비율이 [a,b] 범위에 있도록 직사각형의 수를 센다.

<시간/>

주어진 사각형의 면과 범위 변수가 처음과 마지막에 있습니다. 목표는 [첫 번째, 마지막] 범위에 해당하는 변의 길이/너비 비율이 있는 직사각형의 개수를 찾는 것입니다.

예를 들어

입력

rec[] = { { 200, 210 }, { 100, 50 }, { 300, 190}, {180, 200}, {300, 200}} and first = 1.0, last = 1.6

출력

Count of number of rectangles such that ratio of sides lies in the range [a,b] are: 4

설명

The sides that have ratio in the range [ 1.0,1.6 ] are :
{200,210}, {300,190}, {180,200}, {300,200}

입력

rec[] = { { 10,20 }, { 30, 10 }, { 100, 500}, {900, 300}, {450, 90}} and
first = 3.0, last = 4.0

출력

Count of number of rectangles such that ratio of sides lies in the range [a,b]
are: 2

설명

The sides that have ratio in the range [ 3.0,4.0 ] are :
{30,10}, {900,300}

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다. -

이 접근 방식에서 우리는 pair의 배열 형태로 측면을 취할 것입니다. 각 쌍에 대해 더 큰 값/작은 값에 [ first, last ] 범위에 있는 결과가 있는지 확인합니다. 참이면 그러한 쌍의 수를 증가시킵니다.

  • 유형의 배열 rec[]를 사용합니다.

  • 범위를 정의하기 위해 처음과 마지막에 두 개의 변수를 사용합니다.

  • ratio_sides(pair rec[], int total, double first, double last) 함수는 직사각형의 변을 취하고 변의 비율이 [a,b] 범위에 있도록 직사각형의 개수를 반환합니다.

  • 초기 카운트를 0으로 합니다.

  • i=0에서 i까지 for 루프 트래버스 사용

  • maxi =max(rec[i].first, rec[i].second)로 rec[i] 쌍에서 더 큰 값을 추출합니다.

  • rec[i] 쌍에서 더 작은 값을 mini =min(rec[i].first, rec[i].second)로 추출합니다.

  • 평균=최대/최소를 계산합니다.

  • 평균의 값이 [ first, last ] 범위에 있으면 카운트를 증가시킵니다.

  • for 루프가 끝나면 결과로 count를 반환합니다.

예시

#include <bits/stdc++.h>
using namespace std;
int ratio_sides(pair<int, int> rec[], int total, double first, double last){
   int count = 0;
   for (int i = 0; i < total; i++){
      double maxi = max(rec[i].first, rec[i].second);
      double mini = min(rec[i].first, rec[i].second);
      double average = maxi/mini;
      if (average >= first){
         if(average <= last){
            count++;
         }
      }
   }
   return count;
}
int main(){
   pair<int, int> rec[] = { { 200, 210 }, { 100, 50 }, { 300, 190}, {180, 200}, {300, 200}};
   int total = 5;
   double first = 1.0, last = 1.6;
   cout<<"Count of number of rectangles such that ratio of sides lies in the range [a,b] are: "<<ratio_sides(rec, total, first, last);
   return 0;
}

출력

위의 코드를 실행하면 다음과 같은 출력이 생성됩니다 -

Count the number of rectangles such that ratio of sides lies in the range [a,b] are: 4