Ways to place 4 items in n^2 positions such that no row/column contains more than one
Given an integer N where 4 ? N ? 100. There are N lines vertically and N lines horizontally. So, There are N2 intersections. The task is find the number of ways to place 4 items in these N2 positions such that each row and column contain not more than one item.
Examples:
Input: N = 4
Output: 24
Input: N = 5
Output: 600
Approach: The number of ways to choose 4 horizontal lines that will have items from n is nC4. There are n ways to place an item on the first of these lines. Given the place of the first item, there are n – 1 ways to place an item on the second of these lines because one of the vertical lines is already taken. Given the places of the first and second items, there are n – 2 ways to place an item on the third line and the same way n – 3 for the fourth item. The total number of ways to place items on selected 4 horizontal paths is n * (n – 1) * (n – 2) * (n – 3). So the result is nC4 * n * (n – 1) * (n – 2) * (n – 3).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long NumberofWays( int n)
{
long long x = (1LL * (n) * (n - 1) * (n - 2) * (n - 3))
/ (4 * 3 * 2 * 1);
long long y = (1LL * (n) * (n - 1) * (n - 2) * (n - 3));
return (1LL * x * y);
}
int main()
{
int n = 4;
cout << NumberofWays(n);
return 0;
}
|
Java
class GFG
{
static long NumberofWays( int n)
{
long x = (1l * (n) * (n - 1 ) * (n - 2 ) * (n - 3 ))
/ ( 4 * 3 * 2 * 1 );
long y = (1l * (n) * (n - 1 ) * (n - 2 ) * (n - 3 ));
return (1l * x * y);
}
public static void main(String args[])
{
int n = 4 ;
System.out.println( NumberofWays(n));
}
}
|
Python3
def NumbersofWays(n):
x = (n * (n - 1 ) * (n - 2 ) * (n - 3 )) / / ( 4 * 3 * 2 * 1 )
y = n * (n - 1 ) * (n - 2 ) * (n - 3 )
return x * y
n = 4
print (NumbersofWays(n))
|
C#
using System;
class GFG
{
public static long NumberofWays( int n)
{
long x = (1l * (n) * (n - 1) * (n - 2) *
(n - 3)) / (4 * 3 * 2 * 1);
long y = (1l * (n) * (n - 1) * (n - 2) *
(n - 3));
return (1l * x * y);
}
public static void Main( string [] args)
{
int n = 4;
Console.WriteLine(NumberofWays(n));
}
}
|
PHP
<?php
function NumberofWays( $n )
{
$x = (1 * ( $n ) * ( $n - 1) *
( $n - 2) * ( $n - 3)) /
(4 * 3 * 2 * 1);
$y = (1 * ( $n ) * ( $n - 1) *
( $n - 2) * ( $n - 3));
return (1 * $x * $y );
}
$n = 4;
echo NumberofWays( $n );
?>
|
Javascript
<script>
function NumberofWays(n) {
var x = (1 * n * (n - 1) * (n - 2) * (n - 3)) /
(4 * 3 * 2 * 1);
var y = 1 * n * (n - 1) * (n - 2) * (n - 3);
return 1 * x * y;
}
var n = 4;
document.write(NumberofWays(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...