Given an array of rods[] of size N and an integer value K (3 <= K <= 6), where rods[i] (1 <= rods[i] <= 108) is the length of the ith rod
(1 <= rods.length <= 10), the task is to check if it is possible to arrange all the rods to make a regular polygon of K sides without breaking any rod.
Examples:
Input: rods[] = {1, 1, 2, 2, 2}, k = 4
Output: trueInput: rods[] = {3, 3, 3, 3, 4}, k = 3
Output: false
Arrange rods to make K side Polygon using Backtracking:
Recursively explore different rod arrangements on each side while ensuring that the total length of rods is divisible by ‘k’. If a valid arrangement is found, print “true”; otherwise, print “false”
- Calculates the total length of all rods.
- Check if the total length is divisible by ‘k‘. If not, it’s impossible to form a polygon, so it prints “false” and exits.
- Sort the rods in descending order to optimize the algorithm. Sorting in this way ensures that longer rods are used first.
- Initializes an array subset[] to represent the current state of the ‘k‘ sides, all set to the required_length = sum of rods length / k.
- Call the solve() function to check if it’s possible to form a polygon. If it’s possible, it prints “true“; otherwise, it prints “false.”
-
The solve() function uses recursive backtracking to explore all possible ways of dividing the rods into ‘k‘ sides:
- Checks if all rods have been considered. If yes, it checks whether all ‘k‘ sides have a length of 0, which would mean a polygon can be formed.
- Iterates through each of the ‘k‘ sides and tries to place the current rod on them if the side can accommodate it.
- Recursively call itself with the updated state to explore further possibilities.
- If it finds a valid arrangement, it returns true. Otherwise, it backtracks by restoring the previous state and continues exploring other possibilities.
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std;
// Helper function to recursively check if it's // possible to make a Polygon or not Parameters: // - i: Current index in the array of rods. // - k: Side of Polygon // - subset: An array representing the current // state of the kth sides. // - s: The array of rods. bool solve( int i, int k, vector< int >& subset,
vector< int >& s)
{ // If we have considered all rods,
// check if all sides are of length 0
// (Polygon condition).
if (i == s.size()) {
for ( int len : subset) {
if (len != 0)
return false ;
}
return true ;
}
// Try to place the current rod on
// each of the k sides.
for ( int j = 0; j < k; j++) {
if (subset[j] < s[i])
continue ;
// Place the rod on one side and
// recursively check if it's possible
// to form a Polygon.
subset[j] -= s[i];
if (solve(i + 1, k, subset, s))
return true ;
// If not, backtrack by restoring the
// previous state.
subset[j] += s[i];
}
return false ;
} // Drivers code int main()
{ vector< int > rods = { 1, 1, 2, 2, 2 };
int k = 4;
// Calculate the sum of all rods.
int sum = accumulate(rods.begin(), rods.end(), 0);
// If the sum is not divisible by k, it's
// impossible to form a Polygon.
if (sum % k != 0) {
cout << " false ";
return 0;
}
// Calculate the required length for each
// side of the Polygon.
int required_len = sum / k;
// Sort the rods in descending order to
// optimize the algorithm.
sort(rods.begin(), rods.end(), greater< int >());
// Initialize an array to represent the
// current state of the k sides, all set
// to the required length.
vector< int > subset(k, required_len);
// Call the helper function to recursively
// check if a Polygon can be formed.
if (solve(0, k, subset, rods))
cout << " true ";
else
cout << " false ";
return 0;
} |
import java.util.ArrayList;
import java.util.Collections;
public class PolygonFormation {
// Helper function to recursively check if it's possible
// to form a Polygon.
public static boolean solve( int i, int k,
ArrayList<Integer> subset,
ArrayList<Integer> s)
{
// If all rods have been considered, check if all
// sides are of length 0 (Polygon condition).
if (i == s.size()) {
for ( int len : subset) {
if (len != 0 )
return false ;
}
return true ;
}
// Try to place the current rod on each of the k
// sides.
for ( int j = 0 ; j < k; j++) {
if (subset.get(j) < s.get(i))
continue ;
// Place the rod on one side and recursively
// check if it's possible to form a Polygon.
subset.set(j, subset.get(j) - s.get(i));
if (solve(i + 1 , k, subset, s))
return true ;
// If not, backtrack by restoring the previous
// state.
subset.set(j, subset.get(j) + s.get(i));
}
return false ;
}
public static void main(String[] args)
{
// Input: List of rods and the required number of
// sides for the Polygon (k).
ArrayList<Integer> rods = new ArrayList<>();
Collections.addAll(rods, 1 , 1 , 2 , 2 , 2 );
int k = 4 ;
// Calculate the sum of all rod lengths.
int sum = 0 ;
for ( int rod : rods) {
sum += rod;
}
// If the sum is not divisible by k, it's impossible
// to form a Polygon.
if (sum % k != 0 ) {
System.out.println( "false" );
return ;
}
// Calculate the required length for each side of
// the Polygon.
int requiredLen = sum / k;
// Sort the rods in descending order to optimize the
// algorithm.
Collections.sort(rods, Collections.reverseOrder());
// Initialize an ArrayList to represent the current
// state of the k sides, all set to the required
// length.
ArrayList<Integer> subset = new ArrayList<>();
for ( int i = 0 ; i < k; i++) {
subset.add(requiredLen);
}
// Call the helper function to recursively check if
// a Polygon can be formed.
if (solve( 0 , k, subset, rods))
System.out.println( "true" );
else
System.out.println( "false" );
}
} |
# Python code for the above approach # Helper function to recursively check if it's # possible to make a Polygon or not Parameters: # - i: Current index in the array of rods. # - k: Side of Polygon # - subset: An array representing the current # state of the kth sides. # - s: The array of rods. def solve(i, k, subset, s):
# If we have considered all rods,
# check if all sides are of length 0
# (Polygon condition).
if i = = len (s):
return all (length = = 0 for length in subset)
# Try to place the current rod on
# each of the k sides.
for j in range (k):
if subset[j] < s[i]:
continue
# Place the rod on one side and
# recursively check if it's possible
# to form a Polygon.
subset[j] - = s[i]
if solve(i + 1 , k, subset, s):
return True
# If not, backtrack by restoring the
# previous state.
subset[j] + = s[i]
return False
# Driver code rods = [ 1 , 1 , 2 , 2 , 2 ]
k = 4
# Calculate the sum of all rods. total_sum = sum (rods)
# If the sum is not divisible by k, it's # impossible to form a Polygon. if total_sum % k ! = 0 :
print ( "false" )
else :
# Calculate the required length for each
# side of the Polygon.
required_len = total_sum / / k
# Sort the rods in descending order to
# optimize the algorithm.
rods.sort(reverse = True )
# Initialize an array to represent the
# current state of the k sides, all set
# to the required length.
subset = [required_len] * k
# Call the helper function to recursively
# check if a Polygon can be formed.
if solve( 0 , k, subset, rods):
print ( "true" )
else :
print ( "false" )
# This code is contributed by Abhinav Mahajan (abhinav_m22) |
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass
{ // Helper function to recursively check if it's
// possible to make a Polygon or not.
// Parameters:
// - i: Current index in the array of rods.
// - k: Side of Polygon.
// - subset: An array representing the current
// state of the kth sides.
// - s: The array of rods.
public static bool Solve( int i, int k, List< int > subset, List< int > s)
{
// If we have considered all rods,
// check if all sides are of length 0
// (Polygon condition).
if (i == s.Count)
{
foreach ( int len in subset)
{
if (len != 0)
return false ;
}
return true ;
}
// Try to place the current rod on
// each of the k sides.
for ( int j = 0; j < k; j++)
{
if (subset[j] < s[i])
continue ;
// Place the rod on one side and
// recursively check if it's possible
// to form a Polygon.
subset[j] -= s[i];
if (Solve(i + 1, k, subset, s))
return true ;
// If not, backtrack by restoring the
// previous state.
subset[j] += s[i];
}
return false ;
}
// Driver code
public static void Main()
{
List< int > rods = new List< int > { 1, 1, 2, 2, 2 };
int k = 4;
// Calculate the sum of all rods.
int sum = rods.Sum();
// If the sum is not divisible by k, it's
// impossible to form a Polygon.
if (sum % k != 0)
{
Console.WriteLine( "false" );
return ;
}
// Calculate the required length for each
// side of the Polygon.
int requiredLen = sum / k;
// Sort the rods in descending order to
// optimize the algorithm.
rods.Sort((a, b) => b.CompareTo(a));
// Initialize an array to represent the
// current state of the k sides, all set
// to the required length.
List< int > subset = Enumerable.Repeat(requiredLen, k).ToList();
// Call the helper function to recursively
// check if a Polygon can be formed.
if (Solve(0, k, subset, rods))
Console.WriteLine( "true" );
else
Console.WriteLine( "false" );
}
} // This code is contributed by akshitaguprzj3 |
// Javascript Implementation // Helper function to recursively check if it's // possible to make a Polygon or not Parameters: // - i: Current index in the array of rods. // - k: Side of Polygon // - subset: An array representing the current // state of the kth sides. // - s: The array of rods. function solve(i, k, subset, s) {
// If we have considered all rods,
// check if all sides are of length 0
// (Polygon condition).
if (i === s.length) {
return subset.every(length => length === 0);
}
// Try to place the current rod on
// each of the k sides.
for (let j = 0; j < k; j++) {
if (subset[j] < s[i]) {
continue ;
}
// Place the rod on one side and
// recursively check if it's possible
// to form a Polygon.
subset[j] -= s[i];
if (solve(i + 1, k, subset, s)) {
return true ;
}
// If not, backtrack by restoring the
// previous state.
subset[j] += s[i];
}
return false ;
} // Driver code const rods = [1, 1, 2, 2, 2]; const k = 4; // Calculate the sum of all rods. const totalSum = rods.reduce((acc, rod) => acc + rod, 0); // If the sum is not divisible by k, it's // impossible to form a Polygon. if (totalSum % k !== 0) {
console.log( "false" );
} else {
// Calculate the required length for each
// side of the Polygon.
const requiredLen = totalSum / k;
// Sort the rods in descending order to
// optimize the algorithm.
rods.sort((a, b) => b - a);
// Initialize an array to represent the
// current state of the k sides, all set
// to the required length.
const subset = Array(k).fill(requiredLen);
// Call the helper function to recursively
// check if a Polygon can be formed.
if (solve(0, k, subset, rods)) {
console.log( "true" );
} else {
console.log( "false" );
}
} // This code is contributed by Sakshi |
true
Time Complexity: O(k^N), where ‘N’ is the number of rods and ‘k’ is the number of sides.
Auxiliary Space: O(N)