ได้รับด้านของสี่เหลี่ยมผืนผ้าและตัวแปรช่วง first และ last เป้าหมายคือหาจำนวนสี่เหลี่ยมที่อัตราส่วนความยาว/ความกว้าง อยู่ในช่วง [first, last]
ตัวอย่าง
Input
rec[] = { { 200, 210 }, { 100, 50 }, { 300, 190}, {180, 200}, {300, 200}} and first = 1.0, last = 1.6
Output
Count of number of rectangles such that ratio of sides lies in the range [a,b] are: 4
Explanation
The sides that have ratio in the range [ 1.0,1.6 ] are : {200,210}, {300,190}, {180,200}, {300,200}
Input
rec[] = { { 10,20 }, { 30, 10 }, { 100, 500}, {900, 300}, {450, 90}} and first = 3.0, last = 4.0
Output
Count of number of rectangles such that ratio of sides lies in the range [a,b] are: 2
Explanation
The sides that have ratio in the range [ 3.0,4.0 ] are : {30,10}, {900,300}
วิธีการที่ใช้ในโปรแกรม
วิธีนี้เก็บด้านในรูปอาร์เรย์ของ pair<int,int> สำหรับแต่ละคู่ ตรวจสอบว่า ค่ามากกว่า/ค่าน้อยกว่า ให้ผลลัพธ์อยู่ในช่วง [first, last] ถ้าใช่ เพิ่มจำนวนนับ
- รับอาร์เรย์
rec[]ชนิดpair<int,int> - รับตัวแปร
firstและlastสำหรับกำหนดช่วง - ฟังก์ชัน
ratio_sides(pair<int, int> rec[], int total, double first, double last)คืนค่าจำนวนสี่เหลี่ยมที่อัตราส่วนอยู่ในช่วง - กำหนดจำนวนนับเริ่มต้นเป็น 0
- วนลูป i=0 ถึง total
- หาค่ามากกว่าในคู่:
maxi = max(rec[i].first, rec[i].second) - หาค่าน้อยกว่าในคู่:
mini = min(rec[i].first, rec[i].second) - คำนวณ
average = maxi/mini - ถ้า average อยู่ในช่วง [first, last] เพิ่ม count
- คืนค่า 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;
}
Output
หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:
Count the number of rectangles such that ratio of sides lies in the range [a,b] are: 4