กำหนดด้านของสี่เหลี่ยมในและช่วงตัวแปรก่อนและสุดท้าย เป้าหมายคือการหาจำนวนสี่เหลี่ยมที่มีอัตราส่วนของด้านยาว/ด้านกว้างอยู่ในช่วง [ ก่อน , สุดท้าย ]
ตัวอย่าง
อินพุต
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} แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในแนวทางนี้ เราจะเข้าข้างในรูปแบบของอาร์เรย์ของคู่
-
รับอาร์เรย์ rec[] ของ type pair
. -
หาตัวแปรสองตัวก่อนและตัวสุดท้ายเพื่อกำหนดช่วง
-
ฟังก์ชัน Ratio_sides(pair
rec[], int total, double first, double last) ใช้ด้านข้างของรูปสี่เหลี่ยมผืนผ้าและส่งกลับจำนวนรูปสี่เหลี่ยมผืนผ้าเพื่อให้อัตราส่วนของด้านอยู่ในช่วง [a,b] -
นับเริ่มต้นเป็น 0
-
ใช้ a for loop traverse จาก i=0 ถึง i
-
แยกค่าที่มากขึ้นในคู่ rec[i] เป็น maxi =max(rec[i].first, rec[i].second)
-
แยกค่าที่น้อยกว่าในคู่ rec[i] เป็น mini =min(rec[i].first, rec[i].second)
-
คำนวณหาค่าเฉลี่ย=maxi/mini
-
หากค่าเฉลี่ยมีค่าอยู่ในช่วง [ first,last ] ให้นับเพิ่ม
-
ในตอนท้ายของ for loop return นับเป็นผลลัพธ์..
ตัวอย่าง
#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