- Related Questions & Answers
- Maximum area of rectangle possible with given perimeter in C++
- Count number of squares in a rectangle in C++
- Count the number of rhombi possible inside a rectangle of given size in C++
- Find minimum area of rectangle with given set of coordinates in C++
- Tiling a Rectangle with the Fewest Squares in C++
- Sum of perimeter of all the squares in a rectangle using JavaScript
- Count of matrices (of different orders) with given number of elements in C++
- Count occurrences of the average of array elements with a given number in C++
- Count number of right triangles possible with a given perimeter in C++
- Coordinates of rectangle with given points lie inside in C++
- Maximum number of contiguous array elements with same number of set bits in C++
- Number of indexes with equal elements in given range in C++
- Count subarrays with equal number of occurrences of two given elements in C++
- Find minimum possible size of array with given rules for removing elements in C++
- Check if is possible to get given sum from a given set of elements in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given an array of N integers denoting the length of n sticks. Our task is to print the count of rectangles and squares that can be created from the sticks of the given length.

Let’s take an example to understand the problem

**Input **− array = {5, 5, 7, 7, 1, 4}

**Output **− 1

**Explanation **− a rectangle with sides 5 5 7 7.

To solve this problem, we will have to check if rectangles and squares are possible or not.

Now, for creating a square or rectangle, there should be two sticks of the same length, 2 for rectangle and 4 for square. Now, in our array, we will have to check for pairs of sticks of the same length. For making this search easy, we will sort the array and then find pairs and half of the total pair count will be the number of squares or rectangles that can be created.

Program to show the implementation of our solution,

#include <bits/stdc++.h> using namespace std; int countRecSqr(int sticks[], int n) { sort(sticks, sticks + n); int pairs = 0; for (int i = 0; i < n - 1; i++) { if (sticks[i]==sticks[i + 1]) { pairs++; i++; } } return pairs / 2; } int main() { int sticks[] = { 2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 }; int n = sizeof(sticks) / sizeof(sticks[0]); cout<<"The total number of squares or rectangles that can be created is "; cout<<countRecSqr(sticks, n); return 0; }

The total number of squares or rectangles that can be created is 3

Advertisements