21 Matchsticks Problem
Last Updated :
22 Sep, 2022
Given 21 Matchsticks and 2 users, A and B (computer and user respectively). Users can pick matchsticks not more than four at a time. The one who is forced to pick the last matchstick loses.
Given an array arr[] which contains the moves of the computer. The task is to print the moves of the user so that the user wins the game.
Examples:
Input : N = 4, arr=[ 3, 4, 2, 2]
Output : 2, 1, 3, 3
When the computer chooses 3 sticks, the user chooses 2 sticks
When the computer chooses 4 sticks, the user chooses 1 stick
When the computer chooses 2 sticks, the user chooses 3 sticks
When the computer chooses 2 sticks, the user chooses 3 sticks
Now only 1 stick is left and the computer is forced to pick that stick
Hence the user wins the game.
Input : N = 4 arr=[ 1, 1, 4, 3]
Output : 4, 4, 1, 2
Approach:
- Idea is to think for 20 matchsticks as the user who would pick the last one will lose the game.
- Divide 20 into four parts that is, each part is of size 5. So if the computer picks x matchsticks then the user should pick (5-x) matchsticks and should proceed in the same way.
- In this way, 20 matchsticks will be used and the last matchstick would be picked by the computer.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
void TwentyoneMatchstick( int arr[], int N)
{
for ( int i = 0; i < N; i += 1) {
cout << 5 - arr[i] << " " ;
}
cout << endl;
}
int main()
{
int arr[] = { 3, 4, 2, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
TwentyoneMatchstick(arr, N);
return 0;
}
|
Java
class GFG
{
static void TwentyoneMatchstick( int arr[], int N)
{
for ( int i = 0 ; i < N; i += 1 )
{
System.out.print( 5 - arr[i] + " " );
}
System.out.println();
}
public static void main(String[] args)
{
int arr[] = { 3 , 4 , 2 , 2 };
int N = arr.length;
TwentyoneMatchstick(arr, N);
}
}
|
Python3
def TwentyoneMatchstick(arr, N):
for i in range (N):
print ( 5 - arr[i], end = " " )
arr = [ 3 , 4 , 2 , 2 ]
N = len (arr)
TwentyoneMatchstick(arr, N)
|
C#
using System;
class GFG
{
static void TwentyoneMatchstick( int []arr, int N)
{
for ( int i = 0; i < N; i += 1)
{
Console.Write(5 - arr[i] + " " );
}
Console.Write( "\n" );
}
public static void Main(String[] args)
{
int []arr = {3, 4, 2, 2};
int N = arr.Length;
TwentyoneMatchstick(arr, N);
}
}
|
Javascript
function TwentyoneMatchstick(arr, N)
{
for ( var i = 0; i < N; i += 1)
{
document.write(5 - arr[i] + " " );
}
document.write( "<br>" );
}
var arr = [3, 4, 2, 2];
var N = arr.length;
TwentyoneMatchstick(arr, N);
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...